Part of the Extension API Guide. TUI interaction via ExtensionUI, session observability samples, and the Sentinel (SPEC-04) pattern.

ExtensionUI Reference

Accessed via ctx.ui. Provides interactive prompts that render in the TUI.

interface ExtensionUI {
    /** Display a notification banner.
     *  @param level One of "info" (default), "warn", or "error".
     *  Any unrecognised level renders as "info". */
    suspend fun notify(message: String, level: String = "info")

    /** Show a yes/no confirmation prompt.
     *  Renders as `"$message [y/N]: "`. Accepts `"y"` or `"yes"` as affirmative.
     *  Returns false for any other input, including blank or cancellation. */
    suspend fun confirm(message: String): Boolean

    /** Show a numbered selection list. Renders `prompt` then each option as `"1. option"`.
     *  The user types a number (1-based). Returns the selected option string, or null
     *  if the input is non-numeric, out of range, or the list is empty. */
    suspend fun select(options: List<String>, prompt: String): String?

    /** Show a free-text input prompt. Renders as `"$prompt: "`.
     *  Returns the trimmed input, or null if the input was blank or cancelled. */
    suspend fun input(prompt: String): String?

    /** Prompt the user to approve, deny, or always-approve a pending tool call.
     *  In interactive (TUI) mode: suspends until the user presses y / n / a in the TUI
     *  key handler; always returns a concrete `ApprovalDecision` (never null).
     *  In headless/non-interactive mode (`System.console() == null`): returns null immediately.
     *  Unrecognised input in terminal (non-TUI) mode also returns null.
     *  Prompt text: `"Allow $toolName ($summary)? [y/n/a] "`.
     *  Tool approval scripts should treat null the same as DENY. */
    suspend fun approveToolCall(toolName: String, summary: String): ApprovalDecision?

    /** Start a non-blocking background progress task.
     *  @param description Initial description of the progress task.
     *  @param total Optional total step count for percentage calculation.
     *  Returns a [ProgressTaskHandle] extending [AutoCloseable]. */
    suspend fun startProgress(description: String, total: Long? = null): ProgressTaskHandle
}

Method behaviour summary:

Method Prompt shown Accepted input Returns

notify

"⚠ msg" / "βœ— msg" / "β„Ή msg"

n/a (fire-and-forget)

Unit

confirm

"$message [y/N]: "

"y" or "yes" β†’ true; anything else β†’ false

Boolean

select

numbered list + "Enter number: "

1-based integer; non-numeric or out-of-range β†’ null

String?

input

"$prompt: "

any text; blank or empty β†’ null

String?

approveToolCall

"Allow $toolName ($summary)? [y/n/a] "

y→APPROVE, n→DENY, a→ALWAYS_APPROVE, other/no-console→null

ApprovalDecision?

startProgress

spinner / progress bar ("$description")

n/a (non-blocking handle)

ProgressTaskHandle

Note: In TUI (alt-screen) mode, confirm, select, input, and approveToolCall are driven by the TUI key handler β€” not stdin. approveToolCall in TUI mode always returns a concrete ApprovalDecision (never null). The other three methods delegate to the terminal fallback. startProgress automatically routes to ActiveProgressRegistry in TUI mode and CoroutineProgressAnimator in Headless mode.

ProgressTaskHandle Lifecycle

startProgress returns a ProgressTaskHandle extending AutoCloseable:

interface ProgressTaskHandle : AutoCloseable {
    fun advance(step: Long = 1L)
    fun updateMessage(message: String)
    override fun close()
}
  • advance(step): Increments current step count (defaults to 1).

  • updateMessage(message): Updates the displayed description string.

  • close(): Stops progress animation / unregisters task from active progress grid. Always call close() or wrap in .use { }.

Example:

registerInterceptor(UserBash::class) { event, ctx ->
    val confirmed = ctx.ui.confirm("Run command: ${event.command}?")
    if (!confirmed) {
        UserBashResult(block = true, reason = "User declined")
    } else {
        ctx.ui.startProgress("Executing command...", total = 100L).use { handle ->
            handle.advance(50L)
            handle.updateMessage("Finalizing output...")
        }
        UserBashResult(block = false)
    }
}

Rich TUI Contract (TuiExtensionUI & Theme)

TuiExtensionUI extends ExtensionUI to provide status-bar widgets, overlays, custom views, editor manipulation, and theme access. In .bk.kts scripts, the implicit receiver exposes ui and tui typed directly as TuiExtensionUI without requiring a cast (backed by BookScriptReceiver.ui). Non-script extension contexts can cast (ctx.ui as? TuiExtensionUI).

Every method on TuiExtensionUI carries a no-op headless-safe default body so scripts run safely across TUI, Headless, and Server (ACP) modes without throwing.

Headless Fallback & Delegation Chain

In headless mode or non-TUI runs (including ACP server mode), UI operations fall back to HeadlessTuiExtensionUI β€” a production no-op implementation of TuiExtensionUI.

Approval and UI routing follows a clear delegation chain:

Script / Extension Call β†’ DelegatingExtensionUI β†’ ToolApprovalController.currentUI β†’ TuiApprovalExtensionUI (TUI)
                                                                                  β†˜ HeadlessTuiExtensionUI (Headless / ACP)

DelegatingExtensionUI delegates every TuiExtensionUI call to ToolApprovalController.currentUI, which switches dynamically between TuiApprovalExtensionUI (in interactive TUI mode) and HeadlessTuiExtensionUI (in headless or de-activated modes).

Example Usage in .bk.kts Scripts

// In .bk.kts scripts, 'ui' and 'tui' are typed directly as TuiExtensionUI
ui.setStatus("git_branch", "git: main")
ui.setWorkingMessage("Analyzing codebase...")
ui.setWorkingVisible(true)

// Register a slot widget
ui.setWidget(UiSlot.HEADER, "custom_banner") { width ->
    Text("Active Project Context".take(width))
}

// Clean up when done
ui.removeStatus("git_branch")
ui.setWorkingVisible(false)

Mordant Availability in Scripts

Scripts have access to Mordant 3.1.x on the scripting classpath. This means you can use the full Mordant widget/rendering API from .bk.kts files β€” com.github.ajalt.mordant.rendering.Widget, Text, verticalLayout, Tables, Progress, borders, spinners, and the entire widgets/widgets.progress/widgets.text packages β€” without adding any dependency to your script.

Key imports you’ll typically use in a script:

import com.github.ajalt.mordant.rendering.Widget
import com.github.ajalt.mordant.rendering.Text
import com.github.ajalt.mordant.widgets.progress.*   // progress bars & spinners
import com.github.ajalt.mordant.input.KeyboardEvent
import com.github.ajalt.mordant.input.Key

Widgets you build are rendered into the status bar, slots, footer, custom views, and overlays by the host TUI β€” you never need your own Terminal instance.

Rendered Extension Surface Details

Extension scripts customize the active TUI layout by contributing to status items, slot widgets, and working indicator overrides.

Status Bar Contributions

Call setStatus and removeStatus to add, update, or clear items in the status bar row.

  • Overloads: Accepts plain string text, Mordant Widget, or reactive StateFlow<Widget>.

  • Placement: Extension status items appear in the status bar row directly after built-in status fields (such as model, state, and token count).

  • Updates: Re-calling setStatus with an existing id replaces the previous item in place. Calling removeStatus(id) removes it.

// String status item
ui.setStatus("git_branch", "git: main")

// Mordant Widget status item
ui.setStatus("system_load", Text(ui.theme.fg(ThemeColor.ACCENT, "CPU: 12%")))

// Remove status item
ui.removeStatus("git_branch")

Slot Widgets and Viewport Shrink

Call setWidget and removeWidget to place custom Mordant widgets in specific frame slots.

  • Slot Positions:

  • UiSlot.HEADER: Renders directly below the title header.

  • UiSlot.ABOVE_PROMPT: Renders above the status bar and input prompt box.

  • UiSlot.BELOW_PROMPT: Renders directly below the input prompt box.

  • UiSlot.FOOTER: Renders at the bottom of the screen below the footer bar.

  • Ordering: Multiple widgets registered in the same slot maintain insertion order.

  • Viewport Height: Each rendered slot row reduces the available chat viewport height line for line. The frame builder adjusts viewportHeight automatically so all slot content and message history fit within the terminal height.

  • Width Adjustments: Builders accepting (width: Int) → Widget re-evaluate whenever terminal width changes.

// Register a slot widget above the prompt box
ui.setWidget(UiSlot.ABOVE_PROMPT, "context_summary") { width ->
    Text(ui.theme.fg(ThemeColor.MUTED, "Context: 4 files attached").take(width))
}
1. Keyboard Shortcuts (registerShortcut)

Extensions can register custom keyboard shortcuts using registerShortcut(key, description) { ctx → …​ } (or registerShortcut(key) { ctx → …​ }).

  • Key Specifier: String format like "ctrl+shift+p", "ctrl+c", etc.

  • Built-In Precedence: Core navigation keys always win conflicts. If an extension attempts to bind a key owned by the core, the registration succeeds with a warning logged, but core navigation takes precedence.

  • Handler Context: Receives standard ExtensionContext.

2. Slash Command Argument Completions (autocomplete)

Extension slash commands registered via registerCommand can provide custom argument completions using autocomplete { prefix, args → …​ }:

registerCommand("mycmd") {
    description = "Command with argument completions"
    handler { args, ctx -> ... }
    autocomplete { prefix, args ->
        listOf(CompletionItem("value1", label = "Label 1", description = "Desc"))
    }
}
  • CompletionItem: CompletionItem(val value: String, val label: String? = null, val description: String? = null).

  • Merge Policy: Extension argument completions are merged into the suggestion row alongside built-in and file completers, with robust failure containment (throwing providers are safely contained without crashing the TUI suggestion row).

  • setFooter(render): Replaces the default footer body with a custom renderer (width: Int) → Widget. Passing null restores the default footer. UiSlot.FOOTER slot widgets append after whichever footer body wins.

  • setTitle(title): Updates the terminal window title via standard escape sequence (\u001B]0;$title\u0007).

4. Programmatic Editor Text APIs (setEditorText, getEditorText, pasteToEditor)
  • setEditorText(text): Replaces the current input buffer content.

  • getEditorText(): Reads the current input buffer content.

  • pasteToEditor(text): Appends text to the input buffer with automatic large-paste collapse semantics (payloads exceeding the 1000-character threshold undergo newline normalization/collapse).

Working Indicator Overrides

Call setWorkingMessage, setWorkingIndicator, and setWorkingVisible to customize the loader row displayed while the agent works.

  • Message Override: setWorkingMessage("Analyzing codebase…​") overrides the default loader message text. Passing null restores the built-in message.

  • Indicator Animation: setWorkingIndicator(listOf("β ‹", "β ™", "β Ή", "β Έ"), 100) replaces spinner frames and frame duration.

  • Visibility Toggle: setWorkingVisible(false) hides the working loader row entirely without affecting prompt, footer, or slot rows. Passing true restores visibility.

// Customize working text and spinner
ui.setWorkingMessage("Running static analysis...")
ui.setWorkingIndicator(listOf("◐", "β—“", "β—‘", "β—’"), 150)
ui.setWorkingVisible(true)

// Restore defaults
ui.setWorkingMessage(null)
ui.setWorkingVisible(true)

TuiExtensionUI Method Reference

Method Parameters Description / Default Behavior

setStatus

(id: String, text: String)

Sets or updates a status-bar message by ID. Default: no-op

setStatus

(id: String, widget: Widget)

Sets a status-bar item backed by a Mordant Widget. Default: no-op

setStatus

(id: String, flow: StateFlow<Widget>)

Sets a status-bar item that re-renders automatically when the flow emits. Default: no-op

removeStatus

(id: String)

Removes a status-bar message by ID. Default: no-op

setWidget

(slot: UiSlot, id: String, builder: (width: Int) → Widget)

Registers a custom Mordant Widget builder in a slot (re-rendered on resize). Default: no-op

setWidget

(slot: UiSlot, id: String, flow: StateFlow<Widget>)

Registers a slot widget backed by a StateFlow<Widget>. Default: no-op

removeWidget

(slot: UiSlot, id: String)

Removes a custom widget from a slot. Default: no-op

setWorkingMessage

(message: String?)

Sets or clears the active status-bar working message. Default: no-op

setWorkingIndicator

(frames: List<String>, frameDurationMs: Long = 120)

Customizes working spinner animation frames and frame duration in ms. Default: no-op

setWorkingVisible

(visible: Boolean)

Shows or hides the working indicator. Default: no-op

setFooter

(widget: ((width: Int) → Widget)?)

Replaces the TUI footer panel with a custom widget builder. Default: no-op

setTitle

(title: String)

Updates the active TUI title bar. Default: no-op

setEditorText

(text: String)

Replaces the input editor’s current text. Default: no-op

getEditorText

()

Reads the input editor’s current text. Default: ""

pasteToEditor

(text: String)

Inserts text at current editor cursor position. Default: no-op

confirmTimed

(message: String, timeout: Duration, default: Boolean = false)

Timed confirmation prompt; returns the selection or default on timeout. Default: null (headless)

customView

(view: CustomView<T>)

Opens a full-screen custom interactive view. Default: null

overlay

(options: OverlayOptions, onHandle: (OverlayHandle) → Unit, view: CustomView<T>)

Opens a modal anchored overlay; the handle is delivered to onHandle before the view is created. Default: null

theme

val theme: TuiTheme

Property returning the active TuiTheme (default: ShepherdTheme())

UiSlot Variants

Variant Description

HEADER

Top region of the TUI above message history

ABOVE_PROMPT

Middle region directly above the input prompt box

BELOW_PROMPT

Region directly below the input prompt box

FOOTER

Bottom region below status bar

Interactive Custom Views & Overlays (CustomView, OverlayOptions, OverlayHandle)

Book provides full-screen custom interactive views and modal overlay dialogs through TuiExtensionUI.

CustomViewController<T> Type Table

Property / Method Type Description

events

Flow<KeyboardEvent>

Terminal keyboard input events stream active only while focused (buffered, capacity 64)

scope

CoroutineScope

Coroutine scope tied to view lifetime; cancelled automatically on close

theme

TuiTheme

Active theme instance for styling widgets

requestRender()

Unit

Triggers a TUI re-render frame tick

finish(result: T)

Unit

Closes view/overlay exactly once and completes suspend call with result

cancel()

Unit

Closes view/overlay exactly once and completes suspend call with null

Idempotency: finish/cancel are guarded β€” only the first call wins; repeat calls are ignored.

CustomView<T> and CustomComponent

fun interface CustomView<T> {
    fun create(controller: CustomViewController<T>): CustomComponent
}

fun interface CustomComponent {
    fun render(width: Int): Widget
}

OverlayOptions & Anchor Enum

Property / Variant Type / Value Description

anchor

Anchor

Positioning anchor on screen (CENTER, TOP_CENTER, BOTTOM_CENTER, LEFT_CENTER, RIGHT_CENTER)

widthPercent

Int

Percentage width of terminal screen (default: 60)

heightPercent

Int

Percentage height of terminal screen (default: 50)

title

String?

Optional panel header title

OverlayHandle Lifecycle

Method Description

focus()

Brings overlay to focus

unfocus()

Removes focus from overlay

hide()

Hides overlay panel from render output without closing the session (isHidden flag; triggers a re-render)

show()

Restores hidden overlay panel to render output (triggers a re-render)

close()

Closes the overlay session, removes it from the overlay queue, and cancels the controller scope

Overlay Queue & Keyboard Routing

Overlays are managed by an OverlayManager with single-focus semantics:

  • The first opened overlay becomes active and receives keyboard events.

  • Additional overlays opened while one is active are placed in a FIFO queue and are unfocused until the active one closes; when the active overlay closes (via finish, cancel, or handle.close()), the next queued overlay is automatically focused.

  • Only the focused overlay receives keyboard events β€” a background overlay’s controller.events flow is silent until it gains focus.

  • Closing an overlay also cancels its controller.scope, so any coroutines launched inside the view are terminated.

  • Calling hide() on the active overlay removes it from the compositor output but keeps the session and queue position; show() restores it.

  • customView is implemented as a full-screen overlay(OverlayOptions(), onHandle = {}, view) β€” one shared code path.

Extension Functions (customView, overlay, confirmTimed)

Method Signature Return Type Description

suspend fun <T> customView(view: CustomView<T>): T?

T?

Opens full-screen interactive custom view (equivalent to overlay(OverlayOptions(), {}, view)); returns result or null on cancel

suspend fun <T> overlay(options: OverlayOptions = OverlayOptions(), onHandle: (OverlayHandle) → Unit = {}, view: CustomView<T>): T?

T?

Opens modal anchored overlay panel; onHandle is invoked with the handle before the view is created; returns result or null on cancel

suspend fun confirmTimed(message: String, timeout: Duration, default: Boolean = false): Boolean

Boolean

Timed confirmation dialog; returns selection or default on timeout

Worked Examples (customView, overlay, confirmTimed)

1. Full-Screen Custom View (customView)
// Open a custom full-screen interactive view that listens to keyboard events
val result = ui.customView { controller ->
    controller.scope.launch {
        controller.events.collect { event ->
            if (event.key == Key.Enter) {
                controller.finish("action_completed")
            } else if (event.key == Key.Esc) {
                controller.cancel()
            }
        }
    }
    Text(controller.theme.bold("Custom View: Press Enter to finish, Esc to cancel"))
}
2. Modal Anchored Overlay (overlay)
// Open an anchored modal overlay panel in the center with a custom title
val decision = ui.overlay(
    OverlayOptions(anchor = Anchor.CENTER, widthPercent = 50, heightPercent = 40, title = "Settings")
) { controller ->
    // Optional: capture the handle immediately via onHandle (second lambda arg),
    // e.g. to hide/show the panel while a background tool runs.
    controller.scope.launch {
        controller.events.collect { event ->
            if (event is Key.Escape) controller.cancel()
        }
    }
    object : CustomComponent {
        override fun render(width: Int): Widget = verticalLayout {
            cell(Text(controller.theme.fg(ThemeColor.ACCENT, "Configure options below (width=$width):")))
            cell(Text("Press Esc to close."))
        }
    }
}
3. Timed Confirmation Prompt (confirmTimed)
// Prompt user with a 15-second timeout, falling back to false if no response
val approved = ui.confirmTimed("Execute dangerous migration?", 15.seconds, default = false)
if (approved) {
    ui.notify("Migration starting...", "info")
} else {
    ui.notify("Migration aborted or timed out.", "warn")
}

Focus Semantics & Buffer Preservation (ADR Β§3)

  1. Single Focus Owner: Only one custom view or overlay holds input focus at a time, managed centrally by OverlayManager. While active, InputStateMachine routes all KeyboardEvent`s to the focused view’s `events flow rather than mutating the input buffer.

  2. Nested Overlays Queue: If a view is activated while another is already active, the new view is queued. When the active view closes, the queued view is automatically promoted.

  3. Buffer Preservation Guarantee: User text and cursor position typed into the input buffer before opening a custom view or overlay are saved into a BufferSnapshot and restored byte-identical upon close. Tested and guaranteed across all open/close cycles.

Theme Engine (TuiTheme & ShepherdTheme)

Book provides the TuiTheme interface and default ShepherdTheme implementation to style terminal output with the Firefly color palette.

  • TuiTheme Interface: Defines fg(style: ThemeColor, text: String): String, bg(style: ThemeColor, text: String): String, bold(text: String): String, italic(text: String): String, and strikethrough(text: String): String.

  • ShepherdTheme: Default theme engine emitting ANSI truecolor escape sequences (\u001b[38;2;R;G;Bm) for exact RGB palette colors.

  • Diff Token Independence: Diff lines use dedicated tokens (DIFF_ADDED, DIFF_REMOVED, DIFF_HUNK, DIFF_CONTEXT) rather than SUCCESS or ERROR. This keeps diff line syntax coloring independent from operational success and failure styling.

  • 16-Color Terminal Fallback: On terminals without truecolor support (ansiLevel < TRUECOLOR), ShepherdTheme degrades truecolor sequences to standard 16-color ANSI escape codes.

ThemeColor Token Reference (17 Variants)

Category Token Firefly Palette Default (RGB) 16-Color Fallback ANSI Code Usage

Semantic

TOOL_TITLE

#EABC3A (234, 188, 58) Gold

93 (Bright Yellow)

Tool call headers & entry titles

ACCENT

#C09317 (192, 147, 23) Amber

33 (Yellow)

Highlights, cursor, key hints

SUCCESS

#EABC3A (234, 188, 58) Gold

93 (Bright Yellow)

Successful operations & completed states

ERROR

#703A2A (112, 58, 42) Rust

31 (Red)

Error messages & failures

WARNING

#C09317 (192, 147, 23) Amber

33 (Yellow)

Warnings & cautious alerts

MUTED

#3D4352 (61, 67, 82) Slate

90 (Bright Black)

Subtle borders, secondary text

DIM

#3D4352 (61, 67, 82) Slate

90 (Bright Black)

Dimmed text, background fills

CUSTOM_MESSAGE_BG

#3D4352 (61, 67, 82) Slate

90 (Bright Black)

Background fill for custom extension messages

Diff

DIFF_ADDED

#EABC3A (234, 188, 58) Gold

93 (Bright Yellow)

Added diff lines foreground

DIFF_REMOVED

#F36262 (243, 98, 98) Coral

91 (Bright Red)

Removed diff lines foreground

DIFF_HUNK

#C09317 (192, 147, 23) Amber

33 (Yellow)

Diff hunk headers (@@)

DIFF_CONTEXT

#3D4352 (61, 67, 82) Slate

90 (Bright Black)

Unchanged diff context lines

DIFF_ADDED_BG

#605B4D (96, 91, 77) Gold blend

90 (Bright Black)

Added diff lines background

DIFF_REMOVED_BG

#614955 (97, 73, 85) Coral blend

90 (Bright Black)

Removed diff lines background

Gradient

SECONDARY

#948046 (148, 128, 70) Slate-Gold

33 (Yellow)

Derived midpoint between slate and gold

BRONZE

#986620 (152, 102, 32) Rust-Amber

33 (Yellow)

Derived midpoint between rust and amber

EMBER

#EE8F4E (238, 143, 78) Gold-Coral

93 (Bright Yellow)

Derived midpoint between gold and coral

Gradient Derivation Rules

ShepherdTheme calculates gradient colors dynamically using RGB-lerp between anchor colors in the active palette:

  • SECONDARY = derive(MUTED, TOOL_TITLE, 0.5)

  • BRONZE = derive(ERROR, WARNING, 0.5)

  • EMBER = derive(TOOL_TITLE, Coral(#F36262), 0.5)

  • DIFF_ADDED_BG = derive(MUTED, TOOL_TITLE, 0.2)

  • DIFF_REMOVED_BG = derive(MUTED, Coral(#F36262), 0.2)

Because derived tokens are computed dynamically rather than hardcoded, changing the base theme palette automatically recalculates all secondary, bronze, ember, and diff background shades across the UI.


Session Observability Samples (JSONL)

The following samples live in samples/ and focus on session observability:

Sample Purpose Output file

session-lifecycle-jsonl.bk.kts

Session lifecycle audit trail (session.start, session.compact, session.tree, session.shutdown)

~/.q/observability/session_lifecycle.jsonl

tool-execution-observability-jsonl.bk.kts

Per-tool execution telemetry (duration, errors, result size)

~/.q/observability/tool_execution.jsonl

turn-summary-observability-jsonl.bk.kts

Per-turn rollups (turn latency, tool count, assistant text size)

~/.q/observability/turn_summary.jsonl

mac-bash-sandbox.bk.kts

Wraps every BashTool command in macOS sandbox-exec β€” restricts filesystem writes to CWD + /tmp and blocks network by default

n/a (sandboxing is in-process)

All three use a buildlog.ai-inspired JSONL envelope (spec, event, ts, session_id, session_name, session_file, cwd) for easy ingestion.


sub-agents.bk.kts

Discovers agent definition files on disk and registers each one as a callable Book tool, enabling the main Book agent to delegate sub-tasks to specialised sub-agents.

Two definition formats are supported:

Format Location Activation

Claude Code

.claude/agents/*.md

All .md files in this directory are loaded

GitHub Copilot

.github/prompts/*.md

Only files with mode: agent front-matter field

Agent definition file anatomy:

name: code-reviewer            # tool name (snake_case auto-derived if absent)
description: Reviews code…     # shown to the Book agent so it knows when to call this tool
model: claude-sonnet-4-5       # optional model hint forwarded to the CLI
mode: agent                    # required for Copilot files; ignored for Claude Code files

What the script does:

  • Scans both directories at BookEvent.ResourcesDiscover (startup).

  • Registers each agent as a tool { } named after the agent’s name field (or filename stem), e.g. code_reviewer.

  • The Book agent can call these tools directly: code_reviewer(task="Review the auth module").

  • Spawns the appropriate CLI sub-process for Claude Code agents via claude --print [--system-prompt …] [--model …] with the task on stdin.

  • Spawns the appropriate CLI sub-process for Copilot agents via gh copilot suggest --target shell with system prompt embedded in the composed prompt.

  • A configurable SUB_AGENT_TIMEOUT_SEC (default 120 s) kills runaway processes.

Slash commands:

Command Description

/agents

List all currently loaded sub-agents with their runtime and source file

/agents reload

Re-scan the agent directories without restarting Book

/delegate <name> <task>

Manually invoke a sub-agent by tool name

Prerequisites:

Example agent definitions that can be copied into your project:

samples/agent-definitions/
  claude/
    code-reviewer.md   ← Claude Code sub-agent (no mode: field required)
    test-writer.md     ← Claude Code sub-agent with model hint
  copilot/
    pr-description.md  ← Copilot agent (mode: agent)
    doc-writer.md      ← Copilot agent with model hint

Sentinel Extension Pattern

The Sentinel Extension Pattern (SPEC-04) is used to provide an explicit, cheap, format-independent signal to an external orchestrator (like FirstMate) that an agent turn has ended.

Core Mechanics

  1. Pointer File: A .fm-q-turnend file in the working directory contains the path to the sentinel file on its first line.

  2. Session-Start Caching: The sentinel path is resolved and validated once at BookEvent.SessionStart. This prevents mid-session redirection and ensures the overhead is incurred only once.

  3. Turn-End Touch: On every BookEvent.TurnEnd, the extension touches (creates or updates the mtime of) the sentinel file.

  4. Worktree Containment: To prevent security risks, the extension MUST refuse to write any sentinel file that resolves outside the agent’s current working directory (canonical path check).

Implementation Reference (fm-turnend.bk.kts)

The canonical implementation ships at .bk/tools/fm-turnend.bk.kts.

// Example implementation fragment
registerEventHandler(BookEvent.SessionStart::class) { _, ctx ->
    cachedSentinelPath = resolveSentinelPath(ctx.cwd)
}

registerEventHandler(BookEvent.TurnEnd::class) { _, _ ->
    cachedSentinelPath?.let { touchSentinel(it) }
}

Herdr Composition Contract

When used alongside herdr.bk.kts, the sentinel extension MUST:

  • Use matching vocabulary for state reporting (working on AgentStart, idle on AgentEnd).

  • Contain all handler exceptions (e.g., using a safely { } wrapper) to ensure the event bus remains healthy even if I/O fails. '''

Extension Renderer Registry & Custom Renderers

Book allows extensions to register custom renderers for tool calls, tool results, TUI custom entries, and LLM-context custom messages, as well as define display-only markdown transformer chains.

Renderer Vocabulary

ToolRenderer

Defines custom rendering for tool calls and tool results by tool name.

interface ToolRenderer {
    val renderShell: RenderShell get() = RenderShell.BOXED

    fun renderCall(args: JsonObject, context: ToolRenderContext): Widget
    fun renderResult(result: ToolResultView, context: ToolRenderContext): Widget
}
  • renderShell: RenderShell.BOXED (default) wraps the returned widget in a default panel with a title header; RenderShell.SELF renders the widget raw without box-drawing framing.

  • ToolRenderContext:

  • expanded: Boolean indicating whether the tool row is expanded.

  • isPartial: Boolean true during ToolExecutionUpdate streaming frames; false after ToolExecutionEnd.

  • isError: Boolean true if the tool execution resulted in an error.

  • toolCallId: String unique ID of the tool call.

  • state: MutableMap<String, Any?> shared row-local state map across renderCall and renderResult.

  • lastComponent: CustomComponent? holding the previous render result component.

  • invalidate(): Requests a re-render tick for this specific tool row.

  • ToolResultView: data class ToolResultView(val content: String, val isError: Boolean = false)

EntryRenderer

Defines rendering for TUI-only CustomEntry items persisted via SessionManagerInterface.appendEntry.

fun interface EntryRenderer {
    fun render(entry: CustomEntry, expanded: Boolean, theme: TuiTheme): Widget
}

MessageRenderer

Defines rendering for custom messages participating in LLM context (CustomMessageEntry).

fun interface MessageRenderer {
    fun render(message: CustomMessageEntry, options: MessageRenderOptions, theme: TuiTheme): Widget
}

data class MessageRenderOptions(
    val isStreaming: Boolean = false,
    val availableWidth: Int = 80
)

MarkdownTransformer

Defines display-only markdown transformation chains executed pre-widget in registration order.

fun interface MarkdownTransformer {
    fun transform(markdown: String, context: MarkdownContext): String
}

data class MarkdownContext(
    val messageType: MessageType,
    val isStreaming: Boolean,
    val availableWidth: Int
)

enum class MessageType { USER, ASSISTANT, ASSISTANT_THINKING }
  • Failure-Safe & Display-Only: A throwing transformer is skipped (keeping output so far) and the chain continues. Transformed markdown affects display output only; persisted session and LLM message payloads remain strictly unchanged. '''

Registration API Functions

Extensions register renderers and transformers via extension functions on ExtensionAPI (keeping domain core pure):

registerToolRenderer("execute_sql", myToolRenderer)
registerEntryRenderer("sql_log", myEntryRenderer)
registerMessageRenderer("card_notice", myMessageRenderer)
registerMarkdownTransformer { markdown, ctx -> markdown.replace("TODO", "DONE") }

Failure Containment (ADR Β§9.1)

Any exception thrown inside a tool, entry, or message custom renderer is safely caught per row by MessageListRenderer, which falls back to built-in rendering for that row. The extension script is never unloaded, and other registered contributions continue to render normally.