Module Map
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
:domaincore 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 usingokio.Pathandkotlinx.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 ofTuiThemeproviding 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)@Injectimplementation ofAgentLoopEnvironment. ReceivesFileSystemandProcessRunnervia constructor injection and exposes them as the properties defined by the interface. Wired throughAppGraph. -
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. Loadsmodel_metadata.jsonand delegates id resolution toModelKeyMatcher(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 exposesexternalToolServers(cwd: String): List<ExternalToolServer>which merges two.bk/mcp.jsonfiles:~/.bk/mcp.json(global, lowest priority) and<cwd>/.bk/mcp.json(project-local). Merge rule: project-local entries override global entries with the samename; entries unique to either file are retained. ReturnsemptyList()when both files are absent or malformed. Used byServeCommandto populateExternalToolServerentries for thebook servestart-up path. -
session/(us.nineworlds.book.infrastructure.session): Session stack withSessionManager(JSONL persistence, branching/tree, labels, compaction entries),DefaultSessionResolver(resume lookup/listing),SessionAutoNamer(first-turn auto title generation), andDynamicLogRouter(CacheMap-backed thread-safe routing of session-scoped log files).SessionManager.appendThinkingLevelChange(thinkingLevel: String)writes aThinkingLevelChangeEntrylinked to the current leaf and returns its id;buildSessionContext()replays the most recent entry intoSessionContext.thinkingLevel. Callers convertEffortLeveltoapiValuebefore passing it in โ the orchestrator stores the string verbatim. -
process/(us.nineworlds.book.infrastructure.process):ProcessRunnerinterface,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 bundledripgrep.bk.ktsextension in the:extensionsmodule provides a full-featuredripgreptool โ see Bundled Extensions below. -
GrepTool: Searches file content via Ripgrep (rg) or systemgrep -E. Supportspattern,path,include,exclude,context,beforeContext,afterContext,maxCount,filesOnly(filenames-only,-l),countOnly(per-file match counts,--count/-c), andincludeGlobs(multiple file-type globs, e.g.['.kt', '.kts']).normalizeArgumentsremaps snake_case aliases to camelCase. -
FindTool: Locates files by glob pattern via fd or systemfind. Supportspattern,path,limit,type(f/dto filter files vs. directories),maxDepth(max traversal depth),excludePath(prune a subtree),modifiedWithinDays(recency filter in days), andnewerThan(reference-file recency filter).newerThanforces the system-find fallback path.normalizeArgumentsremaps snake_case aliases to camelCase. -
skills/(us.nineworlds.book.infrastructure.skills):MarkdownSkillLoaderโ loads skills from Markdown files into theSkillRegistry. -
utils/(us.nineworlds.book.infrastructure.utils): Shared utilities (e.g.,Mimetype 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 viaToolMapper, fires theBeforeProviderRequestintercept, logs outbound payloads via the session-scopedKoogTransportLogger, then delegates the entire stream lifecycle toStreamOrchestratorviaemitAll.nextTurnis ~40 lines with one level of nesting. Model listing delegates toLLMClientAPI.models()(implemented by Koog’sOpenAILLMClient) and enriches results viaModelMetadataRegistry; models absent from the registry are returned as minimalModelMetadata(id)entries. When building theLLModel, a registry hit withsupportsReasoning == trueaddsLLMCapability.Thinkingso Koog enables thinking-capable request handling; a miss leaves the capability off.KoogAgentimplementsReasoningAgent(SPEC-2, per ADR-20261002 (prompts/plans/adr/ADR-20261002-llm-reasoning-modes.md)): it exposesoverride var effort: EffortLevel(defaultEffortLevel.DEFAULT=HIGH) and, atbuildKoogPrompt()time, delegates the effort into the Koog request asreasoning_effortinsideLLMParams.additionalPropertiesโ Koog 1.3.0 has no first-class effort field, and itsAdditionalPropertiesFlatteningSerializermerges these entries into the OpenAI wire JSON. Emission is gated on bothmetadataRegistry.lookup(model)?.supportsReasoning == trueandeffort != EffortLevel.OFF; non-reasoning or unknown models, andOFF, omit the key entirely while the caller’s preference stays preserved on the agent.buildKoogPrompt()is fully multi-modal:UserMessageentries containingContent.Imageparts are mapped toContentPart.Imageinside auser {}block;ToolResultMessageentries containingContent.Imageparts emit a texttool { result(…) }block followed by a syntheticuser {}block carrying the images asContentPart.Image(required because Koog 0.8.0’sMessage.Tool.Resultis text-only). Images are passed asAttachmentContent.Binary.Base64โ the base64 string produced byReadFileToolis 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 astreamFactorylambda, collectsStreamFrame`s through `StreamFrameHandler, wires theInactivityWatchdog(defaults: 600 s stream timeout, 30 s inactivity threshold โ tuned for large tool-call generations), discriminatesCancellationExceptionfrom hard errors, handles all three fallback-completion branches (gotEnd,!gotEnd+content,!gotEnd+noContent), dispatches theAfterProviderResponseextension event, and callsonInteraction(wired toKoogTransportLogger::logInteraction). When the stream stalls beforeStreamFrame.End, the fallback path finalizes any accumulated tool-call arguments before emitting the fallbackCompletedevent. -
StreamFrameHandler(us.nineworlds.book.providers.koog): Converts rawStreamFrame`s into `AgentEvent`s. Handles `TextDelta,ReasoningDelta, namedToolCallComplete/ToolCallDelta(start a new tool call), blank-nameToolCallComplete/ToolCallDelta(accumulate incremental argument chunks), andEnd(finalize and emitCompleted). Zero-lengthTextDelta/ReasoningDeltaframes are suppressed at this provider boundary (noAgentEventemitted) โ 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/ThinkingDeltathat 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\nchunk 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 bothToolCallDeltaand blank-nameToolCallCompleteframes into an index-keyedStringBuildermap and are finalized on both the normalEndpath and the stall/timeout fallback path โ preventing empty{}argument dispatches on large streamed payloads. For gateways that double-emit each tool-call event (an identicalToolCallDeltaimmediately followed by aToolCallComplete), it de-duplicates opposite-type adjacent frames by signature (id+ normalizedname+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 eachExternalToolServer, performs MCPinitialize+tools/list, wraps each discovered tool asMcpToolAdapter(ToolSource.MCP), and registers it in the providedToolRegistry. Call-timetoolRegistryparameter (ADR ยง4.3) โ not stored at construction. -
disconnectโ Closes all active client connections, kills subprocesses, and deregisters all tracked MCP tools fromToolRegistry. -
registeredToolsโ Returns a snapshot of the currently trackedToollist.
Internal Structure
| Package | Class | Responsibility |
|---|---|---|
|
|
Public interface โ the only type |
|
|
Concrete implementation of |
|
|
Adapts an MCP SDK |
|
|
Wraps |
|
|
Metro DI graph; scoped to one MCP activation lifecycle โ independent of |
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
-
For each
ExternalToolServerinservers,McpClientManagerspawns aProcessBuildersubprocess. -
Wraps
StdioClientTransportwithIntegerIdTransport. -
Calls
client.connect(transport)with a 10 s timeout; servers that do not respond are skipped. -
Sends
tools/list(10 s timeout); discovered tools are wrapped asMcpToolAdapterand registered. -
On
disconnect, all clients are closed and all tracked tools are deregistered viaToolRegistry.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.
:clihas zeroimplementationorapideclarations foracp-core,acp-model, ormcp-sdk-client. Any accidental SDK import in:clisource 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, initialisesAcpAgentSupport, and blocks until stdin EOF. -
stopโ Cancels all in-flight session loops viaAgentLoop.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 |
|---|---|---|
|
|
Public lifecycle interface |
|
|
Production impl; |
|
|
Process-scope collaborators bound once at |
|
|
Per-start transport config (transport flags) |
|
|
|
|
|
ACP |
|
|
Interface & |
|
|
Deep module interface & |
|
|
Interface & |
|
|
Narrow seam replacing |
|
|
Interface & |
|
|
Interface & |
|
|
Pure option builders ( |
|
|
ACP |
|
|
Implements |
|
|
Implements |
|
|
Lightweight |
|
|
Pure stateless mapper from |
|
|
Metro |
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()throwsNotImplementedErrorwhen 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 toAcpOpsResolverin Spec 6). -
handleSlashCommandโ Extracted (Spec 5): slash-command termination owned byAcpSlashCommandRouterinus.nineworlds.book.features.acp.session.runtime. The router routes/-prefixed prompt text to the handler port and returns the terminalEvent.PromptResponseEvent; the executor’s slash branch awaits that terminal event and never invokes the agent loop for slash turns. The router signature carries noAcpAgentSessionback-reference (R-018) โ the cycle closes through theClientSessionOperationsseam. -
applyMetaOverridesโ Extracted (Spec 3):_metaparsing, model switching, refresh, guardedsafeAgentModel, and after-switch re-notification owned byAcpModelControllerinus.nineworlds.book.features.acp.session.runtime.availableModels/defaultModel/sessionEffortremain delegating read-properties onAcpAgentSession(Variant 2a). -
mapAgentEventsโ Extracted (Spec 2): Turn pipeline, volatile fields (activeRunJob,activeCollectJob,activeChannelSnapshot), andcancel()contract owned byAcpTurnExecutorinus.nineworlds.book.features.acp.session.runtime. -
persistTurnโ turn history persistence (planned extraction toAcpSessionStorein 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):
-
resolveClientOps()โ early return with a warning when the client offers no operations port. -
historyReplay.replay(conversationHistory, ops, logger)โ Extracted (Spec 6): classification + emission owned byAcpHistoryReplay/DefaultAcpHistoryReplayinus.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). -
configOptionsController.emitAvailableCommandsUpdate()โ the available-commands mapping (SlashCommandRegistry.forMode(forAcp = true)โAvailableCommand) lives in the controller that owns the registry. -
modelController.bootstrapInitialModel()+ asyncrefreshModelOptions()โ 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).
Session Runtime Diagram
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.ktsscripts asynchronously in a background coroutine scope. InjectsProcessRunner(alongsideExtensionRegistry,ToolRegistry, andExtensionContext) intoBookScriptReceiverat load time. HoldsBasicJvmScriptingHostas a single constructor-held property. -
BookScriptDefinition: Defines@KotlinScriptbase class (BookScriptBase) and compilation configuration for.bk.ktsscripts. -
BookScriptCompilation: Configures default imports, classpath dependencies, and JVM target options for.bk.ktscompilation. -
BookScriptReceiver: Implicit receiver DSL for.bk.ktsscripts. CarriesscriptPath: okio.Pathexplicitly per evaluation context. Exposestool {},registerCommand,registerEventHandler,registerInterceptor,ctx, andprocessRunnerdirectly 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 toAcpModeRunner,HeadlessModeRunner, andTuiModeRunner. Key CLI flags: -
--modeโ repeatableenum<RunMode>option (values:tui,acp,mcp; default:tui). Activates ACP server, MCP client, or explicit TUI mode.headlessis NOT a valid--modevalue โ headless is derived from-p/--prompt. -
--acp-transportโstdio(default) orhttp. Controls the transportAcpServerImplbinds. -
--acp-hostโ bind address for--acp-transport http(default:localhost). -
--acp-portโ TCP port for--acp-transport http(default:8080). -
When
--mode acpand--mode tuiare both present, a warning is emitted to stderr and ACP wins. -
When
--mode mcpis present (and ACP is not),McpClientFacade.connect()is called at startup with servers fromConfigManager.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 acpandServeCommand(bk serve) delegate execution toAcpModeRunner. -
HeadlessModeRunnerโ Encapsulates single-prompt headless execution, initializingAgentEventProcessorandHeadlessRunner. -
TuiModeRunnerโ Encapsulates interactive TUI session execution, configuringTuiwith 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 toModeExecutionDispatcher.
us.nineworlds.book.cli.commands โ CLI subcommands and setup wizards
-
SessionsCommandโbk sessionssub-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-commandbk serve(@Deprecated("Use 'bk --mode acp' instead")) delegating execution directly toAcpModeRunner.
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 ofApprovalStrategyproviding standardy/n/aprompts and console availability checks. -
InteractiveTuiApprovalStrategyโ Interactive TUI implementation ofApprovalStrategymanaging diff overlay rendering viaDiffRendererand key-handling suspension viaToolApprovalPrompt. -
ToolApprovalControllerโ Encapsulates interactive vs. headless approval mode transitions and fail-safe terminal state restoration. -
DelegatingExtensionUI/MordantExtensionUI/TuiApprovalExtensionUIโ Tool approval flow and UI delegation, leveraging injectedApprovalStrategyinstances. -
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 toDiffSyntaxColorizer.
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). Ownsstart(), constructs and wires all sub-components, holdslastState/isAgentRunningtiming fields, and implementsAgentLoopConfigby delegating toTuiAgentConfig. Also defines theTuiScreenenum (CHAT,MODEL_SELECTION,SESSION_SELECTION,EFFORT_SELECTION). -
TuiAgentConfigโ ImplementsAgentLoopConfig; resolvesBOOK_*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 forExtensionContext/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โ DispatchesKeyboardEvent`s to the correct handler based on current screen mode. Owns paste detection, scroll state, completion overlay state, `@/#file-token scanning, andupdateCompletions()/applySelectedCompletion(). -
InputHistoryโ Persistent input history (~/.bk/history.txt), navigated withAlt+Up/Down. -
ExternalEditorLauncherโ Launches$VISUAL/$EDITORon 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 โ.gitignorefilter โ directory-first sort โ cap at 8. Injected intoInputStateMachinevia constructor parameter for testability. -
GitIgnoreFilterโ Lazy.gitignoreparser. Supports four pattern forms: single-segment wildcard (.class), multi-segment wildcard (build/*),/-anchored literal (/build), and directory-only suffix (node_modules/). Returnsfalsewhen 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 providescompletions(partial)for tab-completion. CallsTuiAgentConfig.buildCommandContext()for extension command execution. -
Completionโ Sealed interface shared by command and file completions.CommandCompletioncarries a slash-prefixeddisplayName;FileCompletioncarriesname,relativePath,isDirectory, and auto-deriveddisplayName(trailing/for directories) and emojidescription.
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 viaActiveProgressRegistry. -
TuiRendererโ Coordinates layout sizing and delegates TUI region widget building to specialized component renderers (HeaderRenderer,MessageListRenderer,PromptBoxRenderer,StatusBarRenderer,FooterRenderer). Referenced byRenderFrameBuilder. -
RenderFrameBuilderโ Assembles a full-screen MordantWidgetfrom aFrameSnapshot. Handles screen routing (MODEL_SELECTION / SESSION_SELECTION / CHAT),UiNoticeBoardnotice 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 viacomputeCursorPosition. -
FrameSnapshotโ Immutable point-in-time snapshot of all Tui state needed for a single frame. Built byTui.buildSnapshot(spinnerFrame)on each render tick. -
CursorPosition(CursorPosition.kt) โ Pure arithmetic:CursorParams,CursorPosition,countPromptRows,computeCursorPosition. Anchors the hardware cursor by computingrowStart = 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 returnsnullwhen no sessions exist. -
ForkScreenโ Interactive fork-point selection.show()runs theBeforeForkintercept, renders the message list, and callsSessionOrchestrator.fork()on selection. -
TreeScreenโ Interactive branch-point selection.show()runs theBeforeTreeintercept.
us.nineworlds.book.cli.agent โ Agent event processing and headless execution
-
AgentEventProcessorโ ProcessesAgentEventemissions: dispatchesAgentStart/AgentEndextension events, detects skill activations viaread_filepath inspection, and triggers session persistence and auto-naming viaSessionOrchestrator. -
HeadlessRunnerโ Executes a single prompt headlessly (-pflag): wiresHeadlessProgressspinner, 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); injectableisTtyflag for testability.
us.nineworlds.book.cli.commands.acp โ ACP entry-point (thin Clikt wrapper only)
-
ServeCommandโ Clikt sub-commandbk serve. Annotated with@Deprecated("Use 'bk --mode acp' instead"). Thin wrapper delegating execution directly toAcpModeRunner. Has zero ACP/MCP SDK imports โ all server logic lives in:features:acp.AcpModeRunneris injected viaAppGraph.
All other ACP types (
AcpAgentSupport,AcpAgentSession,AcpEventMapper,AcpSessionServices, Xcode tools) have been moved to:features:acp.:clino longer declaresacp-core,acp-model, ormcp-sdk-clientasimplementationdependencies โ 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
-
Module Dependency Graph โ All six Gradle modules, their edges, and ring boundary annotations (current target state)
-
Clean Architecture Ring Assignments โ Each module placed in its Clean Architecture ring with dependency-direction callouts
-
Domain Package Structure โ Detailed view of all
us.nineworlds.book.domainpackages, classes, and their inter-package relationships -
Module Dependencies โ Clean Architecture Layers โ Layer rings (
:domainโ:infrastructureโ:cli) and dependency flow -
ACP Session Decomposition โ ACP session runtime decomposition seams (
AcpTurnExecutor,AcpSlashCommandRouter,AcpModelController,AcpConfigOptionsController,ClientSessionOperations)
Sequence Diagrams
-
ACP Session Lifecycle โ Full ACP session lifecycle (
session/new,session/set_config_option,prompt, slash commands,session/cancel, teardown) withAcpModelControllermodel switching -
Agent Loop Main Cycle โ Full turn-by-turn execution sequence including
BeforeAgentStartintercept, pruning pipeline,nextTurn()streaming, tool call dispatching, cache/loop-guard fast-paths, and compaction -
Tool Execution Strategy โ Parallel vs. sequential tool execution with
PureToolResultCachecache-first andRepeatCallDetectorloop-guard branches -
Token Optimisation Pipeline โ Swimlane activity diagram covering
ToolResultPruner,AssistantMessagePruner,ThinkingPruner,PureToolResultCache,RepeatCallDetector, and context compaction -
KoogAgent Streaming โ LLM provider integration:
KoogAgentrequest-building,StreamOrchestratorstream lifecycle (watchdog wiring, frame collection, error discrimination, fallback completion with arg finalization, extension dispatch, interaction logging),StreamFrameHandlerframe dispatch (including empty-delta suppression,ToolCallDeltaand blank-nameToolCallCompleteaccumulation paths), and model listing -
LiteRT-LM Streaming & Sequence โ On-device LiteRT-LM provider streaming:
sendMessageAsyncwithMessageCallback+Channelbridge, real-time delta emission toAgentLoop, and eager model initialization -
KTS Extension Loading โ Extension discovery and
.bk.ktsscript registration -
Model Id Resolution โ How
ModelKeyMatcherfolds a caller-supplied id (gateway prefixes, colon tags, dotted vendors, provider qualifiers) onto a catalogue key, including theAmbiguousoutcome
Class Diagrams
-
Agent Loop Main โ Class Diagram โ Complete class structure for the main execution cycle:
AgentLoop,AgentState,AgentPhase,AgentLoopConfigand all context/result types,Agent,ModelMetadata,ModelKeyMatcher, fullAgentEventsealed hierarchy,Messagehierarchy (UserMessage,AssistantMessage,ToolResultMessage,SystemMessage),AssistantContent/Contentsealed 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),AgentLoopConfigbefore/after hooks,Tool(withexecutionMode),ToolRegistry,ToolResult,PureToolResultCache,RepeatCallDetector, and theAgentEvent.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