Audience: developers and AI agents modifying Book’s LLM integration (core/providers/koog), or adding a new LLM provider.

How Book talks to LLMs: the Koog framework provides streaming/executors; this layer adapts them to Book’s domain model so the rest of the codebase is provider-agnostic.


Module Position

:providers:koog is an outer-ring adapter (module dependencies). Domain defines what an LLM is; this module defines how to get one:

Domain type (imported, never reimplemented) Koog-layer implementation

Agent

KoogAgent

AgentEvent stream

StreamOrchestrator

EffortLevel, ReasoningAgent

effort applied in prompt/executor setup

Message/Content

translated to Koog prompt types at the boundary

Domain files may never import ai.koog.*. All Koog types are confined to this module and :jvm:cli glue.

Agent Interface (domain contract)

interface Agent {
    var model: String?

    /** Streams the next turn from the LLM. */
    fun nextTurn(
        messages: List<Message>,
        tools: List<Tool>,
        sessionLogger: SessionLogger = NoOpSessionLogger
    ): Flow<AgentEvent>

    suspend fun listModels(): List<ModelMetadata>
    fun lookupMetadata(modelId: String): ModelMetadata? = null
}

KoogAgent implements this; AgentLoop depends on the interface only — that is the seam that makes the whole agent loop testable (fake Agent in tests, see Agent Loop).

KoogAgent

Orchestrator wiring executor + model + tools per turn. Constructor receives LLMClientAPI (Koog abstraction, provided by Metro as BifrostOpenAILLMClient), ProviderConfig (holding injected provider API keys and base URL), and emits AgentEvent`s via `StreamOrchestrator. Provider configuration fields are read directly from the injected ProviderConfig instance without setting global JVM system properties (System.setProperty).

StreamOrchestrator — Stream Lifecycle Contract

Owns the entire stream lifecycle of a single agent turn. The contract, preserved from the original KoogAgent.nextTurn:

  • Pre-stream failure (stream factory throws before any frame): exactly one AgentEvent.Error("Failed to initiate stream: …"), flow completes — no fallback Completed.

  • Mid-stream non-cancellation failure: one AgentEvent.Error("Streaming error: …"), then finally emits a fallback Completed if content accumulated (else an additional Error + empty Completed).

  • Mid-stream cancellation:

  • Caller-job cancellation (Ctrl+C): rethrows CancellationException to unwind.

  • Watchdog-only cancellation (inactivity timeout): logs a warning, does not rethrow; finally emits the fallback Completed — the watchdog soft-stop contract.

Also: collects frames via StreamFrameHandler, arms the InactivityWatchdog, discriminates cancellation vs. real errors, handles fallback completion, and dispatches the after_provider_response extension event.

StreamFrameHandler

Maps Koog `StreamFrame`s to domain `AgentEvent`s: text/thinking deltas, tool-call argument accumulation, paired-frame de-duplication for double-emitting gateways. Details: Agent Loop — Streaming Pipeline.

BifrostOpenAILLMClient

Book’s OpenAI-compatible client wrapper (LLMClientAPI). Exists to route requests through Bifrost (proxy/model-registry) with Book-specific defaults, so any OpenAI-compatible backend (OpenAI, vLLM, Ollama-bridges, Bifrost itself) can serve Book without a bespoke client.

PromptExecutorFactory

Open class; create(provider, config): PromptExecutorAPI. Two built-ins:

  • anthropic → AnthropicLLMClient + retry wrapper

  • anything else → OpenAILLMClient against a normalised base URL:

val configBaseUrl = config.openAiBaseUrl.removeSuffix("/")
val baseUrl = if (configBaseUrl.endsWith("/v1")) {
    configBaseUrl.removeSuffix("/v1")
} else {
    configBaseUrl
}

Retry is applied via Koog’s toRetryingClient(RetryConfig) — injected, not hardcoded. open on the class is intentional: tests override create with fakes.

Adding a Provider

  1. Add a branch in PromptExecutorFactory.create wrapping the Koog client in a retrying executor

  2. If the backend is OpenAI-compatible, prefer reusing BifrostOpenAILLMClient with a new base URL — no new client class needed

  3. Extend ProviderConfig/core/infrastructure config parsing (API key env var, base URL). Provider credentials are resolved at startup in the CLI layer and injected via ProviderConfig without global System.setProperty mutations.

  4. Add model registry entries so listModels()/lookupMetadata() return pricing metadata (ModelPricing powers the cost tracker — see Configuration)

  5. No changes outside this module — that’s the point of the boundary

InactivityWatchdog

Cancels a stream that produces no frames for the configured window (soft-stop semantics above). Watchdog-only cancellation is distinguishable from user cancellation inside StreamOrchestrator — do not collapse the two paths.

  • Agent Loop — the consumer of this module; guards, compaction, streaming details

  • DI & Wiring — how KoogAgent, LLMClientAPI, and executors are provided via Metro

  • Domain Package Reference — ReasoningAgent, EffortLevel, Agent definitions