Audience: everyone โ€” this is the entry point to Book’s architecture: the :domain core 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 Agent for LLMs with built-in thinking/reasoning modes (see ADR-20261002 (prompts/plans/adr/ADR-20261002-llm-reasoning-modes.md)). Declares var effort: EffortLevel (default agent effort) and a turn-local nextTurn(messages, tools, sessionLogger, effort) overload that transports turn-local effort without mutating shared instance state. Default effort is EffortLevel.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) implement Agent only, so no implementor is forced to carry unused reasoning state (Interface Segregation Principle). Callers should verify both agent is ReasoningAgent and modelMetadata.supportsReasoning == true before exposing reasoning controls.

  • EffortLevel: Enum of seven reasoning-effort levels โ€” OFF, MINIMAL, LOW, MEDIUM, HIGH, XHIGH, MAX. Each constant carries apiValue, the lowercase verbatim string persisted in JSONL session logs (e.g. EffortLevel.XHIGH.apiValue == "xhigh"). OFF, LOW, MEDIUM, HIGH, and XHIGH are compatible with standard Pi agent log parsers; MINIMAL and MAX are Book-specific extensions serialized verbatim. EffortLevel.DEFAULT is HIGH.

  • AppScope: Dependency injection scope marker

Feature Packages

  • agentloop/: Orchestrates the "Thinking โ†’ Executing โ†’ Learning" cycle

Diagram
Diagram
  • AgentLoop: Main orchestration driver. Not a singleton โ€” one instance is created per active session via AgentLoopFactory. Constructs TurnProcessor and TurnSession, drives the turn loop, and acts on TurnOutcome variants. Exposes cancelAndJoin() to cancel the in-flight run() coroutine and await its completion (used by AcpServerImpl.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). Exposes executeTurn().

  • TurnSession: Mutable session state holder. Holds currentMessages, newMessages, unproductiveTurns counter, and pendingSteeringMessages across turns in a single run() execution.

  • TurnOutcome: Sealed outcome type (Continue, StopComplete, StopError, MaxTurnsReached) returned by TurnProcessor.executeTurn().

  • AgentLoopFactory: Functional interface fun interface AgentLoopFactory { fun create(ctx: QSessionContext?, env: AgentLoopEnvironment): QAgentSession }. Called once per session/new or session/load in ACP mode to produce a fully isolated QAgentSession. The production binding is an AppGraph lambda that constructs a fresh AgentLoop each time.

  • QAgentSession: Data class returned by AgentLoopFactory.create(). Holds agentLoop: AgentLoop and sessionOrchestrator: SessionOrchestrator. Passed to AcpAgentSession at construction โ€” never shared across sessions.

  • AgentLoopTypes: Configuration and context types (AgentLoopConfig owning loop turn limits maxTurns and maxUnproductiveTurns, pruning/cache settings isPruningDisabled and cacheMaxTurnAge, and optional turn-local effort, AgentContext, TurnContext, hook contexts/results)

  • ToolCallExecutor: Tool-call execution pipeline (parallel/sequential dispatch, cache, loop guard, config hooks). Holds an AgentLoopEnvironment (injected; defaults to a no-op stub for test compatibility) and constructs a fresh ToolCallContext(fileSystem, processRunner) from it at a single call site inside executeWithCacheAndGuard before passing it to tool.execute().

  • ToolCallContext: Single I/O carrier passed to every Tool.execute() invocation. Carries fileSystem: FileSystem, processRunner: ProcessRunner, and optional outputContext: OutputContext? (default null). Pure domain type โ€” zero :cli/:infrastructure imports. Tools must never resolve FileSystem or ProcessRunner from their own constructors; they read exclusively from callContext.

  • AgentLoopEnvironment: Domain interface that bundles fileSystem: FileSystem and processRunner: ProcessRunner. Held by ToolCallExecutor; its fields are used to construct a fresh ToolCallContext for every tool invocation. Production binding is provided by :cli’s `AppGraph.

  • RunEnvironment: Sealed interface with exactly three variants โ€” Tui (interactive terminal), Headless (non-interactive -p flag), Server (ACP/MCP serve mode). Computed via RunEnvironment.derive(modes.toSet(), headlessPrompt). isHeadless: Boolean is a permanent computed bridge property (val isHeadless: Boolean get() = environment != RunEnvironment.Tui) โ€” it must never be removed or stored as a Boolean field; 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 a Set<RunMode> to RunEnvironment.derive(). --mode on BookArgCommand accepts this enum via Clikt .enum<RunMode>(ignoreCase=true).multiple() โ€” the flag is repeatable and case-insensitive (e.g. --mode acp --mode mcp). headless is NOT a RunMode; headless execution is derived internally from the presence of -p/--prompt.

  • AgentSessionConfig: Per-session token knobs forwarded into AgentLoop.run(). All five fields default to null ("use system default"). Parsed from ACP _meta via AcpMetaParser.toAgentSessionConfig(). Fields: maxTurns: Int?, maxUnproductiveTurns: Int?, cacheMaxTurnAge: Int?, disablePruning: Boolean?, compactionThresholdFraction: Double?. hasAnyOverride(): Boolean returns false when all fields are null โ€” callers receive null rather than a semantically-empty instance.

  • TurnProgress: pure isTurnProductive(assistantMessage, toolResults) function โ€” classifies each turn for the no-progress cap; returns true when โ‰ฅ1 tool result succeeded or the assistant produced non-blank text

  • agentloop/state/: State machine and state data

    • AgentState: State data class (lastTurnInputTokens drives compaction) and AgentPhase enum

    • AgentLoopStateMachine: Interface owning MutableStateFlow<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 on Tool.source: for ToolSource.MCP tools it canonicalizes any path argument to an absolute path before computing the cache key, ensuring that ./foo and /abs/foo map to the same key; for BUILTIN tools 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 via invalidateByPath(path) (evicts the exact path and all ancestor-directory entries) and turn-based TTL via advanceTurn() / maxTurnAge (default 5, env Q_CACHE_MAX_TURN_AGE). Content.Image results 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: Removes ToolResultMessage`s whose matching `ToolCall was 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 old ToolResultMessage bodies with stubs (token opt, O(1) growth)

    • AssistantMessagePruner: Strips reasoning text from old AssistantMessage entries

    • ThinkingPruner: Removes AssistantContent.Thinking blocks 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: SessionEntry subtype (@SerialName("thinking_level_change")) recording a reasoning-effort change. Carries thinkingLevel: String โ€” the caller passes EffortLevel.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: String is replayed from the most recent ThinkingLevelChangeEntry on 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 .jsonl files and the associated SessionLogger. Initializes a FileSessionLogger for each session. Exposes close() to flush and release log file handles.

  • SessionOrchestrator: Domain interface for session lifecycle operations. Declares persistTurn(messages: List<Message>) and resumeSession(path: String): RestoredSession. The concrete implementation lives in :cli (us.nineworlds.book.cli.session.SessionOrchestrator); :domain owns only the contract.

  • RestoredSession: Data class wrapping fullHistory: List<Message> โ€” the reconstituted message list returned by resumeSession.

  • 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 as amazon.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). Returns Resolved, Ambiguous, or Unresolved. See Model Resolution.

  • ModelKeyMatcher.Match: Sealed result type. Ambiguous is 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 `ToolsModule from environment (BASH_MAX_LINES, BASH_MAX_BYTES, user.dir) and injected into tools (BashTool) and guards (RepeatCallDetector).

  • Tool: Tool interface and implementations. Each Tool carries a source: ToolSource property (default BUILTIN) identifying its origin. The execute signature is suspend fun execute(arguments: JsonObject, callContext: ToolCallContext, onUpdate: (ToolResult) → Unit): ToolResult โ€” callContext is the single carrier for all I/O dependencies (fileSystem, processRunner). Tool implementations must read infra deps from callContext and must not declare them as constructor parameters.

  • ToolSource: Enum with exactly three variants โ€” BUILTIN (framework-shipped tools), EXTENSION (.bk.kts script tools), MCP (Model Context Protocol server tools). No other variants exist.

  • ToolRegistry: Tool discovery and management. deregister(name) removes a tool by name; it throws IllegalStateException if the tool’s source is BUILTIN or EXTENSION โ€” only MCP tools 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?, suspend execute(args: String): CommandResult).

  • CommandOutput: Sink interface for slash-command output (displayMessage, displayError, handleFork, handleResumeSession, handleResumeFromTurn). Implemented per-transport โ€” TUI (:cli) and ACP (AcpCommandOutput in :features:acp).

  • CommandCallbacks: Callback interface for command lifecycle hooks (displayMessage, displayError, handleResumeSession โ€” all suspend).

  • SlashCommandRegistry: Registry for SlashCommand metadata and SlashCommandHandler executable instances (register(command), findByName(name), allCommands(), forMode(forAcp), register(handler), findHandler(name), allHandlers()). ACP listing excludes commands with rendering == 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 :infrastructure and operational logs from :cli are 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:

Diagram

Bundled Extensions (:extensions module)

The :extensions module ships ready-to-use .bk.kts scripts in extensions/src/scripts/:

Script Tool / Command Condition

ripgrep.bk.kts

ripgrep tool + /rg-status command

Tool registered only when rg binary is found in PATH; /rg-status always registered

tool_approval.bk.kts

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 CompactionPolicy when 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 mordant-coroutines). Handles colors, styled widgets, complex layouts, and coroutine-driven non-blocking animations. Frames are rendered to ANSI strings via Terminal.render() and emitted as a single rawPrint for flicker-free output. The prompt region uses character-wrap (not word-wrap) to keep the rendered layout in sync with the cursor arithmetic โ€” see TUI Architecture.

Clikt

CLI command parsing and sub-command management.

Okio

I/O library used for sandboxed file operations.