Audience: developers and AI agents working on Book’s implementation. Per-package breakdown of :core:domain, :core:presentation, :infrastructure, :core:providers:koog, :features:mcp, :features:acp, :jvm:scripting, and :cli, plus the architecture diagram catalogue.

For the :domain core abstractions, design philosophies, and dependencies, see the Architecture Overview.

:core:domain (Core Abstractions)

Pure Kotlin domain contracts and interfaces without external platform or engine dependencies.

  • extensions/ (us.nineworlds.book.domain.extensions):

  • ExtensionScriptLoader: Platform-neutral interface for asynchronous script loading using okio.Path and kotlinx.coroutines.Job.

  • NoOpExtensionScriptLoader: Zero-dependency default implementation returning completed jobs and empty lists for non-JVM target platforms or test contexts.

:core:presentation (Presentation Contract & Theme Engine)

Presentation layer contracts, theme engine, and rich extension UI types. Ring position: presentation layer, depends on :core:domain; consumed by :jvm:scripting and :jvm:cli.

  • extensions/ (us.nineworlds.book.presentation.extensions):

  • TuiExtensionUI: Extended extension UI interface with status widgets, working indicator controls, overlays, custom views, and theme access. Every method carries a no-op headless-safe default body.

  • TuiTheme: Interface for theme styling (ANSI foreground/background coloring, bold/italic/strikethrough styling).

  • ThemeColor: Enum with 17 tokens covering semantic, diff, and gradient colors.

  • ShepherdTheme: Default implementation of TuiTheme providing the Firefly palette and dynamic RGB-lerp gradient derivation.

  • CustomView.kt: Custom view vocabulary (UiSlot, OverlayOptions, OverlayHandle, CustomView, CustomComponent, CustomViewController).

:infrastructure (Implementations)

Implements the interfaces defined in :domain using specific technologies, organized into feature packages.

  • agentloop/ (us.nineworlds.book.infrastructure.agentloop): DefaultAgentLoopEnvironment โ€” @SingleIn(AppScope::class) @Inject implementation of AgentLoopEnvironment. Receives FileSystem and ProcessRunner via constructor injection and exposes them as the properties defined by the interface. Wired through AppGraph.

  • filesystem/ (us.nineworlds.book.infrastructure.filesystem): SandboxedOkioFileSystem โ€” secure, sandboxed file access using Okio.

  • systemprompt/ (us.nineworlds.book.infrastructure.systemprompt): DefaultSystemPromptLoader โ€” loads and merges system prompts from ~/.bk/SYSTEM.md, .bk/SYSTEM.md, ~/.bk/AGENTS.md, <projectDir>/AGENTS.md, and CLI flags. AGENTS.md files follow the agents.md spec and are always injected into context regardless of CLI overrides.

  • models/ (us.nineworlds.book.infrastructure.models): ModelMetadataRegistry โ€” model catalogue and metadata. Loads model_metadata.json and delegates id resolution to ModelKeyMatcher (us.nineworlds.book.domain.models), so metadata lookups and pricing lookups always resolve to the same catalogue entry. See Model Resolution.

  • config/ (us.nineworlds.book.infrastructure): ConfigManager โ€” reads and writes ~/.bk/config.json (model selection, last-session map). Also exposes externalToolServers(cwd: String): List<ExternalToolServer> which merges two .bk/mcp.json files: ~/.bk/mcp.json (global, lowest priority) and <cwd>/.bk/mcp.json (project-local). Merge rule: project-local entries override global entries with the same name; entries unique to either file are retained. Returns emptyList() when both files are absent or malformed. Used by ServeCommand to populate ExternalToolServer entries for the book serve start-up path.

  • session/ (us.nineworlds.book.infrastructure.session): Session stack with SessionManager (JSONL persistence, branching/tree, labels, compaction entries), DefaultSessionResolver (resume lookup/listing), SessionAutoNamer (first-turn auto title generation), and DynamicLogRouter (CacheMap-backed thread-safe routing of session-scoped log files). SessionManager.appendThinkingLevelChange(thinkingLevel: String) writes a ThinkingLevelChangeEntry linked to the current leaf and returns its id; buildSessionContext() replays the most recent entry into SessionContext.thinkingLevel. Callers convert EffortLevel to apiValue before passing it in โ€” the orchestrator stores the string verbatim.

  • process/ (us.nineworlds.book.infrastructure.process): ProcessRunner interface, JvmProcessRunner, ProcessBuilderRunner โ€” external process execution.

  • tools/ (us.nineworlds.book.infrastructure.tools): Concrete implementations of built-in tools (BashTool, GrepTool, ReadFileTool, WriteFileTool, EditFileTool, FindTool). FileMutationQueue (CacheMap-backed thread-safe queue) serialises file-write operations. A bundled ripgrep.bk.kts extension in the :extensions module provides a full-featured ripgrep tool โ€” see Bundled Extensions below.

  • GrepTool: Searches file content via Ripgrep (rg) or system grep -E. Supports pattern, path, include, exclude, context, beforeContext, afterContext, maxCount, filesOnly (filenames-only, -l), countOnly (per-file match counts, --count/-c), and includeGlobs (multiple file-type globs, e.g. ['.kt', '.kts']). normalizeArguments remaps snake_case aliases to camelCase.

  • FindTool: Locates files by glob pattern via fd or system find. Supports pattern, path, limit, type (f/d to filter files vs. directories), maxDepth (max traversal depth), excludePath (prune a subtree), modifiedWithinDays (recency filter in days), and newerThan (reference-file recency filter). newerThan forces the system-find fallback path. normalizeArguments remaps snake_case aliases to camelCase.

  • skills/ (us.nineworlds.book.infrastructure.skills): MarkdownSkillLoader โ€” loads skills from Markdown files into the SkillRegistry.

  • utils/ (us.nineworlds.book.infrastructure.utils): Shared utilities (e.g., Mime type helpers).

:core:providers:koog (Koog Provider Module)

Houses the Koog LLM provider implementation (us.nineworlds.book.providers.koog), isolating Koog framework dependencies and provider components. Depends on :core:domain.

  • KoogAgent (us.nineworlds.book.providers.koog): Integration with LLMs (OpenAI, Anthropic) via the Koog framework. Resolves the provider, builds the Koog prompt and model, maps tools via ToolMapper, fires the BeforeProviderRequest intercept, logs outbound payloads via the session-scoped KoogTransportLogger, then delegates the entire stream lifecycle to StreamOrchestrator via emitAll. nextTurn is ~40 lines with one level of nesting. Model listing delegates to LLMClientAPI.models() (implemented by Koog’s OpenAILLMClient) and enriches results via ModelMetadataRegistry; models absent from the registry are returned as minimal ModelMetadata(id) entries. When building the LLModel, a registry hit with supportsReasoning == true adds LLMCapability.Thinking so Koog enables thinking-capable request handling; a miss leaves the capability off. KoogAgent implements ReasoningAgent (SPEC-2, per ADR-20261002 (prompts/plans/adr/ADR-20261002-llm-reasoning-modes.md)): it exposes override var effort: EffortLevel (default EffortLevel.DEFAULT = HIGH) and, at buildKoogPrompt() time, delegates the effort into the Koog request as reasoning_effort inside LLMParams.additionalProperties โ€” Koog 1.3.0 has no first-class effort field, and its AdditionalPropertiesFlatteningSerializer merges these entries into the OpenAI wire JSON. Emission is gated on both metadataRegistry.lookup(model)?.supportsReasoning == true and effort != EffortLevel.OFF; non-reasoning or unknown models, and OFF, omit the key entirely while the caller’s preference stays preserved on the agent. buildKoogPrompt() is fully multi-modal: UserMessage entries containing Content.Image parts are mapped to ContentPart.Image inside a user {} block; ToolResultMessage entries containing Content.Image parts emit a text tool { result(…​) } block followed by a synthetic user {} block carrying the images as ContentPart.Image (required because Koog 0.8.0’s Message.Tool.Result is text-only). Images are passed as AttachmentContent.Binary.Base64 โ€” the base64 string produced by ReadFileTool is used directly, avoiding a decode/re-encode round-trip.

  • StreamOrchestrator (us.nineworlds.book.providers.koog): Owns the full stream lifecycle of a single agent turn โ€” invokes the streaming executor via a streamFactory lambda, collects StreamFrame`s through `StreamFrameHandler, wires the InactivityWatchdog (defaults: 600 s stream timeout, 30 s inactivity threshold โ€” tuned for large tool-call generations), discriminates CancellationException from hard errors, handles all three fallback-completion branches (gotEnd, !gotEnd+content, !gotEnd+noContent), dispatches the AfterProviderResponse extension event, and calls onInteraction (wired to KoogTransportLogger::logInteraction). When the stream stalls before StreamFrame.End, the fallback path finalizes any accumulated tool-call arguments before emitting the fallback Completed event.

  • StreamFrameHandler (us.nineworlds.book.providers.koog): Converts raw StreamFrame`s into `AgentEvent`s. Handles `TextDelta, ReasoningDelta, named ToolCallComplete/ToolCallDelta (start a new tool call), blank-name ToolCallComplete/ToolCallDelta (accumulate incremental argument chunks), and End (finalize and emit Completed). Zero-length TextDelta/ReasoningDelta frames are suppressed at this provider boundary (no AgentEvent emitted) โ€” some providers (e.g. GLM-5.3-flash via Koog 1.3.0) interleave empty text deltas with every reasoning delta, which previously flushed one downstream session update per fragment and shredded ACP clients' thinking output; see ADR-20261001 (prompts/plans/adr/ADR-20261001-acp-thinking-delta-fragmentation.md). Whitespace-only deltas are preserved (the guard is empty-only, not blank-only). Second defense layer: AcpAgentSession’s event collector independently short-circuits any zero-length `TextDelta/ThinkingDelta that reaches it (no chunk emission) and applies the trailing newline contract โ€” non-empty reasoning deltas are emitted immediately, and when transitioning to terminal events (AgentEnd/Error/TurnEnd), structural events, or real text deltas, a separate \n chunk is emitted if the preceding reasoning did not end with a newline โ€” so the session stays immune even if a future provider re-introduces empty deltas. Tool-call arguments are accumulated from both ToolCallDelta and blank-name ToolCallComplete frames into an index-keyed StringBuilder map and are finalized on both the normal End path and the stall/timeout fallback path โ€” preventing empty {} argument dispatches on large streamed payloads. For gateways that double-emit each tool-call event (an identical ToolCallDelta immediately followed by a ToolCallComplete), it de-duplicates opposite-type adjacent frames by signature (id + normalized name + content + index) so each logical call and argument chunk is processed exactly once; pure same-type streaming and opposite-type frames with differing content are left untouched.

:features:mcp (MCP Client Module)

Encapsulates all Model Context Protocol (MCP) client logic. :cli and :features:acp depend on this module; :domain and :infrastructure do not.

Public API โ€” McpClientFacade

us.nineworlds.book.features.mcp.McpClientFacade is the sole public interface of this module. External modules must never import McpClientManager or any us.nineworlds.book.features.mcp.client. / us.nineworlds.book.features.mcp.transport. type directly.

interface McpClientFacade {
    suspend fun connect(servers: List<ExternalToolServer>, toolRegistry: ToolRegistry)
    suspend fun disconnect(toolRegistry: ToolRegistry)
    fun registeredTools(): List<Tool>
}
  • connect โ€” Spawns a subprocess for each ExternalToolServer, performs MCP initialize + tools/list, wraps each discovered tool as McpToolAdapter (ToolSource.MCP), and registers it in the provided ToolRegistry. Call-time toolRegistry parameter (ADR ยง4.3) โ€” not stored at construction.

  • disconnect โ€” Closes all active client connections, kills subprocesses, and deregisters all tracked MCP tools from ToolRegistry.

  • registeredTools โ€” Returns a snapshot of the currently tracked Tool list.

Internal Structure

Package Class Responsibility

us.nineworlds.book.features.mcp

McpClientFacade

Public interface โ€” the only type :cli imports

us.nineworlds.book.features.mcp.client

McpClientManager

Concrete implementation of McpClientFacade; @Inject @SingleIn(McpScope)

us.nineworlds.book.features.mcp.tools

McpToolAdapter

Adapts an MCP SDK Tool to the :domain Tool interface; ToolSource.MCP

us.nineworlds.book.features.mcp.transport

IntegerIdTransport

Wraps StdioClientTransport; converts string JSON-RPC IDs to integers for xcrun mcpbridge (Xcode 27 beta) compatibility

us.nineworlds.book.features.mcp.di

McpComponent / McpScope

Metro DI graph; scoped to one MCP activation lifecycle โ€” independent of AppScope

DI Wiring

AppGraph.provideMcpClientFacade() instantiates McpClientManager() directly (Metro @Provides method, @SingleIn(AppScope::class)). The concrete type is an internal detail; callers receive only McpClientFacade.

McpClientManager โ€” Connection lifecycle

  1. For each ExternalToolServer in servers, McpClientManager spawns a ProcessBuilder subprocess.

  2. Wraps StdioClientTransport with IntegerIdTransport.

  3. Calls client.connect(transport) with a 10 s timeout; servers that do not respond are skipped.

  4. Sends tools/list (10 s timeout); discovered tools are wrapped as McpToolAdapter and registered.

  5. On disconnect, all clients are closed and all tracked tools are deregistered via ToolRegistry.deregister(name).

Ring Boundary

:features:mcp depends on :domain (for Tool, ToolRegistry, ExternalToolServer, ToolSource, ToolCallContext) and :infrastructure is not a dependency. It must never depend on :cli.


:features:acp (ACP Server Module)

Encapsulates all Agent Client Protocol (ACP) server logic. :cli depends on this module via AcpServer; :domain and :infrastructure do not.

Ring boundary enforced at build level. :cli has zero implementation or api declarations for acp-core, acp-model, or mcp-sdk-client. Any accidental SDK import in :cli source will fail the build immediately.

Public API โ€” AcpServer

us.nineworlds.book.features.acp.AcpServer is the sole lifecycle interface exposed to :cli.

interface AcpServer {
    suspend fun start(config: AcpStartConfig)
    suspend fun stop()
}
  • start โ€” Starts the Stdio ACP transport, initialises AcpAgentSupport, and blocks until stdin EOF.

  • stop โ€” Cancels all in-flight session loops via AgentLoop.cancelAndJoin(), then clears the session registry. Prevents torn JSONL writes.

Per-Session Isolation

Each incoming ACP session/new or session/load request produces a distinct QAgentSession via AgentLoopFactory.create(ctx, env) (see :domain โ†’ AgentLoopFactory below). AgentLoop is therefore never a singleton โ€” one instance exists per active session and is discarded when the session ends.

Internal Structure

Package Class Responsibility

us.nineworlds.book.features.acp

AcpServer

Public lifecycle interface

us.nineworlds.book.features.acp

AcpServerImpl

Production impl; @Inject; owns AcpSessionRegistry

us.nineworlds.book.features.acp

AcpServerDependencies

Process-scope collaborators bound once at AppGraph construction

us.nineworlds.book.features.acp

AcpStartConfig

Per-start transport config (transport flags)

us.nineworlds.book.features.acp

AcpSessionRegistry

CacheMap-backed thread-safe registry of active `QAgentSession`s

us.nineworlds.book.features.acp.session

AcpAgentSession

ACP AgentSession impl โ€” thin adapter with the five-parameter constructor plus a defaulted historyReplay collaborator (sessionId, turnExecutor, modelController, configOptionsController, sessionOrchestrator, historyReplay); delegates turn execution to AcpTurnExecutor and postInitialize() to its collaborators; configOptions & setConfigOption overrides. The legacy construction path lives in AcpAgentSession.create(…​) (companion factory)

us.nineworlds.book.features.acp.session.runtime

AcpHistoryReplay

Interface & DefaultAcpHistoryReplay impl (Spec 6) owning history replay classification + emission: UserMessage text โ†’ UserMessageChunk, assistant text โ†’ AgentMessageChunk, thinking โ†’ AgentThoughtChunk. Deliberately omits system/tool-result/tool-call messages (R-028). Warn-logs (with the throwable attached) an IllegalStateException/IllegalArgumentException from a single message and continues; any other exception propagates

us.nineworlds.book.features.acp.session.runtime

AcpTurnExecutor

Deep module interface & DefaultAcpTurnExecutor impl owning turn pipeline, volatile fields (activeRunJob, activeCollectJob, activeChannelSnapshot), and awaitable cancel(). Delegates slash-command termination to AcpSlashCommandRouter and awaits the router’s terminal event

us.nineworlds.book.features.acp.session.runtime

AcpSlashCommandRouter

Interface & DefaultAcpSlashCommandRouter impl owning slash-command termination: routes /-prefixed prompt text to the handler port and returns the terminal Event.PromptResponseEvent. Signature carries no AcpAgentSession back-reference (R-018)

us.nineworlds.book.features.acp.session.runtime

ClientSessionOperations

Narrow seam replacing AcpAgentSession back-reference

us.nineworlds.book.features.acp.session.runtime

AcpModelController

Interface & DefaultAcpModelController impl owning model switching, resolution, _meta override, safeAgentModel, and AfterSwitchListener hook

us.nineworlds.book.features.acp.session.runtime

AcpConfigOptionsController

Interface & DefaultAcpConfigOptionsController impl owning config-option builds, setConfigOption handling, effort state, and notifyConfigOptionsChanged()

us.nineworlds.book.features.acp.session

AcpConfigOptions

Pure option builders (modelConfigOption, effortConfigOption) and label formatter; model list comes from the provider verbatim

us.nineworlds.book.features.acp.agent

AcpAgentSupport

ACP AgentSupport impl; creates per-session QAgentSession via AgentLoopFactory; calls buildEnvironmentFromCapabilities() to construct the per-session AgentLoopEnvironment

us.nineworlds.book.features.acp.capabilities

AcpFileSystem

Implements FileSystem by delegating read()/write() to ClientSessionOperations.fsReadTextFile()/fsWriteTextFile() via runBlocking. Used when client advertises capabilities.fs != null.

us.nineworlds.book.features.acp.capabilities

AcpProcessRunner

Implements ProcessRunner by delegating to ClientSessionOperations terminal RPCs (terminalCreate โ†’ terminalWaitForExit โ†’ terminalOutput โ†’ terminalRelease). Emits periodic Stdout(".") heartbeat events every 10 s via a concurrent coroutine. Streaming limitation: full output is delivered only after terminalWaitForExit returns โ€” real Stdout content is never streamed incrementally. Used when client advertises capabilities.terminal == true.

us.nineworlds.book.features.acp.capabilities

SimpleAgentLoopEnvironment

Lightweight AgentLoopEnvironment value-holder constructed per session from capabilities; holds AcpFileSystem/SandboxedOkioFileSystem and AcpProcessRunner/ProcessBuilderRunner depending on what the client advertised.

us.nineworlds.book.features.acp.events

AcpEventMapper

Pure stateless mapper from AgentEvent โ†’ ACP Event; returns null for unmapped events

us.nineworlds.book.features.acp.di

AcpScope

Metro @Scope annotation for ACP server lifetime

Transport Configuration โ€” AcpTransportConfig

us.nineworlds.book.features.acp.AcpTransportConfig is a sealed interface with exactly two variants:

sealed interface AcpTransportConfig {
    data object Stdio : AcpTransportConfig
    data class StreamableHttp(
        val host: String = "localhost",
        val port: Int = 8080,
    ) : AcpTransportConfig
}
  • Stdio โ€” default for all Xcode and CLI-registered ACP agents.

  • StreamableHttp(host, port) โ€” reserved for future HTTP-capable IDEs. Not yet supported by ACP SDK v0.25.0; AcpServerImpl.start() throws NotImplementedError when this variant is active.

AcpServerImpl.start() contains an exhaustive when(config.transport) with no else branch โ€” adding a new variant without a corresponding branch is a compile error. The CLI flag value is http (not streamable-http):

--acp-transport stdio   โ†’  AcpTransportConfig.Stdio
--acp-transport http    โ†’  AcpTransportConfig.StreamableHttp(host, port)

AcpStartConfig carries the transport: data class AcpStartConfig(val transport: AcpTransportConfig = Stdio, …​).

Per-Session _meta โ€” AcpMetaParser

us.nineworlds.book.features.acp.session.AcpMetaParser parses _meta: JsonElement? from ACP prompt or session/new requests into AgentSessionConfig?. Keys are namespaced under book. (e.g. book.maxTurns). Returns null when _meta is absent, not a JsonObject, or no book. keys are present. The hasAnyOverride() guard prevents callers from receiving a semantically-empty config.

Session Seams (AcpAgentSession Decomposition)

AcpAgentSession.prompt() is decomposed into five named seams:

  • resolveClientOps โ€” client operations resolution fallback (planned extraction to AcpOpsResolver in Spec 6).

  • handleSlashCommand โ€” Extracted (Spec 5): slash-command termination owned by AcpSlashCommandRouter in us.nineworlds.book.features.acp.session.runtime. The router routes /-prefixed prompt text to the handler port and returns the terminal Event.PromptResponseEvent; the executor’s slash branch awaits that terminal event and never invokes the agent loop for slash turns. The router signature carries no AcpAgentSession back-reference (R-018) โ€” the cycle closes through the ClientSessionOperations seam.

  • applyMetaOverrides โ€” Extracted (Spec 3): _meta parsing, model switching, refresh, guarded safeAgentModel, and after-switch re-notification owned by AcpModelController in us.nineworlds.book.features.acp.session.runtime. availableModels/defaultModel/sessionEffort remain delegating read-properties on AcpAgentSession (Variant 2a).

  • mapAgentEvents โ€” Extracted (Spec 2): Turn pipeline, volatile fields (activeRunJob, activeCollectJob, activeChannelSnapshot), and cancel() contract owned by AcpTurnExecutor in us.nineworlds.book.features.acp.session.runtime.

  • persistTurn โ€” turn history persistence (planned extraction to AcpSessionStore in Spec 4).

postInitialize() โ€” Thin Orchestrator (Spec 6)

postInitialize() is decomposed into four delegated steps, executed in this exact order (order matters: history replay precedes the commands update so the client sees narrative before the menu):

  1. resolveClientOps() โ€” early return with a warning when the client offers no operations port.

  2. historyReplay.replay(conversationHistory, ops, logger) โ€” Extracted (Spec 6): classification + emission owned by AcpHistoryReplay/DefaultAcpHistoryReplay in us.nineworlds.book.features.acp.session.runtime. The replayer is stateless and pure (classification + emission only, no transport or session state); one bad message is warn-logged and skipped, never aborting the replay (R-028).

  3. configOptionsController.emitAvailableCommandsUpdate() โ€” the available-commands mapping (SlashCommandRegistry.forMode(forAcp = true) โ†’ AvailableCommand) lives in the controller that owns the registry.

  4. modelController.bootstrapInitialModel() + async refreshModelOptions() โ€” initial model application and the background model list refresh.

Final Constructor Shape (Spec 5, R-020)

AcpAgentSession carries the five spec-5 parameters plus a defaulted sixth collaborator introduced by Spec 6 (historyReplay: AcpHistoryReplay = DefaultAcpHistoryReplay()), keeping the legacy five-argument call sites source-compatible:

AcpAgentSession(
    sessionId: SessionId,
    turnExecutor: AcpTurnExecutor,
    modelController: AcpModelController,
    configOptionsController: AcpConfigOptionsController,
    sessionOrchestrator: SessionOrchestrator
)

The @Suppress("LongParameterList") annotation has been deleted (R-020 gate). DI wiring and test fixtures construct sessions via the AcpAgentSession.create(…​) companion factory, which builds the default executor and controllers from raw collaborators (agent loop, slash-command handler/router, registry, system prompt, initial history, start config).

DI Wiring

AppGraph.provideAcpServerDependencies() assembles AcpServerDependencies from existing AppScope bindings. AppGraph.provideAcpServer() constructs AcpServerImpl(dependencies) and binds it as AcpServer. ServeCommand in :cli (thin Clikt wrapper) receives AcpServer and calls acpServer.start(AcpStartConfig()) in its run(). AppGraph also exposes mcpClientFacade: McpClientFacade for use by BookArgCommand’s `--mode mcp path.

AgentLoopFactory โ€” per-session mechanism

us.nineworlds.book.domain.agentloop.AgentLoopFactory is a functional interface defined in :domain:

fun interface AgentLoopFactory {
    fun create(ctx: QSessionContext?, env: AgentLoopEnvironment): QAgentSession
}

QAgentSession is a data class holding the AgentLoop and its SessionOrchestrator. Each call to create() constructs a fresh, isolated AgentLoop โ€” no shared mutable state between sessions. AgentLoop is no longer annotated @SingleIn(AppScope::class).

Xcode tools โ€” deleted

XcodeReadFileTool, XcodeWriteFileTool, and XcodeTerminalTool have been deleted. They have been superseded by AcpFileSystem and AcpProcessRunner in us.nineworlds.book.features.acp.capabilities, which are wired into the per-session AgentLoopEnvironment by AcpAgentSupport.buildEnvironmentFromCapabilities(). The agent now accesses the Xcode file-system and terminal indirectly through the standard ToolCallContext.fileSystem / ToolCallContext.processRunner path rather than through bespoke ACP-registered tool classes.

The ClientOperationsHolder singleton (formerly used to thread ClientSessionOperations between ACP callbacks and Xcode tools) was also deleted as part of this refactor. Both AcpFileSystem and AcpProcessRunner accept a () → ClientSessionOperations supplier lambda instead โ€” evaluated lazily at call time via the session’s activeOps reference. No global mutable state is involved.

Ring Boundary

:features:acp depends on :domain and :infrastructure. It must never depend on :cli. The bk serve Clikt entry-point remains in :cli as the thin wrapper; all ACP/MCP SDK types are confined to :features:acp and :features:mcp.


:jvm:scripting (Kotlin Scripting Extension Module)

Houses the JVM Kotlin Scripting engine (us.nineworlds.book.scripts) and kotlin-scripting-* dependencies.

  • KtsToolLoader: Discovers and loads .bk.kts scripts asynchronously in a background coroutine scope. Injects ProcessRunner (alongside ExtensionRegistry, ToolRegistry, and ExtensionContext) into BookScriptReceiver at load time. Holds BasicJvmScriptingHost as a single constructor-held property.

  • BookScriptDefinition: Defines @KotlinScript base class (BookScriptBase) and compilation configuration for .bk.kts scripts.

  • BookScriptCompilation: Configures default imports, classpath dependencies, and JVM target options for .bk.kts compilation.

  • BookScriptReceiver: Implicit receiver DSL for .bk.kts scripts. Carries scriptPath: okio.Path explicitly per evaluation context. Exposes tool {}, registerCommand, registerEventHandler, registerInterceptor, ctx, and processRunner directly in script scope. '''

:cli (Interface Layer)

The entry point and user interface. After the TUI God-class decomposition (ADR-20260713), the cli module is organized into focused sub-packages. See TUI Architecture for a full description of the frame layout, prompt rendering, cursor positioning, and file attachment completion.

us.nineworlds.book.cli.entry โ€” Process entry point, command parsing, and logging

  • Main.kt / BookArgCommand โ€” Clikt command entry point. Session resume logic, model selection, system-prompt loading, and mode execution delegation to AcpModeRunner, HeadlessModeRunner, and TuiModeRunner. Key CLI flags:

  • --mode โ€” repeatable enum<RunMode> option (values: tui, acp, mcp; default: tui). Activates ACP server, MCP client, or explicit TUI mode. headless is NOT a valid --mode value โ€” headless is derived from -p/--prompt.

  • --acp-transport โ€” stdio (default) or http. Controls the transport AcpServerImpl binds.

  • --acp-host โ€” bind address for --acp-transport http (default: localhost).

  • --acp-port โ€” TCP port for --acp-transport http (default: 8080).

  • When --mode acp and --mode tui are both present, a warning is emitted to stderr and ACP wins.

  • When --mode mcp is present (and ACP is not), McpClientFacade.connect() is called at startup with servers from ConfigManager.externalToolServers(cwd).

  • Launcher.kt โ€” Entry point wrapper handling output stream redirection.

  • CliLogger.kt โ€” CLI operational logger adapter.

us.nineworlds.book.cli.di โ€” Dependency Injection graph

  • AppGraph โ€” Metro DI graph; composes feature provider modules (TuiModule, AgentLoopModule, ToolsModule, InfrastructureModule).

  • TuiModule โ€” Provider interface for TUI subsystem dependencies (Terminal, TuiRenderer, Tui, CliLogger, SlashCommandRegistry).

  • AgentLoopModule โ€” Provider interface for agent loop and LLM execution dependencies (AgentLoopEnvironment, AgentLoopStateMachine, AgentLoopFactory, Agent, RetryConfig, ProviderConfig, PromptExecutorFactory, LLMClientAPI, CompactionPolicy).

  • ToolsModule โ€” Provider interface for tools, skills, prompt loader, extensions, ACP, MCP, and mode runner dependencies (ToolRegistry, ExtensionRegistry, SkillRegistry, ExtensionContext, SystemPromptLoader, McpClientFacade, AcpServerDependencies, AcpServer, AcpModeRunner, HeadlessModeRunner, TuiModeRunner, ModeExecutionDispatcher, ServeCommand, Set<Tool>).

  • InfrastructureModule โ€” Provider interface for core infrastructure I/O, process, and session dependencies (FileSystem, ConfigManager, SessionManager, SessionAutoNamer, DynamicLogRouter, SessionOrchestrator, DefaultSessionResolver, ProcessRunner).

us.nineworlds.book.cli.runners โ€” Execution Mode Runners

  • ModeRunner โ€” Common interface contract for CLI execution mode runners.

  • AcpModeRunner โ€” Encapsulates ACP mode startup, job synchronization, and stdio stdout protection. bk --mode acp and ServeCommand (bk serve) delegate execution to AcpModeRunner.

  • HeadlessModeRunner โ€” Encapsulates single-prompt headless execution, initializing AgentEventProcessor and HeadlessRunner.

  • TuiModeRunner โ€” Encapsulates interactive TUI session execution, configuring Tui with system prompt and starting interactive execution.

  • ModeExecutionDispatcher โ€” Central orchestration dispatcher (ModeExecutionDispatcher.dispatch(…​)) handling early ACP server routing, external MCP server connections (--mode mcp), and delegation to headless or TUI runners.

  • ModeDispatchContext โ€” Data container holding environment, mode set, ACP start config, loading jobs, prompts, initial messages, and session state passed to ModeExecutionDispatcher.

us.nineworlds.book.cli.commands โ€” CLI subcommands and setup wizards

  • SessionsCommand โ€” bk sessions sub-command family (SessionsListCommand, SessionsRmCommand, SessionsClearCommand).

  • InitWizard โ€” Project initialization wizard (invoked by /init).

us.nineworlds.book.cli.commands.acp โ€” ACP server subcommand

  • ServeCommand โ€” Deprecated Clikt sub-command bk serve (@Deprecated("Use 'bk --mode acp' instead")) delegating execution directly to AcpModeRunner.

us.nineworlds.book.cli.approval โ€” Extension UI approval adapters

  • ApprovalStrategy โ€” Strategy interface for prompt formatting, console checking, and tool approval execution across headless and TUI modes.

  • HeadlessApprovalStrategy โ€” Headless console implementation of ApprovalStrategy providing standard y/n/a prompts and console availability checks.

  • InteractiveTuiApprovalStrategy โ€” Interactive TUI implementation of ApprovalStrategy managing diff overlay rendering via DiffRenderer and key-handling suspension via ToolApprovalPrompt.

  • ToolApprovalController โ€” Encapsulates interactive vs. headless approval mode transitions and fail-safe terminal state restoration.

  • DelegatingExtensionUI / MordantExtensionUI / TuiApprovalExtensionUI โ€” Tool approval flow and UI delegation, leveraging injected ApprovalStrategy instances.

  • ToolApprovalPrompt โ€” Manages the pending tool-approval deferred.

us.nineworlds.book.cli.tui.render โ€” Rendering and diff visualization

  • DiffSyntaxColorizer โ€” Line-level colorizer styling unified diff syntax (+ green, - red, @@ cyan, +/โ€” dim, context gray) with Mordant.

  • HeaderRenderer โ€” Generates the ASCII banner and session name header.

  • MessageListRenderer โ€” Formats the scrolling grid of message history and streaming content.

  • PromptBoxRenderer โ€” Manages the user input area character wrapping.

  • StatusBarRenderer โ€” Renders the progress spinner and thinking status.

  • DiffRenderer โ€” Unified diff widget used in approval prompts and TUI diff overlay, delegating line styling to DiffSyntaxColorizer.

us.nineworlds.book.cli.session โ€” Session lifecycle

  • SessionOrchestrator โ€” Owns the full session lifecycle: resolve by ID/fragment/most-recent, persist messages, fork/branch, auto-name, and dispatch session lifecycle extension events (SessionStart, SessionShutdown, ResourcesDiscover).

us.nineworlds.book.cli.tui โ€” TUI shell and shared state

  • Tui โ€” TUI lifecycle and wiring (~290 lines). Owns start(), constructs and wires all sub-components, holds lastState/isAgentRunning timing fields, and implements AgentLoopConfig by delegating to TuiAgentConfig. Also defines the TuiScreen enum (CHAT, MODEL_SELECTION, SESSION_SELECTION, EFFORT_SELECTION).

  • TuiAgentConfig โ€” Implements AgentLoopConfig; resolves BOOK_* environment variables (BOOK_MAX_TURNS, BOOK_DISABLE_PRUNING, BOOK_MAX_UNPRODUCTIVE_TURNS, BOOK_CACHE_MAX_TURN_AGE) at CLI startup to populate loop limits and pruning settings; owns the steering/follow-up message queues and factories for ExtensionContext / ExtensionCommandContext.

  • UiNoticeBoard โ€” Thread-safe owner of ephemeral UI-only notices (skill loaded, session resumed) that survive agent-loop resets without being sent to the LLM.

us.nineworlds.book.cli.tui.navigation โ€” Navigation & Screen Transitions

  • ScreenNavigator / DefaultScreenNavigator โ€” Manages active screen state (activeScreen), modal screen controller references (activeController), transition navigation (navigateTo), and modal dismissal (dismissCurrent, Escape key delegation).

us.nineworlds.book.cli.tui.input โ€” Keyboard handling and file completion

  • InputStateMachine โ€” Dispatches KeyboardEvent`s to the correct handler based on current screen mode. Owns paste detection, scroll state, completion overlay state, `@/# file-token scanning, and updateCompletions() / applySelectedCompletion().

  • InputHistory โ€” Persistent input history (~/.bk/history.txt), navigated with Alt+Up/Down.

  • ExternalEditorLauncher โ€” Launches $VISUAL/$EDITOR on Ctrl+G; manages temp-file lifecycle.

  • FileCompleter โ€” Lists CWD entries matching a partial path token typed after @ or #. Pipeline: root guard โ†’ sub-path resolution โ†’ prefix filter โ†’ dotfile exclusion โ†’ .gitignore filter โ†’ directory-first sort โ†’ cap at 8. Injected into InputStateMachine via constructor parameter for testability.

  • GitIgnoreFilter โ€” Lazy .gitignore parser. Supports four pattern forms: single-segment wildcard (.class), multi-segment wildcard (build/*), /-anchored literal (/build), and directory-only suffix (node_modules/). Returns false when the file does not exist.

us.nineworlds.book.cli.tui.commands โ€” Slash command routing

  • SlashCommandRouter โ€” Registers 11 built-in commands, checks extension commands first, dispatches to the correct handler, and provides completions(partial) for tab-completion. Calls TuiAgentConfig.buildCommandContext() for extension command execution.

  • Completion โ€” Sealed interface shared by command and file completions. CommandCompletion carries a slash-prefixed displayName; FileCompletion carries name, relativePath, isDirectory, and auto-derived displayName (trailing / for directories) and emoji description.

us.nineworlds.book.cli.tui.render โ€” Frame building and render loop

  • TuiRenderCoordinator โ€” Manages TUI render loop state, thread-safe dirty state signaling (@Volatile renderDirty), frame snapshot orchestration, and active extension progress tracking via ActiveProgressRegistry.

  • TuiRenderer โ€” Coordinates layout sizing and delegates TUI region widget building to specialized component renderers (HeaderRenderer, MessageListRenderer, PromptBoxRenderer, StatusBarRenderer, FooterRenderer). Referenced by RenderFrameBuilder.

  • RenderFrameBuilder โ€” Assembles a full-screen Mordant Widget from a FrameSnapshot. Handles screen routing (MODEL_SELECTION / SESSION_SELECTION / CHAT), UiNoticeBoard notice merging, viewport height calculation, and all overlay conditionals (status, approval, completions).

  • RenderLoop โ€” Owns the render coroutine: throttles to ~20 fps (50 ms), advances the spinner at 120 ms, wraps each frame in synchronized-output markers ([?2026h/l) for iTerm2/kitty, and positions the hardware cursor via computeCursorPosition.

  • FrameSnapshot โ€” Immutable point-in-time snapshot of all Tui state needed for a single frame. Built by Tui.buildSnapshot(spinnerFrame) on each render tick.

  • CursorPosition (CursorPosition.kt) โ€” Pure arithmetic: CursorParams, CursorPosition, countPromptRows, computeCursorPosition. Anchors the hardware cursor by computing rowStart = terminalHeight โˆ’ footerHeight โˆ’ totalPromptRows, independent of variable-height overlays above the prompt.

us.nineworlds.book.cli.screens โ€” Self-sufficient selection UIs

  • ModelSelectionScreen โ€” Arrow-key model picker. load(agentLoop, fallback, onError) companion factory fetches models from the API (or falls back to provider list) and creates the screen.

  • SessionSelectionScreen โ€” Type-to-filter session picker with relative timestamps. open(sessionManager) companion factory returns null when no sessions exist.

  • ForkScreen โ€” Interactive fork-point selection. show() runs the BeforeFork intercept, renders the message list, and calls SessionOrchestrator.fork() on selection.

  • TreeScreen โ€” Interactive branch-point selection. show() runs the BeforeTree intercept.

us.nineworlds.book.cli.agent โ€” Agent event processing and headless execution

  • AgentEventProcessor โ€” Processes AgentEvent emissions: dispatches AgentStart/AgentEnd extension events, detects skill activations via read_file path inspection, and triggers session persistence and auto-naming via SessionOrchestrator.

  • HeadlessRunner โ€” Executes a single prompt headlessly (-p flag): wires HeadlessProgress spinner, collects events for text output and error display, runs the agent loop to completion, and prints session info.

  • HeadlessProgress โ€” stderr-based spinner for headless mode. TTY-aware (skips output when piped); injectable isTty flag for testability.

us.nineworlds.book.cli.commands.acp โ€” ACP entry-point (thin Clikt wrapper only)

  • ServeCommand โ€” Clikt sub-command bk serve. Annotated with @Deprecated("Use 'bk --mode acp' instead"). Thin wrapper delegating execution directly to AcpModeRunner. Has zero ACP/MCP SDK imports โ€” all server logic lives in :features:acp. AcpModeRunner is injected via AppGraph.

All other ACP types (AcpAgentSupport, AcpAgentSession, AcpEventMapper, AcpSessionServices, Xcode tools) have been moved to :features:acp. :cli no longer declares acp-core, acp-model, or mcp-sdk-client as implementation dependencies โ€” the ring boundary is compiler-enforced.

  • Commands: CLI entry points and slash commands defined with Clikt.

  • AppGraph: The Dependency Injection graph using Metro. '''

Architecture Diagrams

Visual representations of Book’s architecture are available in the diagrams/ directory. All diagrams are in PlantUML format (.puml). Class diagrams use !pragma layout smetana and require no external Graphviz installation.

Module Structure

Sequence Diagrams

  • ACP Session Lifecycle โ€” Full ACP session lifecycle (session/new, session/set_config_option, prompt, slash commands, session/cancel, teardown) with AcpModelController model switching

  • Agent Loop Main Cycle โ€” Full turn-by-turn execution sequence including BeforeAgentStart intercept, pruning pipeline, nextTurn() streaming, tool call dispatching, cache/loop-guard fast-paths, and compaction

  • Tool Execution Strategy โ€” Parallel vs. sequential tool execution with PureToolResultCache cache-first and RepeatCallDetector loop-guard branches

  • Token Optimisation Pipeline โ€” Swimlane activity diagram covering ToolResultPruner, AssistantMessagePruner, ThinkingPruner, PureToolResultCache, RepeatCallDetector, and context compaction

  • KoogAgent Streaming โ€” LLM provider integration: KoogAgent request-building, StreamOrchestrator stream lifecycle (watchdog wiring, frame collection, error discrimination, fallback completion with arg finalization, extension dispatch, interaction logging), StreamFrameHandler frame dispatch (including empty-delta suppression, ToolCallDelta and blank-name ToolCallComplete accumulation paths), and model listing

  • LiteRT-LM Streaming & Sequence โ€” On-device LiteRT-LM provider streaming: sendMessageAsync with MessageCallback + Channel bridge, real-time delta emission to AgentLoop, and eager model initialization

  • KTS Extension Loading โ€” Extension discovery and .bk.kts script registration

  • Model Id Resolution โ€” How ModelKeyMatcher folds a caller-supplied id (gateway prefixes, colon tags, dotted vendors, provider qualifiers) onto a catalogue key, including the Ambiguous outcome

Class Diagrams

  • Agent Loop Main โ€” Class Diagram โ€” Complete class structure for the main execution cycle: AgentLoop, AgentState, AgentPhase, AgentLoopConfig and all context/result types, Agent, ModelMetadata, ModelKeyMatcher, full AgentEvent sealed hierarchy, Message hierarchy (UserMessage, AssistantMessage, ToolResultMessage, SystemMessage), AssistantContent / Content sealed types, Usage / Cost, and all five token-optimisation classes (ToolResultPruner, AssistantMessagePruner, ThinkingPruner, PureToolResultCache, RepeatCallDetector)

  • Tool Execution Strategy โ€” Class Diagram โ€” Focused class structure for tool execution: AgentLoop (tool-execution surface), AgentLoopConfig before/after hooks, Tool (with executionMode), ToolRegistry, ToolResult, PureToolResultCache, RepeatCallDetector, and the AgentEvent.ToolExecution* event subclasses

  • Gallery App & Bridge Component Architecture โ€” Class and component architecture mapping Gallery UI, Gallery Bridge, Book Domain AgentLoop, and LiteRT-LM Provider layer

Additional Documentation