Embedding Book as an ACP Agent — Architecture & Internals
Audience: developers and AI agents working on Book’s ACP server implementation, or embedding the agent loop in host applications. This page covers module structure, internal APIs, and design contracts.
Just want to connect Book to your IDE? See the user-facing guide: ACP Server Configuration (flags, transports,
_meta, troubleshooting) and Xcode Integration.
Diagrams
-
06-activity-startup-swimlanes.puml— Startup & Mode Selection -
10-activity-transport-selection-swimlanes.puml— Transport Selection -
04-seq-acp-session-lifecycle.puml— Session Lifecycle -
07-activity-session-prompt-swimlanes.puml— Session Prompt Turn Lifecycle -
08-activity-acp-capability-delegation.puml— Capability-Driven Tool Delegation -
09-seq-multi-session-concurrency.puml— Multi-Session Concurrency -
11-seq-slash-command-acp-routing.puml— Slash Command Routing
Full catalogue: docs/diagrams/README.md (repository file; diagram pages are not published to the site).
Module Structure
The ACP server lives in the :features:acp Gradle module. Its public surface is deliberately
narrow — the rest of the codebase never touches ACP internals:
| Type | Role |
|---|---|
|
Top-level interface: lifecycle ( |
|
Implements the stdio/IDE transport loop and session registry |
|
Tracks live `BookAgentSession`s; enforces per-session isolation |
|
Parsed |
|
Sealed interface with exactly two variants: |
|
Metro-scoped dependency bundle handed to each new session |
sealed interface AcpTransportConfig {
data object Stdio : AcpTransportConfig
data class Sse(val port: Int) : AcpTransportConfig
}
AcpServer interface
interface AcpServer {
fun start()
fun stop()
}
Per-Session Isolation
Every incoming session/new request produces a distinct, fully isolated
BookAgentSession via AgentLoopFactory.create(ctx, env):
fun interface AgentLoopFactory {
fun create(ctx: SessionContext, env: AgentEnvironment): AgentLoop
}
-
No shared mutable state between sessions (message history, working directory, tool overrides are all per-session)
-
AcpMetaParserconverts ACPmetapayloads intoAgentSessionConfig— the domain layer (core/domain/…/agentloop/AgentLoopFactory.kt) documents this contract: _"Used byq.features.acp.session.AcpMetaParser.toAgentSessionConfigas a guard" — so domain never imports ACP types; ACP adapts into domain. -
Sessions are torn down deterministically on
session/end; the registry refuses double-registration of a session id.
Per-Session Reasoning Effort
ACP _meta may carry an effort override, applied for the lifetime of that session
(ReasoningAgent.effort, see Agent Loop — Domain Model).
Thinking Stream Flush Contract
While a model is streaming thinking content, ACP sessions flush partial thinking
deltas to the IDE client on a cadence rather than buffering until message end — the
client stays responsive during long reasoning phases. The flush cadence is transport-
independent and specified in features/acp/…/events.
Capability-Driven Environment
ACP clients advertise capabilities (filesystem access, terminal/pty, etc.). Book maps them onto the domain port interfaces so the agent’s tool surface reflects what the host IDE can actually do:
| Domain port | ACP implementation | Behaviour |
|---|---|---|
|
|
Delegates every operation to the IDE client via |
|
|
Spawns processes through the IDE’s terminal capability |
SimpleAgentLoopEnvironment composes these into the AgentEnvironment handed to the
AgentLoop. When the IDE lacks a capability, the corresponding tool is absent from
the registry rather than failing at execution time.
AcpFileSystem
Implements the full FileSystem port (list, read, write, append, exists,
delete, isDirectory, mkdirs, size, move) — every call is an RPC round-trip
to the IDE, so hot loops (e.g. large greps) route through Book’s built-in tools where
possible, not the IDE filesystem.
AcpProcessRunner
run(…) returns a Flow<ProcessEvent> (Stdout/Stderr/Completed/Error)
delegated to the host terminal capability.
Timeout
Per-command timeout defaults are enforced by the ACP layer; a watchdog cancels the flow
and reports Completed(exitCode = -1) to the agent rather than hanging the turn.
Heartbeat interval
Long-running processes emit periodic heartbeat frames to keep IDE transports from
timing out; the interval is configurable via AcpStartConfig.
Transport Configuration
AcpTransportConfig is a sealed interface with exactly two variants (Stdio,
Sse(port: Int)). See the user guide for the CLI flags that produce each variant:
Transport flags.
Per-Session Configuration via _meta
The _meta → AgentSessionConfig mapping (working directory, model, effort, tool
denials) is documented with the user flags table:
Per-Session _meta.
Native Session Configuration Options & session/set_config_option
AcpAgentSession overrides configOptions and setConfigOption to expose native model selection and reasoning effort pickers to ACP clients:
-
configOptionsadvertisement:buildConfigOptions()constructs a list ofSessionConfigOption.Selectitems: -
model: populated from the provider’s model list (agentLoop.listModels()), withModelMetadataRegistryas a fallback seed before the first provider fetch completes. No credential- or context-window-based filtering is applied — the provider only returns models it can serve. -
thought_level: populated fromEffortLevel.entries. -
currentValueis resolved from live state (agentLoop.state.value.modelandsessionEffort); when no model is set yet, it falls back to the first available model so the client picker never shows an empty selection. -
postInitialize()— Thin Orchestrator (Spec 6): Four delegated steps, in order: (1)resolveClientOps()with warn-and-early-return when absent; (2)historyReplay.replay(…)— conversation history classification + emission owned byAcpHistoryReplay/DefaultAcpHistoryReplayinsession.runtime(user text →UserMessageChunk, assistant text →AgentMessageChunk, thinking →AgentThoughtChunk; system/tool-result/tool-call messages deliberately omitted per R-028; a single message failing withIllegalStateException/IllegalArgumentExceptionis warn-logged with the throwable attached and the replay continues — other exceptions propagate); (3)emitAvailableCommandsUpdate()on the config options controller; (4)bootstrapInitialModel()on the model controller plus the async refresh below. -
Background Model Refresh (
postInitialize()): LaunchesrefreshModelOptions()asynchronously on session creation. Fetches live models viaagentLoop.listModels(), updates cached model metadata, and pushes aSessionUpdate.ConfigOptionUpdateon success. On failure or empty result, degrades silently (retains local seed, logs warning). -
Guarded Emission Helper (
emitConfigOptionUpdate): Centralizes all option-update emissions (trySendwith error logging); ensures post-session/deleteemissions become safe, logged no-ops. -
Slash-Command Synchronization:
/modeland/efforthandlers trigger option updates via the shared helper (notifyConfigOptionsChanged()), keeping IDE pickers synchronized. -
session/set_config_optionhandling: -
model: validates that no prompt turn is active (activeChannelSnapshot == null) and the model is in the provider’s advertised model list. On success, callsagentLoop.setModel(modelId), notifiesSessionUpdate.ConfigOptionUpdate, and emits an immediateSessionUpdate.UsageUpdatefrom live state. Busy requests during prompt turns throwIllegalStateException. -
thought_level: case-insensitively maps input string toEffortLevel, setssessionEffort, updatesagentLoop.setThinkingLevel(…), re-emitsSessionUpdate.ConfigOptionUpdate, and returns refreshed options. -
Unknown
configId`s throw `IllegalArgumentException. -
No
session/set_config_optionpath writes to persistent storage (configManager/sessionOrchestrator). -
Usage Update Size Suppression (
AcpEventMapper):SessionUpdate.UsageUpdateis emitted onAgentEndor model switch only whenemitUsageUpdatesis true and the model’s context window size is known (modelContextWindow > 0). Models with unknown or zero context windows suppress usage updates to prevent misinforming the client context meter. -
Legacy delegates:
@UnstableApioverridesavailableModels,defaultModel, andsetModelare thin delegates (≤ 3 lines) delegating directly to the shared model-switch and option-building logic.
Structured Logging
ACP mode emits structured JSONL log lines (request ids, session ids, transport events)
so IDE integrations can correlate agent activity with their own logs. Log levels follow
the standard --log-level flag.
Slash Command Routing in ACP Mode
Slash commands arriving over ACP are routed through the same ExtensionRegistry
command lookup as the TUI (findCommand(name) → execute). The routing diagram
(11-seq-slash-command-acp-routing.puml) covers ordering between extension commands,
built-in commands, and plain prompts. The extension side is documented in
Extension API: Events; user-facing command list in
Slash Commands in ACP Mode.
Deleted: Xcode-specific Tools
A previous iteration shipped Xcode-only tools; these were removed in favour of the capability-driven environment (the IDE’s own tools are offered through ACP instead). Kept as a note here because older session JSONL logs may reference them.
Ring Boundary
:features:acp sits in the outer ring of the Clean Architecture diagram
(module dependencies). Hard rules:
-
May import from:
core/domain,core/infrastructure,:features:mcp(via facade only) -
Must never be imported by:
core/*,:jvm:cli(cli talks toAcpServerinterface only) -
All ACP types cross into domain only as mapped domain values (
AgentSessionConfig,AgentEnvironment) — see DI & Wiring for the Metro graph.