Architecture Overview
Audience: everyone โ this is the entry point to Book’s architecture: the
:domaincore abstractions, logging, design philosophies, and key dependencies.Per-module deep dives (infrastructure, providers, features, cli packages): see the Module Map. Diagram catalogue: Architecture Diagrams.
Module Responsibilities
:domain (Core)
Core business logic โ what Book actually does โ organized by feature into cohesive packages following Clean Architecture principles.
Core Abstractions (Root Level)
-
Agent: The primary abstraction for AI agents
-
ReasoningAgent: Capability interface extending
Agentfor LLMs with built-in thinking/reasoning modes (see ADR-20261002 (prompts/plans/adr/ADR-20261002-llm-reasoning-modes.md)). Declaresvar effort: EffortLevel(default agent effort) and a turn-localnextTurn(messages, tools, sessionLogger, effort)overload that transports turn-local effort without mutating shared instance state. DefaulteffortisEffortLevel.DEFAULT(HIGH) with the default supplied by implementors, since Kotlin interfaces cannot hold property state. Only agents that support reasoning implement this interface; non-reasoning agents (rule-based agents, simple test mocks) implementAgentonly, so no implementor is forced to carry unused reasoning state (Interface Segregation Principle). Callers should verify bothagent is ReasoningAgentandmodelMetadata.supportsReasoning == truebefore exposing reasoning controls. -
EffortLevel: Enum of seven reasoning-effort levels โ
OFF,MINIMAL,LOW,MEDIUM,HIGH,XHIGH,MAX. Each constant carriesapiValue, the lowercase verbatim string persisted in JSONL session logs (e.g.EffortLevel.XHIGH.apiValue == "xhigh").OFF,LOW,MEDIUM,HIGH, andXHIGHare compatible with standard Pi agent log parsers;MINIMALandMAXare Book-specific extensions serialized verbatim.EffortLevel.DEFAULTisHIGH. -
AppScope: Dependency injection scope marker
Feature Packages
-
agentloop/: Orchestrates the "Thinking โ Executing โ Learning" cycle
-
AgentLoop: Main orchestration driver. Not a singleton โ one instance is created per active session viaAgentLoopFactory. ConstructsTurnProcessorandTurnSession, drives the turn loop, and acts onTurnOutcomevariants. ExposescancelAndJoin()to cancel the in-flightrun()coroutine and await its completion (used byAcpServerImpl.stop()for graceful drain). -
TurnProcessor: Per-turn execution engine. Encapsulates context preparation, compaction, provider execution, streaming delta dispatch (handleStreamEvent), tool batching, circuit-breaker detection, and terminal error handling (abortTurn). ExposesexecuteTurn(). -
TurnSession: Mutable session state holder. HoldscurrentMessages,newMessages,unproductiveTurnscounter, andpendingSteeringMessagesacross turns in a singlerun()execution. -
TurnOutcome: Sealed outcome type (Continue,StopComplete,StopError,MaxTurnsReached) returned byTurnProcessor.executeTurn(). -
AgentLoopFactory: Functional interfacefun interface AgentLoopFactory { fun create(ctx: QSessionContext?, env: AgentLoopEnvironment): QAgentSession }. Called once persession/neworsession/loadin ACP mode to produce a fully isolatedQAgentSession. The production binding is anAppGraphlambda that constructs a freshAgentLoopeach time. -
QAgentSession: Data class returned byAgentLoopFactory.create(). HoldsagentLoop: AgentLoopandsessionOrchestrator: SessionOrchestrator. Passed toAcpAgentSessionat construction โ never shared across sessions. -
AgentLoopTypes: Configuration and context types (AgentLoopConfigowning loop turn limitsmaxTurnsandmaxUnproductiveTurns, pruning/cache settingsisPruningDisabledandcacheMaxTurnAge, and optional turn-localeffort,AgentContext,TurnContext, hook contexts/results) -
ToolCallExecutor: Tool-call execution pipeline (parallel/sequential dispatch, cache, loop guard, config hooks). Holds anAgentLoopEnvironment(injected; defaults to a no-op stub for test compatibility) and constructs a freshToolCallContext(fileSystem, processRunner)from it at a single call site insideexecuteWithCacheAndGuardbefore passing it totool.execute(). -
ToolCallContext: Single I/O carrier passed to everyTool.execute()invocation. CarriesfileSystem: FileSystem,processRunner: ProcessRunner, and optionaloutputContext: OutputContext?(defaultnull). Pure domain type โ zero:cli/:infrastructureimports. Tools must never resolveFileSystemorProcessRunnerfrom their own constructors; they read exclusively fromcallContext. -
AgentLoopEnvironment: Domain interface that bundlesfileSystem: FileSystemandprocessRunner: ProcessRunner. Held byToolCallExecutor; its fields are used to construct a freshToolCallContextfor every tool invocation. Production binding is provided by:cli’s `AppGraph. -
RunEnvironment: Sealed interface with exactly three variants โTui(interactive terminal),Headless(non-interactive-pflag),Server(ACP/MCP serve mode). Computed viaRunEnvironment.derive(modes.toSet(), headlessPrompt).isHeadless: Booleanis a permanent computed bridge property (val isHeadless: Boolean get() = environment != RunEnvironment.Tui) โ it must never be removed or stored as aBooleanfield; callers that only care about interactivity use it without needing to exhaustively match all variants. -
RunMode: Enum with three variants โTUI,ACP,MCP. Passed as aSet<RunMode>toRunEnvironment.derive().--modeonBookArgCommandaccepts this enum via Clikt.enum<RunMode>(ignoreCase=true).multiple()โ the flag is repeatable and case-insensitive (e.g.--mode acp --mode mcp).headlessis NOT aRunMode; headless execution is derived internally from the presence of-p/--prompt. -
AgentSessionConfig: Per-session token knobs forwarded intoAgentLoop.run(). All five fields default tonull("use system default"). Parsed from ACP_metaviaAcpMetaParser.toAgentSessionConfig(). Fields:maxTurns: Int?,maxUnproductiveTurns: Int?,cacheMaxTurnAge: Int?,disablePruning: Boolean?,compactionThresholdFraction: Double?.hasAnyOverride(): Booleanreturnsfalsewhen all fields arenullโ callers receivenullrather than a semantically-empty instance. -
TurnProgress: pureisTurnProductive(assistantMessage, toolResults)function โ classifies each turn for the no-progress cap; returnstruewhen โฅ1 tool result succeeded or the assistant produced non-blank text -
agentloop/state/: State machine and state data
-
AgentState: State data class (lastTurnInputTokensdrives compaction) andAgentPhaseenum -
AgentLoopStateMachine: Interface owningMutableStateFlow<AgentState>and all phase transitions -
DefaultAgentLoopStateMachine: Production FSM implementation
-
-
agentloop/guard/: Runtime safety fuses
-
EmptyArgumentGuard: Pre-execution fast-fail guard โ intercepts tool calls whose arguments are genuinely empty ({}), returns a corrective[ARGUMENTS MISSING]instruction to the model before the repeat detector is touched -
EmptyArgumentCircuitBreaker: Session-scoped consecutive-empty-arg strike counter; trips after 3 strikes and stops the run -
RepeatCallDetector: Session-scoped loop guard for non-cacheable tools (bash, write_file, โฆ).normalizeArgs()dispatches onTool.source: forToolSource.MCPtools it canonicalizes anypathargument to an absolute path before computing the cache key, ensuring that./fooand/abs/foomap to the same key; forBUILTINtools the existing bash/read_file normalization logic applies unchanged.
-
-
agentloop/cache/: Result caching
-
PureToolResultCache: Session-scoped cache for deterministic tools (read_file, grep, ls). Supports path-based ejection viainvalidateByPath(path)(evicts the exact path and all ancestor-directory entries) and turn-based TTL viaadvanceTurn()/maxTurnAge(default 5, envQ_CACHE_MAX_TURN_AGE).Content.Imageresults are never stored.
-
-
agentloop/tokenestimation/: Token counting
-
OutgoingContextEstimator: Conservative heuristic estimator (1 token โ 4 chars) for outgoing prompt size
-
-
agentloop/compaction/: Context compaction policy
-
CompactionPolicy: Decides whether proactive compaction is needed (max(local, provider) > window ร threshold)
-
-
agentloop/compaction/pruners/: Message-history pruning pipeline (6-stage)
-
OrphanedToolResultPruner: RemovesToolResultMessage`s whose matching `ToolCallwas pruned in a prior turn -
EmptyArgumentCallPruner: Removes empty-arg call/result pairs from LLM context -
ToolErrorPatternPruner: Collapses repeated identical tool errors into one representative + summary -
ToolResultPruner: Replaces oldToolResultMessagebodies with stubs (token opt, O(1) growth) -
AssistantMessagePruner: Strips reasoning text from oldAssistantMessageentries -
ThinkingPruner: RemovesAssistantContent.Thinkingblocks before each LLM call
-
-
messages/: Message types and transformations
-
Message: Core message abstractions (User, Assistant, Tool, System) -
MessageTransformer: Session message transformation utilities -
session/: Session management and history
-
SessionEntry: Sealed class hierarchy for all session entry types -
ThinkingLevelChangeEntry:SessionEntrysubtype (@SerialName("thinking_level_change")) recording a reasoning-effort change. CarriesthinkingLevel: Stringโ the caller passesEffortLevel.apiValue(lowercase, Pi-compatible) rather than the enum name. See ADR-20261002 (prompts/plans/adr/ADR-20261002-llm-reasoning-modes.md). -
SessionContext: Reconstructed message/model/thinking context for resume.thinkingLevel: Stringis replayed from the most recentThinkingLevelChangeEntryon the current branch, defaulting to"off"when the log contains none. -
SessionLogger: Interface for session-scoped logging. -
FileSessionLogger: Implementation that writes to~/.bk/agent/logs/--<cwd>--/. -
SessionResolver: Contract for resolving sessions by recency or id/name fragment -
SessionInfo: Session metadata used by CLI/TUI pickers and listing -
ModelInfo: Model metadata -
SessionManager: Manages session.jsonlfiles and the associatedSessionLogger. Initializes aFileSessionLoggerfor each session. Exposesclose()to flush and release log file handles. -
SessionOrchestrator: Domain interface for session lifecycle operations. DeclarespersistTurn(messages: List<Message>)andresumeSession(path: String): RestoredSession. The concrete implementation lives in:cli(us.nineworlds.book.cli.session.SessionOrchestrator);:domainowns only the contract. -
RestoredSession: Data class wrappingfullHistory: List<Message>โ the reconstituted message list returned byresumeSession. -
tracking/: Metrics and monitoring
-
TokenTracker: Interface for tracking token usage -
TokenTrackerImpl: Default implementation -
process/: Process execution abstraction
-
ProcessRunner: Interface for running external processes -
models/: Model id resolution
-
ModelKeyMatcher: Maps a caller-supplied model id onto a key in the shipped catalogue. Pure string logic over an injected key list โ no I/O. Handles gateway prefixes (bifrost/openrouter/…), colon tags (:free, and Bedrock versions such asamazon.nova-pro-v1:0), dotted vendor ids (anthropic.claude-sonnet-4-6), provider aliases (z-ai=zai=zai-org), and snapshots (glm-5.3-flash-001โglm-5.3-flash). ReturnsResolved,Ambiguous, orUnresolved. See Model Resolution. -
ModelKeyMatcher.Match: Sealed result type.Ambiguousis reported rather than guessed when several catalogue entries match equally and no provider preference decides. -
tools/: Tool registry and execution
-
ToolConfig: Data class (maxLines: Int = 2000,maxBytes: Int = 100000,cwd: String = "") holding tool output truncation limits and working directory context. Bound in:jvm:cli’s `ToolsModulefrom environment (BASH_MAX_LINES,BASH_MAX_BYTES,user.dir) and injected into tools (BashTool) and guards (RepeatCallDetector). -
Tool: Tool interface and implementations. EachToolcarries asource: ToolSourceproperty (defaultBUILTIN) identifying its origin. Theexecutesignature issuspend fun execute(arguments: JsonObject, callContext: ToolCallContext, onUpdate: (ToolResult) → Unit): ToolResultโcallContextis the single carrier for all I/O dependencies (fileSystem,processRunner). Tool implementations must read infra deps fromcallContextand must not declare them as constructor parameters. -
ToolSource: Enum with exactly three variants โBUILTIN(framework-shipped tools),EXTENSION(.bk.ktsscript tools),MCP(Model Context Protocol server tools). No other variants exist. -
ToolRegistry: Tool discovery and management.deregister(name)removes a tool by name; it throwsIllegalStateExceptionif the tool’ssourceisBUILTINorEXTENSIONโ onlyMCPtools may be deregistered at runtime. -
DefaultToolRegistry:CacheMap-backed implementation; safe for concurrent coroutine access. -
ToolDSL: Builder DSL for tool definitions -
extensions/: Extension system
-
Extension: Extension contracts -
ExtensionUI: UI integration points -
commands/: Command execution
-
Command: Command abstraction -
CommandResult: Result types -
SlashCommand: Domain interface for slash-command metadata (name: String,description: String?,rendering: CommandRendering,inputHint: String?). -
SlashCommandHandler: Polymorphic interface for executable slash command handlers (name: String,description: String?, suspendexecute(args: String): CommandResult). -
CommandOutput: Sink interface for slash-command output (displayMessage,displayError,handleFork,handleResumeSession,handleResumeFromTurn). Implemented per-transport โ TUI (:cli) and ACP (AcpCommandOutputin:features:acp). -
CommandCallbacks: Callback interface for command lifecycle hooks (displayMessage,displayError,handleResumeSessionโ allsuspend). -
SlashCommandRegistry: Registry forSlashCommandmetadata andSlashCommandHandlerexecutable instances (register(command),findByName(name),allCommands(),forMode(forAcp),register(handler),findHandler(name),allHandlers()). ACP listing excludes commands withrendering == TUI_ONLY. -
events/: Event system
-
BookEvent: Broadcast events -
InterceptableEvent: Request-response events -
skills/: Skill abstraction
-
Skill: Reusable agent skills -
filesystem/: File system abstraction
-
FileSystem: Sandboxed file operations -
systemprompt/: System prompt loading
-
SystemPromptLoader: Loads and merges system prompts from SYSTEM.md, AGENTS.md, and CLI flags (see agents.md spec)
Constraint: This module must not depend on any platform-specific or Infrastructure libraries. It is pure Kotlin.
Ring Boundary Rule: Per Clean Architecture, :domain must have zero implementation or api dependencies on :infrastructure, :cli, or any :features:* module. Dependencies always point inward โ outer rings depend on :domain, never the reverse. Any proposed change that would add such a dependency must be re-expressed as an interface in :domain with the concrete implementation in the appropriate outer ring.
Logging Architecture
Book uses Klogging as its primary structured logging engine. This unifies operational, diagnostic, and transport logs into a single high-performance stream.
Key Features
-
Structured Logging: Logs carry rich metadata (e.g., model IDs, session IDs, turn counts) instead of simple string interpolation. This enables precise filtering and analysis.
-
Unified Stream: Diagnostic logs from
:infrastructureand operational logs from:cliare routed through the same engine. -
Direct Klogging Integration: Ktor HTTP client logging delegates directly to Klogging (
noCoLogger("KtorClient")) without SLF4J adapters or bridges. -
Hierarchical Log Paths: Logs are automatically organized by workspace:
~/.bk/agent/logs/--<cwd>--/q-<timestamp>.log. This isolates logs for different projects even when using the same global installation.
Implementation Details
-
io.klogging.NoCoLogger: The standard logging interface used across all modules. -
us.nineworlds.book.infrastructure.session.PathUtils: Responsible for resolving the workspace-aware log file paths. -
CliLogger: A thin wrapper around Klogging for operational events (startup, shutdown, important status changes). -
KoogTransportLogger: Emits detailed, structured records of LLM outbound requests and inbound frames. '''
Design Philosophies
1. Spec-First Development (SDD)
We use a Phased GSD (Goal, Steps, Deliverables) protocol for all complex changes. This eliminates "Vibe Coding" by requiring a clear plan before implementation begins.
2. Contract-Driven Extensions
New capabilities are defined as tools. A tool is a simple contract: "Given these JSON arguments, produce this JSON result." This lets Book use tools written in Kotlin, scripts, or eventually external processes.
For more details on how extensions are loaded, see:
Bundled Extensions (:extensions module)
The :extensions module ships ready-to-use .bk.kts scripts in extensions/src/scripts/:
| Script | Tool / Command | Condition |
|---|---|---|
|
|
Tool registered only when |
|
opt-in interactive tool approval gate |
Always registered |
ripgrep.bk.kts exposes most of what RipGrep can do โ type filters, multiline search, PCRE2, JSON output, replacement, and more. It uses processRunner.run() (the framework-provided ProcessBuilderRunner) for non-blocking execution, keeping the agent UI fully responsive during searches.
3. Deterministic Context Management (Agent-Side, LLM as Last Resort)
Book’s primary context-management mechanism is agent-side and deterministic: a composable pruning pipeline rewrites message history before every LLM call, with no LLM involvement. LLM-summarisation compaction exists, but only as a rarely-needed last resort when the pruning pipeline alone cannot keep the context under the model’s window threshold.
This inverts the ratio used by most coding agents, whose primary mechanism is LLM summarisation (auto-compact / history summarisation) with light heuristics alongside. In Book the tiers are:
-
Tier 1 โ Deterministic pruning (primary, every turn, zero tokens): the six-stage pruner pipeline replaces old tool-result bodies with position-stable stubs (keeping tool identity + arguments + a short excerpt), strips thinking blocks globally, collapses repeated identical errors into a single suppression marker, and removes empty-argument call pairs. It is a pure function of the history: same input, same output โ unit-testable, reproducible, debuggable, and free.
-
Tier 2 โ LLM-summarisation compaction (fallback, only when the window fills): triggered by
CompactionPolicywhen the estimated/provider-reported context exceeds the threshold fraction of the model window.
Properties this buys:
-
O(recent-window) tokens, not O(session). Old tool results cost ~80-token stubs regardless of session length; per-turn context grows only by the recent verbatim window.
-
KV-/prompt-cache friendly by construction. Stubs are deterministic and replace messages in place โ message count and ordering stay stable, so the stubbed prefix is byte-stable across turns and keeps hitting runtime prefix caches. The only per-turn invalidation is the recent window itself.
-
No recursive cost. Summarisation spends LLM tokens to save LLM tokens; Tier 1 costs zero. Tier 2 fires rarely precisely because Tier 1 exists โ in most sessions, never.
-
No hidden LLM calls, no nondeterministic summaries. The information policy (what is kept, what is elided, per-pruner defaults) is explicit, versioned code โ not an emergent property of a summariser model.
-
Local-model fit. Context management is effectively free every turn instead of an occasional multi-second summarisation stall โ important for on-device/locally-hosted models where prefill time and context window are the scarce resources.
The information lost by stubbing is controlled and uniform (every stub retains the call’s identity, arguments, and a short excerpt so the model can see what was already read without re-sending it), in contrast to summarisation, which is lossy in uncontrolled, model-chosen ways.
4. Agentic Autonomy with Human Overlays
The AgentLoop is designed for autonomy but respects "Human Gate" hooks. For example, the AgentLoopConfig allows blocking tool execution until a human approves it.
Key Dependencies
| Dependency | Purpose |
|---|---|
Koog |
The agent framework. Provides the Prompt DSL and manages streaming LLM responses. |
Metro |
Compile-time Dependency Injection. Fast and type-safe wiring of components. |
Mordant |
Terminal UI rendering (v3.1.0, including |
Clikt |
CLI command parsing and sub-command management. |
Okio |
I/O library used for sandboxed file operations. |