Extension API: UI, Observability & the Sentinel Pattern
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 |
|---|---|---|---|
|
|
n/a (fire-and-forget) |
|
|
|
|
|
|
numbered list + |
1-based integer; non-numeric or out-of-range β null |
|
|
|
any text; blank or empty β null |
|
|
|
|
|
|
spinner / progress bar ( |
n/a (non-blocking handle) |
|
Note: In TUI (alt-screen) mode,
confirm,select,input, andapproveToolCallare driven by the TUI key handler β not stdin.approveToolCallin TUI mode always returns a concreteApprovalDecision(never null). The other three methods delegate to the terminal fallback.startProgressautomatically routes toActiveProgressRegistryin TUI mode andCoroutineProgressAnimatorin 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 callclose()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 reactiveStateFlow<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
setStatuswith an existingidreplaces the previous item in place. CallingremoveStatus(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
viewportHeightautomatically so all slot content and message history fit within the terminal height. -
Width Adjustments: Builders accepting
(width: Int) → Widgetre-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))
}
Shortcuts, Argument Completions, Footer, Title & Editor APIs
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).
3. Custom Footer and Terminal Title (setFooter, setTitle)
-
setFooter(render): Replaces the default footer body with a custom renderer(width: Int) → Widget. Passingnullrestores the default footer.UiSlot.FOOTERslot 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. Passingnullrestores 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. Passingtruerestores 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 |
|---|---|---|
|
|
Sets or updates a status-bar message by ID. Default: no-op |
|
|
Sets a status-bar item backed by a Mordant |
|
|
Sets a status-bar item that re-renders automatically when the flow emits. Default: no-op |
|
|
Removes a status-bar message by ID. Default: no-op |
|
|
Registers a custom Mordant |
|
|
Registers a slot widget backed by a |
|
|
Removes a custom widget from a slot. Default: no-op |
|
|
Sets or clears the active status-bar working message. Default: no-op |
|
|
Customizes working spinner animation frames and frame duration in ms. Default: no-op |
|
|
Shows or hides the working indicator. Default: no-op |
|
|
Replaces the TUI footer panel with a custom widget builder. Default: no-op |
|
|
Updates the active TUI title bar. Default: no-op |
|
|
Replaces the input editor’s current text. Default: no-op |
|
|
Reads the input editor’s current text. Default: |
|
|
Inserts text at current editor cursor position. Default: no-op |
|
|
Timed confirmation prompt; returns the selection or |
|
|
Opens a full-screen custom interactive view. Default: |
|
|
Opens a modal anchored overlay; the handle is delivered to |
|
|
Property returning the active |
UiSlot Variants
| Variant | Description |
|---|---|
|
Top region of the TUI above message history |
|
Middle region directly above the input prompt box |
|
Region directly below the input prompt box |
|
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 |
|---|---|---|
|
|
Terminal keyboard input events stream active only while focused (buffered, capacity 64) |
|
|
Coroutine scope tied to view lifetime; cancelled automatically on close |
|
|
Active theme instance for styling widgets |
|
|
Triggers a TUI re-render frame tick |
|
|
Closes view/overlay exactly once and completes suspend call with |
|
|
Closes view/overlay exactly once and completes suspend call with |
Idempotency:
finish/cancelare 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 |
|---|---|---|
|
|
Positioning anchor on screen ( |
|
|
Percentage width of terminal screen (default: 60) |
|
|
Percentage height of terminal screen (default: 50) |
|
|
Optional panel header title |
OverlayHandle Lifecycle
| Method | Description |
|---|---|
|
Brings overlay to focus |
|
Removes focus from overlay |
|
Hides overlay panel from render output without closing the session ( |
|
Restores hidden overlay panel to render output (triggers a re-render) |
|
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
activeand 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, orhandle.close()), the next queued overlay is automatically focused. -
Only the focused overlay receives keyboard events β a background overlay’s
controller.eventsflow 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. -
customViewis implemented as a full-screenoverlay(OverlayOptions(), onHandle = {}, view)β one shared code path.
Extension Functions (customView, overlay, confirmTimed)
| Method Signature | Return Type | Description |
|---|---|---|
|
|
Opens full-screen interactive custom view (equivalent to |
|
|
Opens modal anchored overlay panel; |
|
|
Timed confirmation dialog; returns selection or |
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)
-
Single Focus Owner: Only one custom view or overlay holds input focus at a time, managed centrally by
OverlayManager. While active,InputStateMachineroutes allKeyboardEvent`s to the focused view’s `eventsflow rather than mutating the input buffer. -
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.
-
Buffer Preservation Guarantee: User text and cursor position typed into the input buffer before opening a custom view or overlay are saved into a
BufferSnapshotand 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.
-
TuiThemeInterface: Definesfg(style: ThemeColor, text: String): String,bg(style: ThemeColor, text: String): String,bold(text: String): String,italic(text: String): String, andstrikethrough(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 thanSUCCESSorERROR. This keeps diff line syntax coloring independent from operational success and failure styling. -
16-Color Terminal Fallback: On terminals without truecolor support (
ansiLevel < TRUECOLOR),ShepherdThemedegrades 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 |
|
|
93 (Bright Yellow) |
Tool call headers & entry titles |
|
|
33 (Yellow) |
Highlights, cursor, key hints |
|
|
|
93 (Bright Yellow) |
Successful operations & completed states |
|
|
|
31 (Red) |
Error messages & failures |
|
|
|
33 (Yellow) |
Warnings & cautious alerts |
|
|
|
90 (Bright Black) |
Subtle borders, secondary text |
|
|
|
90 (Bright Black) |
Dimmed text, background fills |
|
|
|
90 (Bright Black) |
Background fill for custom extension messages |
|
Diff |
|
|
93 (Bright Yellow) |
Added diff lines foreground |
|
|
91 (Bright Red) |
Removed diff lines foreground |
|
|
|
33 (Yellow) |
Diff hunk headers ( |
|
|
|
90 (Bright Black) |
Unchanged diff context lines |
|
|
|
90 (Bright Black) |
Added diff lines background |
|
|
|
90 (Bright Black) |
Removed diff lines background |
|
Gradient |
|
|
33 (Yellow) |
Derived midpoint between slate and gold |
|
|
33 (Yellow) |
Derived midpoint between rust and amber |
|
|
|
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 audit trail ( |
|
|
Per-tool execution telemetry (duration, errors, result size) |
|
|
Per-turn rollups (turn latency, tool count, assistant text size) |
|
|
Wraps every BashTool command in macOS |
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 |
|
All |
GitHub Copilot |
|
Only files with |
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’snamefield (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 shellwith system prompt embedded in the composed prompt. -
A configurable
SUB_AGENT_TIMEOUT_SEC(default 120 s) kills runaway processes.
Slash commands:
| Command | Description |
|---|---|
|
List all currently loaded sub-agents with their runtime and source file |
|
Re-scan the agent directories without restarting Book |
|
Manually invoke a sub-agent by tool name |
Prerequisites:
-
Claude Code agents:
claudebinary in PATH (Anthropic CLI) -
Copilot agents:
ghbinary in PATH with thecopilotextension installed (GitHub Copilot in the CLI)
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
-
Pointer File: A
.fm-q-turnendfile in the working directory contains the path to the sentinel file on its first line. -
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. -
Turn-End Touch: On every
BookEvent.TurnEnd, the extension touches (creates or updates the mtime of) the sentinel file. -
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 (
workingonAgentStart,idleonAgentEnd). -
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.SELFrenders the widget raw without box-drawing framing. -
ToolRenderContext: -
expanded:Booleanindicating whether the tool row is expanded. -
isPartial:Booleantrue duringToolExecutionUpdatestreaming frames; false afterToolExecutionEnd. -
isError:Booleantrue if the tool execution resulted in an error. -
toolCallId:Stringunique ID of the tool call. -
state:MutableMap<String, Any?>shared row-local state map acrossrenderCallandrenderResult. -
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.