Part of the Extension API Guide. Complete references for broadcast BookEvent types and InterceptableEvent types.

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

cwd

String

Current working directory

reason

String

Always "startup" in current implementation

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

reason

String

"new", "resume", or other startup reason

prevSession

String?

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

entry

CompactionEntry

The compaction entry written to the session

fromExt

Boolean

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

newLeaf

String

Session file path of the new branch

oldLeaf

String

Session file path of the parent branch

summary

String

Summary text stored at the branch point

fromExt

Boolean

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

reason

String

"ctrl_c", "ctrl_d", or other shutdown reason

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

messages

List<Message>

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

index

Int

0-based turn index within the current run

timestamp

Long

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

index

Int

0-based turn index

message

AssistantMessage

The assistant message produced this turn

results

List<ToolResultMessage>

Tool results collected during this turn

event.message.usage is a Usage value containing:

Usage field Type Description

input

Long

Input tokens consumed this turn

output

Long

Output tokens produced this turn

cacheRead

Long

Tokens served from the provider cache

cacheWrite

Long

Tokens written into the provider cache (serialized as cacheCreation in JSONL)

totalTokens

Long

Sum of all token fields

cost

Cost

Computed cost breakdown

usage.cost is a Cost value containing:

Cost field Type Description

input

Double

Cost for input tokens (USD)

output

Double

Cost for output tokens (USD)

cacheRead

Double

Cost for cache-read tokens (USD)

cacheWrite

Double

Cost for cache-creation tokens (USD)

total

Double

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

message

Message

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

message

Message

The partially-built message so far

streamEvent

StreamEvent

Either StreamEvent.TextDelta(delta) or StreamEvent.ThinkingDelta(delta)

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

id

String

Unique tool call ID for this invocation

name

String

Tool name (e.g., "bash", "read_file")

args

JsonObject

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

id

String

Tool call ID

name

String

Tool name

args

JsonObject

Arguments

partial

String

Partial output so far


BookEvent.ToolExecutionEnd

Fires when a tool finishes executing.

Field Type Description

id

String

Tool call ID

name

String

Tool name

result

String

Full output text

isError

Boolean

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

status

Int

HTTP status code (always 200 in current Koog abstraction)

headers

Map<String, String>

Response headers (empty in current Koog abstraction)


BookEvent.ModelSelected

Fires when the active LLM model is changed.

Field Type Description

modelId

String

The new model identifier

prevId

String?

The previous model identifier, or null if first selection

source

String

Who changed the model: "user", "extension", etc.

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

level

String

New thinking level identifier

prevLevel

String?

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

reason

String

Why the switch was requested

targetSessionFile

String?

Target session path, or null for a new session

Result Field Default Controls

cancel

false

Set true to abort the switch

registerInterceptor(BeforeSwitch::class) { event, ctx ->
    SwitchResult(cancel = false) // allow
}

BeforeFork

Fires before creating a branch (fork) in the session tree.

Payload Field Type Description

entryId

String

ID of the session entry being forked from

position

Int

Position in the session at which to fork

Result Field Default Controls

cancel

false

Set true to abort the fork


BeforeCompact

Fires before a session compaction.

Payload Field Type Description

preparation

CompactionPreparation

sessionFile: String, entryCount: Int

Result Field Default Controls

cancel

false

Set true to abort compaction


BeforeTree

Fires before the tree selector UI is displayed.

Payload Field Type Description

preparation

TreePreparation

sessionFile: String, leafCount: Int

Result Field Default Controls

cancel

false

Set true to abort showing the tree selector


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

prompt

String

The user’s input text

systemPrompt

String

Current system prompt (merged from SYSTEM.md files and CLI flags)

systemPromptOptions

JsonObject

Additional system prompt options

Result Field Default Controls

message

null

If non-null, inject a custom JsonObject as the first message

systemPrompt

null

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:

  1. ~/.bk/SYSTEM.md content (if exists, auto-discovered)

  2. .bk/SYSTEM.md content (if exists, auto-discovered)

  3. --system-prompt FILE CLI flag (if provided, replaces steps 1-2)

  4. --system-prompt-append FILE CLI flag (if provided, appends to previous steps)

  5. 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

message

Message

The completed message

Result Field Default Controls

message

null

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

toolName

String

Name of the tool being called

toolCallId

String

Unique call ID

input

JsonObject

Arguments provided to the tool

Result Field Default Controls

block

false

Set true to prevent execution

reason

null

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

toolName

String

Name of the tool

toolCallId

String

Unique call ID

content

String

Raw output from the tool

details

JsonObject?

Extra structured output, or null

isError

Boolean

Whether the tool reported an error

Result Field Default Controls

content

null

Override the content string (null = keep original)

isError

null

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

messages

List<Message>

The full message list to be sent

Result Field Default Controls

messages

null

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

payload

JsonObject

The raw provider API request payload

Result Field Default Controls

payload

null

Replacement payload (null = use original)


UserBash

Fires before BashTool executes a shell command. Lets you block or modify the command.

Payload Field Type Description

command

String

The command string to execute

exclude

List<String>

Excluded patterns (from config)

cwd

String

Working directory for the command

Result Field Default Controls

block

false

Set true to prevent execution

reason

null

Reason string logged and returned as error output

command

null

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

text

String

The raw input text

source

String

Always "keyboard" in current implementation

Result Field Default Controls

text

null

Override the input text (null = use original)

cancel

false

Set true to discard the input entirely

registerInterceptor(InputReceived::class) { event, ctx ->
    // Auto-expand shorthand
    val expanded = event.text.replace("!fix", "Please fix the last error.")
    InputResult(text = expanded)
}