Book’s Bible: The Extension API Guide
Audience: AI agents and developers writing
.bk.ktsextension scripts for the Book agent. The guide was originally a single self-contained document; it is now split into per-topic pages. This landing page is self-contained for most extensions (execution model, imports, registration, worked examples, best practices). Read the topic pages for the complete API.Agent tip: read
docs/extend/extension-api-full.mdโ an auto-generated, single-file concatenation of all six pages, if you want the entire guide in one read. (Repository file, intentionally not a site page โ read it from the repo checkout.)
Topic pages: Context & State (
ExtensionContext,RunEnvironment, session state,tool { }) ยท Events (BookEvent,InterceptableEventreferences) ยท UI (ExtensionUI, observability samples, Sentinel) ยท Approval (opt-in tool gating) ยท Processes (non-blocking external processes)
Overview
The Book extension system lets you hook into the Book agent lifecycle via .bk.kts Kotlin Script files. Scripts are discovered automatically and evaluated at startup; the handlers and commands they register persist for the entire session lifetime.
Discovery
Book looks for .bk.kts files in:
-
~/.bk/tools/โ global extensions applied to every session -
.bk/tools/relative to the current working directory โ project-local extensions
All files with the .bk.kts suffix in these directories are loaded. Sub-directories are not searched.
Execution Model
-
Scripts are evaluated once at startup using the Kotlin scripting host.
-
All top-level statements in the script body execute immediately (e.g., variable initialisation).
-
registerEventHandler,registerInterceptor,registerCommand, andtoolcalls take effect immediately and remain registered for the session. -
tool {}registration is conditional: if thetool {}block is never called (e.g. guarded byif (rgPath != null) tool { … }), the tool is simply absent from the registry. The agent will not see or attempt to call it. -
Scripts run in background coroutines; startup is not blocked by slow script compilation.
-
A compilation error in one script is logged and skipped; other scripts continue loading normally.
Implicit Properties
Every .bk.kts script has the following top-level properties available without qualification:
| Property | Type | Description |
|---|---|---|
|
|
Access to |
|
|
Direct access to rich TUI extension interface ( |
|
|
Explicit alias for |
|
|
Framework-injected process runner. Use |
|
|
Path of the executing script file ( |
Classpath and Imports
The following packages are automatically available โ no import statements needed:
// โโ Domain model โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
us.nineworlds.book.domain.* // BookEvent, InterceptableEvent, ExtensionContext, etc.
us.nineworlds.book.domain.events.* // BookEvent subtypes, InterceptableEvent subtypes, result types
us.nineworlds.book.domain.extensions.ApprovalDecision // APPROVE, DENY, ALWAYS_APPROVE
us.nineworlds.book.domain.agentloop.RunEnvironment // Tui, Headless, Server โ see xref:api-context.adoc#_runenvironment_reference[ยง2a]
us.nineworlds.book.domain.messages.Content // Content sealed class (Text, Image)
us.nineworlds.book.domain.messages.Content.Text // Content.Text โ most common tool result type
us.nineworlds.book.domain.messages.Content.Image // Content.Image โ for tools returning images
us.nineworlds.book.domain.messages.AssistantContent // AssistantContent subtypes for observability
us.nineworlds.book.domain.messages.AssistantMessage // Full assistant message type
us.nineworlds.book.domain.messages.Message // Base message type
us.nineworlds.book.domain.tools.ToolResult // ToolResult(content, isError) โ structured tool returns
us.nineworlds.book.domain.tools.ToolSource // BUILTIN, EXTENSION, MCP โ tool origin tag
us.nineworlds.book.domain.process.ProcessRunner // Interface for running external processes
us.nineworlds.book.domain.process.ProcessEvent // Stdout, Stderr, Completed, Error events from processes
// โโ Serialization โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
kotlinx.serialization.json.* // Json, JsonObject, JsonArray, buildJsonObject, put, etc.
// โโ Coroutines โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
kotlinx.coroutines.flow.* // Flow, map, filter, toList, collect, etc.
// โโ Okio (filesystem & I/O) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
okio.FileSystem // Okio multiplatform filesystem
okio.Path // Okio path type
okio.Path.Companion.toPath // "some/path".toPath() extension
okio.buffer // .buffer() extension for Source/Sink
okio.use // .use {} extension for auto-close
okio.Sink // Write destination
okio.Source // Read source
The full application classpath is available, so you may also import any library already on the classpath (see ยง1a for details and @DependsOn usage).
Classpath, @DependsOn, and Mordant Access
What is already on the script classpath
Script compilation uses dependenciesFromCurrentContext(wholeClasspath = true). This puts the
entire Book fat-JAR classpath on every script’s compile-time and runtime classpath. Every
library Book depends on is available to scripts without any annotation:
| Library | Import prefix | Version |
|---|---|---|
Kotlin stdlib |
|
(matches runtime) |
Kotlinx Coroutines |
|
โ |
Kotlinx Serialization |
|
โ |
Okio |
|
โ |
Mordant (TUI) |
|
3.1.0 |
Klogging |
|
0.11.8 |
Declaring additional Maven dependencies with @DependsOn
If a script needs a library that is not on the Book classpath (e.g., an HTTP client, a
custom Mordant extension, or a domain-specific SDK), declare it with @DependsOn at the
top of the script file. The Kotlin scripting host resolves the dependency from Maven at
compile time using the configured MavenDependenciesResolver.
// Declare a custom Maven dependency (resolves at compile time)
@file:DependsOn("com.squareup.okhttp3:okhttp:4.12.0")
// Declare multiple dependencies
@file:DependsOn(
"com.squareup.okhttp3:okhttp:4.12.0",
"com.squareup.okhttp3:logging-interceptor:4.12.0"
)
To add a non-standard Maven repository:
@file:Repository("https://repo.example.com/maven")
@file:DependsOn("com.example:my-lib:1.0.0")
Important: @DependsOn / @Repository annotations must be at the very top of the
file, before any import statements or code. They are processed by the script compiler
before the rest of the file is evaluated.
Using Mordant directly in scripts
Mordant 3.1.0 is on the script classpath. Scripts can import and use Mordant types without
any @DependsOn annotation:
import com.github.ajalt.mordant.rendering.TextColors
import com.github.ajalt.mordant.rendering.TextStyle
import com.github.ajalt.mordant.widgets.Text
import com.github.ajalt.mordant.table.grid
The primary use case for Mordant in scripts is the TuiExtensionUI interface (see ยง3a โ Opt-in Tool Approval), which
allows scripts to push Mordant Widget instances into the Book agent’s TUI footer and header
regions.
Note: Direct Mordant use requires the Book TUI to be running. In scripts,
ui/tuiare already typed asTuiExtensionUI, and every rich-TUI method is a safe no-op in headless/ACP mode โ so scripts do not need to branch. If you need to check the environment explicitly, usectx.isHeadless(true for any non-TUI mode) orctx.environment. Full TUI contract (status bar, slot widgets, overlays, custom views, theme): api-ui.html.
Registration API
BookScriptReceiver is the implicit this of every .bk.kts script. Its four registration functions are directly in scope with no qualifier needed.
// Broadcast listener โ receives every matching event, return value ignored
registerEventHandler(BookEvent.SessionStart::class) { event, ctx ->
// `event` is typed as BookEvent.SessionStart
ctx.displayMessage("Started: ${event.reason}")
}
// Intercept handler โ must return the corresponding result type
registerInterceptor(UserBash::class) { event, ctx ->
// `event` is typed as UserBash
UserBashResult(block = false)
}
// Slash command โ invoked when user types /name [args] in the TUI
registerCommand("mycommand", "Does something useful") { args, ctx ->
ctx.displayMessage("mycommand called with: $args")
}
// Custom tool โ made available to the agent alongside built-in tools
tool {
name = "my_tool"
description = "Does something useful for the agent"
val input = string("input", "The input value")
execute { args ->
"Result: ${args[input]}"
}
}
There is no registry. qualifier, no string-key overload, and no Any-typed API. All types are resolved at KTS compile time, giving full IDE completion when editing in IntelliJ.
Theme & Rich UI Contract (Preview)
Extensions can access rich TUI features through TuiExtensionUI directly via ui or tui in .bk.kts scripts (or (ctx.ui as? TuiExtensionUI) in Kotlin extension classes) and the theme engine:
-
TuiExtensionUI: ExtendsExtensionUIwith rich TUI methods (setStatus,setWidget, working indicators,setTitle,setFooter, editor text,confirmTimed,overlay,customView). In scripts,BookScriptReceiver.uiandBookScriptReceiver.tuiexposeTuiExtensionUIwithout casting. Base five methods (notify,confirm,select,input,approveToolCall) are unchanged; new methods default to safe no-ops in headless or non-interactive mode. -
ThemeColor: Enum with 17 tokens across semantic (TOOL_TITLE,ACCENT,SUCCESS,ERROR,WARNING,MUTED,DIM,CUSTOM_MESSAGE_BG), diff (DIFF_ADDED,DIFF_REMOVED,DIFF_HUNK,DIFF_CONTEXT,DIFF_ADDED_BG,DIFF_REMOVED_BG), and gradient derivation (SECONDARY,BRONZE,EMBER). -
ShepherdTheme: The default theme engine implementingTuiTheme. Emits ANSI truecolor sequences for the Firefly palette and dynamically derives gradient tokens via RGB-lerp between anchor colors. -
Custom View Vocabulary:
-
UiSlot:HEADER,ABOVE_PROMPT,BELOW_PROMPT,FOOTER(four layout slots). -
OverlayOptions:anchor(CENTER),widthPercent,heightPercent,title. -
OverlayHandle: Controls overlay visibility (focus,unfocus,hide,show,close). -
CustomView<T>: Fun interfacecreate(controller: CustomViewController<T>): CustomComponent. -
CustomComponent: Fun interfacerender(width: Int): Widget. -
CustomViewController<T>: Exposes coroutinescope,eventsflow (KeyboardEvent),theme,finish(result),cancel(), andrequestRender(). '''
Command Registration Reference
registerCommand supports both simple function signature and builder DSL overloads:
// 1. Simple function signature
registerCommand(
name: String,
description: String? = null,
handler: suspend (args: String, ctx: ExtensionCommandContext) -> Unit
)
// 2. Builder DSL signature (supports argument autocomplete)
registerCommand(
name: String,
block: CommandBuilder.() -> Unit
)
Example using the builder DSL:
registerCommand("mycommand") {
description = "Command with dynamic argument completions"
handler { args, ctx ->
ctx.displayMessage("mycommand executed with: $args")
}
autocomplete { prefix, args ->
listOf(
CompletionItem("option1", label = "Option 1", description = "First argument choice"),
CompletionItem("option2", label = "Option 2", description = "Second argument choice")
)
}
}
-
Registers a
/nameslash command in the TUI. -
Commands are invoked when the user types
/name [args]at the input prompt. -
argsis everything after the command name (may be blank). -
ExtensionCommandContextextendsExtensionContextand addssuspend fun waitForIdle()โ lets the command wait for any running agent turn to finish before acting. -
Command names must be unique; a second
registerCommandwith the same name overwrites the first. -
Slash commands bypass the
InputReceivedinterceptor by design. '''
Complete Working Examples
session-logger.bk.kts
Logs key session lifecycle events.
registerEventHandler(BookEvent.SessionStart::class) { event, ctx ->
ctx.displayMessage("[Logger] Session started: ${event.reason}")
}
registerEventHandler(BookEvent.SessionShutdown::class) { event, ctx ->
ctx.displayMessage("[Logger] Session ended: ${event.reason}")
}
registerEventHandler(BookEvent.SessionCompact::class) { event, ctx ->
ctx.displayMessage("[Logger] Session compacted (fromExt=${event.fromExt})")
}
registerEventHandler(BookEvent.SessionTree::class) { event, ctx ->
ctx.displayMessage("[Logger] Branch created: ${event.newLeaf} from ${event.oldLeaf}")
}
tool-guard.bk.kts
Blocks dangerous shell commands via the UserBash interceptor.
val BLOCKED_PATTERNS = listOf("rm -rf", "sudo rm", "> /dev/", "dd if=")
registerInterceptor(UserBash::class) { event, ctx ->
val isDangerous = BLOCKED_PATTERNS.any { event.command.contains(it) }
if (isDangerous) {
ctx.ui.notify("Blocked dangerous command: ${event.command}", "warn")
UserBashResult(block = true, reason = "Matched dangerous pattern")
} else {
UserBashResult(block = false)
}
}
prompt-injector.bk.kts
Appends custom rules to the system prompt (which may already include content from SYSTEM.md files).
registerInterceptor(BeforeAgentStart::class) { event, ctx ->
// event.systemPrompt already contains merged content from:
// ~/.bk/SYSTEM.md, .bk/SYSTEM.md, and any CLI flags
AgentStartResult(
systemPrompt = event.systemPrompt + """
## Custom Rules (injected by extension)
- Always end responses with a confidence score (0โ100%).
- Prefer concise answers under 3 paragraphs.
""".trimIndent()
)
}
model-tracker.bk.kts
Persists model-change events to the session.
registerEventHandler(BookEvent.ModelSelected::class) { event, ctx ->
val entry = buildJsonObject {
put("from", event.prevId ?: "none")
put("to", event.modelId)
put("source", event.source)
}
ctx.sessionManager.appendEntry("myext.model_switch", entry)
ctx.displayMessage("[Tracker] Model changed: ${event.prevId} โ ${event.modelId}")
}
registerEventHandler(BookEvent.SessionStart::class) { event, ctx ->
ctx.displayMessage("[Tracker] Session started: ${ctx.sessionManager.getSessionId()}")
}
stateful-counter.bk.kts
Counts tool executions for the current runtime and persists markers to the session log.
var callCount = 0
registerEventHandler(BookEvent.SessionStart::class) { _, ctx ->
callCount = 0
ctx.displayMessage("[Counter] Counter reset for runtime; markers continue in session log")
}
registerEventHandler(BookEvent.ToolExecutionEnd::class) { event, ctx ->
callCount++
ctx.sessionManager.appendEntry("myext.tool_call_count", buildJsonObject { put("tool", event.name) })
}
registerEventHandler(BookEvent.SessionShutdown::class) { _, ctx ->
ctx.displayMessage("[Counter] Total tool calls this session: $callCount")
}
cost-tracker.bk.kts
Logs per-turn token usage and cost, then prints a run-total at agent end.
// cost-tracker.bk.kts
// Reads usage.cost.total and usage.totalTokens from every TurnEnd event,
// then summarises the full run in the AgentEnd handler.
var runInputTokens = 0L
var runOutputTokens = 0L
var runCacheRead = 0L
var runCacheWrite = 0L
var runCostTotal = 0.0
registerEventHandler(BookEvent.AgentStart::class) { _, _ ->
// Reset accumulators at the start of each agent run
runInputTokens = 0L
runOutputTokens = 0L
runCacheRead = 0L
runCacheWrite = 0L
runCostTotal = 0.0
}
registerEventHandler(BookEvent.TurnEnd::class) { event, ctx ->
val u = event.message.usage
runInputTokens += u.input
runOutputTokens += u.output
runCacheRead += u.cacheRead
runCacheWrite += u.cacheWrite
runCostTotal += u.cost.total
ctx.displayMessage(
"[Cost] turn=${event.index} in=${u.input} out=${u.output} " +
"cost=\$${"%.6f".format(u.cost.total)}"
)
}
registerEventHandler(BookEvent.AgentEnd::class) { _, ctx ->
ctx.displayMessage(
"[Cost] run total โ in=$runInputTokens out=$runOutputTokens " +
"cacheRead=$runCacheRead cacheWrite=$runCacheWrite " +
"cost=\$${"%.6f".format(runCostTotal)}"
)
}
custom-commands.bk.kts
Registers custom slash commands.
registerCommand("hello", "Prints a greeting") { args, ctx ->
val name = args.ifBlank { "world" }
ctx.displayMessage("[hello] Hello, $name!")
}
registerCommand("tools-summary", "Shows current session metadata") { _, ctx ->
val name = ctx.sessionManager.getSessionName() ?: "unnamed"
ctx.displayMessage("[tools-summary] session=${ctx.sessionManager.getSessionId()} name=$name")
}
custom-tool.bk.kts
Registers two custom tools available to the agent.
tool {
name = "word_count"
description = "Counts the number of words in the provided text"
val text = string("text", "The text to count words in")
execute { args ->
val count = args[text].trim().split(Regex("\\s+")).filter { it.isNotEmpty() }.size
"$count word(s)"
}
}
tool {
name = "repeat_text"
description = "Repeats the given text N times"
val text = string("text", "The text to repeat")
val times = integer("times", "How many times to repeat (1โ20)")
execute { args ->
val n = args[times].coerceIn(1, 20)
(1..n).joinToString("\n") { args[text] }
}
}
Extension Best Practices
DO:
-
Use
ctx.displayMessage()for all user-visible output -
Use
noCoLoggerfor diagnostic or background logging toq.log -
Handle exceptions inside your handler body โ don’t let them propagate
-
Use
cancel = truein intercept results only when genuinely necessary -
Namespace your session entry types:
"myext.counter"not"counter" -
Use
ctx.ui.notify(โฆ)for non-blocking status messages -
Keep script-level variable initialisation fast (it blocks script evaluation)
-
Give tools clear, specific
descriptionstrings โ the LLM uses them to decide when to call the tool -
Use
required = falsefor optional tool parameters and handle the zero/empty/false defaults gracefully
DON’T:
-
Use
block = trueon tool calls without providing a visiblereason -
Store large objects in session entries (keep to IDs and scalar values)
-
Perform long-running synchronous I/O directly in broadcast handlers
-
Register the same command name more than once (second registration silently overwrites the first)
-
Register a tool with the same name as a built-in tool unless you intend to override it
-
Rely on handler execution order across scripts (order is load order, implementation detail) '''
Error Handling
| Scenario | Behaviour |
|---|---|
Exception in a broadcast handler |
Caught, logged to |
Exception in an interceptor handler |
Caught, logged to |
Exception thrown inside a |
Propagated as a |
|
|
|
|
Script compilation error |
Logged to |
Missing |
No error; the event just has no extension handler |
Check q.log (in the project root) for handler error output. Error lines include the event class name and the full stack trace.
Fail-open guarantee: Every intercept path in Book is designed to fail-open. If your interceptor throws or is absent, the operation proceeds normally. This means a badly-written extension cannot accidentally break the agent โ it may just silently have no effect.