Book’s extension system lets you add tools, slash commands, and event handlers without recompiling. It runs on Kotlin Scripting.

What You Can Build

Extensions can enhance Book in several ways:

  • Custom Agent Tools: Define new capabilities via tool { …​ } that the LLM can call during turns.

  • Slash Commands: Register custom /command shortcuts for interactive user workflows.

  • Event Observers & Interceptors: Intercept or monitor system events (session start/shutdown, tool calls, bash commands).

  • Custom Tool, Entry & Message Renderers: Register custom renderers (ToolRenderer, EntryRenderer, MessageRenderer) for tool calls/results, custom entries, and LLM custom messages with failure-safe fallback.

  • Markdown Transformer Chains: Intercept and transform markdown content pre-widget build in registration order with failure isolation.

  • Themed Tool & Entry Rendering: Style custom outputs using TuiTheme and the 17-token ThemeColor palette.

  • Status-Bar Widgets & Layout Slots: Inject dynamic widgets into UiSlot positions (HEADER, ABOVE_PROMPT, BELOW_PROMPT, FOOTER) or update working indicators.

  • Custom Interactive Views & Modal Overlays: Present full-screen interactive views or anchored modal overlay dialogs using customView and overlay.

  • Timed Confirmation Dialogs: Prompt users with timeout-backed decisions via confirmTimed.

  • Keyboard Focus Capture & Buffer Preservation: Receive keyboard event streams in focused custom views with automatic input buffer save/restore semantics.

  • Keyboard Shortcuts & Key Handling: Receive and react to terminal KeyboardEvent streams inside focused custom views or globally via registerShortcut.

  • Argument & File Completions: Provide interactive tab-completion items for slash commands and custom prompt tokens.

  • Slash Command Argument Completions: Provide dynamic argument completion items for extension slash commands via autocomplete { prefix, args → …​ }.

  • Custom Footer & Terminal Title Control: Customize the TUI footer via setFooter and update the terminal window title via setTitle.

  • Programmatic Editor Text Control: Read, prefill, and append text in the prompt input buffer via setEditorText, getEditorText, and pasteToEditor.

API Reference โ€” this page covers script placement, bundled scripts, and quick-start examples. The full API lives in the split Extension API Guide: "Context, State & Tools" ยท Events ยท "UI, Observability & Sentinel" ยท Opt-in Tool Approval ยท External Processes

Where to Place Scripts

Book looks for scripts ending in .bk.kts in the following locations:

  1. ~/.bk/tools/ (Global extensions)

  2. ./.bk/tools/ (Project-specific extensions)

Bundled Extensions

The :extensions module ships ready-to-use scripts in extensions/src/scripts/:

Script Provides Notes

ripgrep.bk.kts

ripgrep tool + /rg-status command

Requires rg in PATH; tool auto-disabled when not installed

tool_approval.bk.kts

Interactive tool-approval gate

Opt-in; install in ~/.bk/tools/ to enable

session-playback-server.bk.kts

/debug-session-start [port] and /debug-session-stop commands

Requires Python 3 in PATH; ships alongside session-player.html in .bk/tools/

firstmate.bk.kts

FirstMate harness adapter

Integrates Book with FirstMate agent orchestration

herdr.bk.kts

Herdr terminal multiplexer control

Pane and workspace management commands

Copy any bundled script to ~/.bk/tools/ or .bk/tools/ to activate it.

Session Playback Server (session-playback-server.bk.kts)

This script provides a browser-based visual replayer for any Book session JSONL file. It is useful for debugging multi-turn agent runs, preparing demos, and reviewing tool-call sequences offline.

Commands registered:

Command Description

/debug-session-start [port]

Start a local HTTP server on localhost:<port> (default 8080) and open the session player in your browser. Serves the current session’s JSONL file alongside session-player.html.

/debug-session-stop

Stop the running HTTP server and free the port.

Requirements: Python 3 must be on your PATH (used to serve static files via python3 -m http.server). The script itself requires no additional dependencies.

How it works: On /debug-session-start, the script resolves the current session JSONL path from ctx.sessionManager, copies session-player.html next to it, and launches python3 -m http.server <port> in a background thread. The server URL is printed to the TUI; navigating to it in a browser loads the player which reads the JSONL and renders a turn-by-turn replay with collapsible tool calls.

Tip: Headless (-p) sessions are also persisted to ~/.bk/agent/sessions/ and can be replayed the same way โ€” start Book interactively, run /debug-session-start, and navigate to the session file you want to inspect.

Session Observability Samples

Three session-focused observability samples are available in samples/:

  • session-lifecycle-jsonl.bk.kts: writes session lifecycle events (session.start, session.compact, session.tree, session.shutdown) to ~/.bk/observability/session_lifecycle.jsonl.

  • tool-execution-observability-jsonl.bk.kts: writes per-tool latency/error telemetry to ~/.bk/observability/tool_execution.jsonl.

  • turn-summary-observability-jsonl.bk.kts: writes per-turn rollups (duration, tool count, assistant text size) to ~/.bk/observability/turn_summary.jsonl.

These samples use a buildlog.ai-inspired JSONL envelope (spec, event, ts, session_id, etc.) so logs are easy to parse with jq, Python, or ingestion pipelines.


Defining a New Tool

You can create custom tools that the agent can use to interact with your environment.

Sample: weather.bk.kts

tool {
    name = "get_weather"
    description = "Fetches the current weather for a given city."

    // Define inputs using the DSL
    val city = string("city", "The name of the city")

    execute {
        val cityName = it[city]
        // In a real script, you'd call an API here
        "The weather in $cityName is sunny, 22ยฐC."
    }
}

Defining Parameters

Tools define their input schema using helper functions within the tool block. This information is used to generate the JSON Schema that the LLM uses to understand how to call your tool.

  • string(name, description, required): Defines a string parameter.

  • integer(name, description, required): Defines an integer parameter.

  • boolean(name, description, required): Defines a boolean parameter.

By default, parameters are required = true.

Accessing Arguments

Inside the execute block, you can access the values passed by the agent using the it object (which is a JsonObject) and the parameter keys you defined.

tool {
    name = "calculate"
    val a = integer("a", "First number")
    val b = integer("b", "Second number")
    val op = string("operation", "add, sub, mul, or div")

    execute { args ->
        val valA = args[a]
        val valB = args[b]
        when (args[op]) {
            "add" -> valA + valB
            // ...
            else -> "Unknown operation"
        }
    }
}

Returning Results

The execute block can return:

  1. A String: It will be automatically wrapped in a ToolResult as text.

  2. Any Object: Its toString() representation will be used as the result text.

  3. A ToolResult: For advanced use cases where you want to return multiple content items (like text and images) or mark the result as an error. '''

Adding Slash Commands

Slash commands allow you to trigger custom logic directly from the TUI.

Sample: timer.bk.kts

registerCommand(
    name = "timer",
    description = "Starts a countdown timer."
) { args, ctx ->
    val seconds = args.trim().toIntOrNull() ?: 5
    println("Starting $seconds second timer...")
    java.lang.Thread.sleep(seconds * 1000L)
    println("Time is up!")
}

Reacting to Events

You can hook into system events to perform logging, auditing, or custom automation.

Sample: logger.bk.kts

registerEventHandler(BookEvent.SessionStart::class) { event, ctx ->
    ctx.displayMessage("New mission started in: ${ctx.cwd}")
}

registerEventHandler(BookEvent.ToolExecutionEnd::class) { event, ctx ->
    ctx.displayMessage("Tool execution completed: ${event.name}")
}

Available Broadcast Events (BookEvent)

Event Class Description

BookEvent.SessionStart

Fired when a new session begins or on startup.

BookEvent.SessionShutdown

Fired when the session ends.

BookEvent.AgentStart

Fired when the agent begins a processing turn.

BookEvent.AgentEnd

Fired when the agent completes its run.

BookEvent.TurnStart

Fired at the beginning of each agent turn.

BookEvent.TurnEnd

Fired at the end of each agent turn.

BookEvent.ToolExecutionStart

Fired before a tool is executed.

BookEvent.ToolExecutionEnd

Fired after a tool has finished executing.

BookEvent.ModelSelected

Fired when the active LLM model is switched.


Contributing to the TUI

Extensions can interact with the TUI in several ways:

1. Slash Commands

As shown above, registerCommand allows you to add new / commands. These commands can output text directly to the terminal using ctx.displayMessage(text).

2. Custom Tools

Tools you define via tool { …​ } are naturally integrated into the TUI. Their outputs are rendered as part of the agent’s turn.

3. Displaying Messages

Both ExtensionContext and ExtensionCommandContext provide a displayMessage(String) function. This allows your event handlers or commands to push information to the user’s view.

registerEventHandler(BookEvent.ToolExecutionStart::class) { event, ctx ->
    ctx.displayMessage("๐Ÿš€ Starting tool: ${event.name}")
}

4. Keyboard Shortcuts

Register global keyboard shortcuts with registerShortcut(key, description) { ctx → …​ } โ€” e.g. registerShortcut("ctrl+shift+p", "My panel") { …​ }. Core navigation keys always take precedence over extension bindings. See api-ui.html.

5. Slash Command Argument Completions

Slash commands registered with registerCommand(name) { …​ } can supply dynamic argument completions via autocomplete { prefix, args → …​ }, returning CompletionItem(value, label, description) entries merged into the TUI suggestion row.

6. TUI Widgets, Custom Views & Overlays (requires TUI mode)

In interactive TUI mode, ui is typed as TuiExtensionUI, giving scripts the full Mordant 3.1.x widget surface:

// Status bar items (text, Mordant Widget, or StateFlow<Widget>)
ui.setStatus("git_branch", "git: main")

// Slot widgets re-rendered on terminal resize
ui.setWidget(UiSlot.HEADER, "banner") { width -> Text("My Banner".take(width)) }

// Full-screen interactive view โ€” suspends until finish/cancel
val picked = ui.customView { controller ->
    controller.scope.launch {
        controller.events.collect { if (it is Key.Escape) controller.cancel() }
    }
    object : CustomComponent {
        override fun render(width: Int) = Text("Pick something, Esc to cancel")
    }
}

// Modal anchored overlay (FIFO queue, single focus owner)
val decision = ui.overlay(OverlayOptions(anchor = Anchor.CENTER)) { controller ->
    object : CustomComponent {
        override fun render(width: Int) = Text("Confirm? Esc to cancel")
    }
}

// Timed confirmation
val ok = ui.confirmTimed("Deploy now?", 10.seconds, default = false)

All of these are no-op safe in headless / ACP server mode โ€” no branching on isHeadless required. Full contract, OverlayOptions, OverlayHandle, theme tokens and worked examples: api-ui.html.

7. Editor Manipulation

ui.setEditorText(text), ui.getEditorText(), and ui.pasteToEditor(text) let scripts read and write the TUI input buffer programmatically (large pastes are auto-collapsed).

Extension Architecture

The following diagram illustrates how Book discovers and loads extensions at startup.

Diagram

The Extension DSL (ExtensionAPI)

The following functions are available in the top-level scope of your .bk.kts scripts:

  • tool { …​ }: Builder for creating Agent tools. May be called conditionally โ€” if not called, the tool is not registered.

  • registerCommand(name, description, handler): Register a TUI slash command.

  • registerEventHandler(eventClass, handler): Register a broadcast listener for a BookEvent subtype.

  • registerInterceptor(eventClass, handler): Register an interceptor for an InterceptableEvent subtype.

Available Contexts and Properties:

  • ctx: The top-level ExtensionContext. Provides cwd, sessionManager, ui, isHeadless, and displayMessage().

  • processRunner: A ProcessRunner instance injected by the framework. Use this to launch external processes without blocking the agent UI. See the Extension API ยง10 for the correct coroutine pattern.

  • scriptPath: An okio.Path representing the file path of the current .bk.kts script (provided on BookScriptReceiver, replacing System.getProperty("book.script.path")).

  • ExtensionCommandContext: Extends ExtensionContext with a waitForIdle() function to wait for the agent to finish its current turn.

Conditional Tool Registration

You can guard tool { } registration with any runtime condition โ€” for example, checking whether an external binary is installed:

val rgPath: String? = try {
    val p = ProcessBuilder("which", "rg").start()
    val r = p.inputStream.bufferedReader().readText().trim()
    p.errorStream.bufferedReader().readText()
    if (p.waitFor(5, java.util.concurrent.TimeUnit.SECONDS) && p.exitValue() == 0 && r.isNotEmpty()) r else null
} catch (_: Exception) { null }

if (rgPath != null) tool {
    name = "ripgrep"
    // ...
}

If the condition is false, tool {} is never called and the tool is absent from the registry โ€” the agent will not see or attempt to use it.

IDE Setup โ€” configuring IntelliJ IDEA for .bk.kts authoring (script resolution, SDK) moved to ide-setup.html.

Headless Extension Loading & Harness Integration

Headless Extension Execution

Extensions are fully loaded and evaluated in headless mode (-p / --prompt or non-interactive runs) via HeadlessRunner. Event handlers, interceptors, and tools defined in .bk.kts scripts execute normally, so CI runs, automated tests, and agent orchestration pipelines can use custom extension logic.

FirstMate & Herdr Integration

The :extensions module provides bundled scripts for integrating Book with FirstMate (firstmate.bk.kts) and controlling the Herdr terminal multiplexer (herdr.bk.kts).

Environment Marker (BOOK_FLEET=1)

Every child process spawned by Book (including tools, subprocesses, and custom script process runners) automatically observes BOOK_FLEET=1 in its environment (unless already set by the parent). This enables safe nesting detection and fleet orchestration.

Sentinel Extension Pattern (SPEC-04)

Extensions can use turn-end sentinel files (e.g., .fm-bk-turnend) to signal agent turn completion to external orchestrators without parsing raw output streams.


Available Libraries and Imports

Book scripts have access to the full :infrastructure classpath. The following libraries are imported by default:

Default Imports

The following packages are available without any import statement:

  • us.nineworlds.book.domain.*: Access to core abstractions like Agent and AppScope.

  • us.nineworlds.book.domain.tools.*: Access to Tool, ToolRegistry, and the tool DSL.

  • us.nineworlds.book.domain.messages.*: Message types like Message, UserMessage, AssistantMessage.

  • us.nineworlds.book.domain.commands.*: Command and CommandResult types.

  • us.nineworlds.book.domain.extensions.*: Extension system types.

  • us.nineworlds.book.domain.events.*: Event system including BookEvent and InterceptableEvent.

  • us.nineworlds.book.domain.process.*: ProcessRunner interface and ProcessEvent sealed class (Stdout, Stderr, Completed, Error). The processRunner top-level property is also available directly โ€” no import needed.

  • kotlinx.serialization.json.*: Classes like JsonObject, JsonPrimitive, and buildJsonObject.

Available Libraries

You can import and use any of the following standard project dependencies:

Library Key Packages Use Case

Kotlin Standard Library (2.4.20)

kotlin.*

Core language features.

KotlinX Serialization

kotlinx.serialization.*

Parsing and generating JSON.

KotlinX Coroutines

kotlinx.coroutines.*

Asynchronous operations and delays.

Okio

okio.*

File I/O and buffering.

Klogging

io.klogging.*

Structured logging (use noCoLogger).

Ktor Client

io.ktor.client.*

Making HTTP/REST requests.

Koog DSL

ai.koog.prompt.dsl.*

Building complex prompts (if needed in scripts).

Kotlin Diff Utils

dev.gitlive.difflib.*

Calculating text differences.


Dynamic Dependencies (@file:DependsOn)

If you need a library that isn’t pre-bundled with Book, you can pull it in dynamically from Maven Central using the @file:DependsOn annotation at the very top of your script.

Using Maven Artifacts

@file:DependsOn("org.jetbrains.kotlinx:kotlinx-html-jvm:0.11.0")

import kotlinx.html.*
import kotlinx.html.stream.createHTML

tool {
    name = "generate_report"
    execute {
        createHTML().html {
            body {
                h1 { +"Agent Execution Report" }
            }
        }
    }
}

Adding Custom Repositories

If the library is hosted on a custom Maven repository, use @file:Repository:

@file:Repository("https://maven.pkg.jetbrains.space/public/p/compose/dev")
@file:DependsOn("org.jetbrains.compose.runtime:runtime:1.6.0")

Advanced Sample: A "Web Search" Tool

This tool demonstrates how to use kotlinx.serialization (which is imported by default) and external Java/Kotlin APIs.

import java.net.URL

tool {
    name = "google_search"
    description = "Performs a simple Google search and returns the top results."

    val query = string("query", "The search terms")

    execute {
        val q = it[query]
        val results = URL("https://www.google.com/search?q=$q").readText()
        // Extract links or text from the HTML...
        "Found results for: $q"
    }
}