The AgentLoop (located in us.nineworlds.book.domain.agentloop) is the central orchestration component in Book. It is a zero-mutation orchestrator: AgentLoop delegates all state mutations to AgentLoopStateMachine, which owns the MutableStateFlow<AgentState> and enforces valid AgentPhase transitions.

Package Structure

The agent loop functionality is split into focused sub-packages under us.nineworlds.book.domain.agentloop:

us.nineworlds.book.domain.agentloop (core)

  • AgentLoop.kt: Main orchestration driver β€” constructs TurnProcessor and TurnSession, drives the turn loop, and acts on TurnOutcome variants; zero direct state mutation

  • TurnProcessor.kt: 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 a single public executeTurn() returning TurnOutcome

  • TurnSession.kt: Mutable session state holder β€” owns currentMessages, newMessages, unproductiveTurns counter, and pendingSteeringMessages across turns

  • TurnOutcome.kt: Sealed outcome type with 4 variants (Continue, StopComplete, StopError, MaxTurnsReached) returned by executeTurn()

  • ToolCallExecutor.kt: Tool-call execution pipeline β€” dispatches parallel/sequential, enforces cache, loop guard, config hooks, and extension intercepts

  • TurnProgress.kt: Pure function isTurnProductive(assistantMessage, toolResults) β€” returns true when β‰₯1 tool result succeeded (isError == false) or the assistant produced non-blank text; used by TurnProcessor to detect and bound consecutive unproductive turns

  • AgentLoopTypes.kt: Configuration and context types

  • AgentLoopConfig: Interface for customizing loop behavior, turn execution limits (maxTurns, maxUnproductiveTurns), and pruning/caching configuration (isPruningDisabled, cacheMaxTurnAge)

  • AgentContext, TurnContext: Contextual information

  • BeforeToolCallContext, AfterToolCallContext: Hook contexts passed to AgentLoopConfig.beforeToolCall() and afterToolCall() respectively β€” give host Kotlin code access to the full AgentContext (messages, system prompt, all tools) before/after each tool execution

us.nineworlds.book.domain.agentloop.state

  • AgentState.kt: State data class and AgentPhase enum (IDLE, THINKING, EXECUTING_TOOLS, COMPLETED, ERROR)

  • AgentLoopStateMachine.kt: Interface that owns MutableStateFlow<AgentState> and all phase transitions β€” the single authority for state mutation. Transition methods:

  • onStart() β€” transitions to THINKING

  • onTextDelta(text) / onThinkingDelta(text) β€” accumulates partial assistant content

  • onToolsStarted() β€” transitions to EXECUTING_TOOLS

  • onCompleted(message) β€” transitions to COMPLETED and records the final AssistantMessage

  • onError(reason) β€” transitions to ERROR

  • onReset() β€” resets state to a clean AgentState(model, modelMetadata), discarding all phase, partial-message, and token data. Called by AgentLoop.resetState() when the user runs /new or /clear. Preserves only the active model and its metadata so the next run does not need to re-fetch model information.

  • DefaultAgentLoopStateMachine.kt: Production implementation; enforces valid AgentPhase FSM transitions and silently discards illegal ones

us.nineworlds.book.domain.agentloop.guard

  • EmptyArgumentGuard.kt: Pre-execution fast-fail for tool calls with empty arguments ({}); returns a corrective ToolResult without executing the tool

  • EmptyArgumentCircuitBreaker.kt: Runtime safety fuse that tracks consecutive empty-argument strikes per session; trips after a configurable threshold (default 3) and returns a concise circuit-break error, stopping the run before the generic no-progress cap activates

  • RepeatCallDetector.kt: Session-scoped guard that breaks tool-call loops using a sliding window (windowSize = 20) of the most-recent calls; flags a key as looping once it exceeds maxCallsPerKey (default 4) appearances in the window, allowing old calls to age out naturally

us.nineworlds.book.domain.agentloop.cache

  • PureToolResultCache.kt: Session-scoped in-process cache for deterministic tools. Never caches or serves results for empty-argument or empty-content calls. Supports path-based ejection via invalidateByPath(path) (evicts the exact path and any ancestor-directory entries) and turn-based TTL via advanceTurn() / maxTurnAge (default 5 turns, env BOOK_CACHE_MAX_TURN_AGE). Content.Image results are excluded from put() to avoid accumulating stale blobs in memory.

us.nineworlds.book.domain.agentloop.tokenestimation

  • OutgoingContextEstimator.kt: Deterministic, provider-agnostic conservative estimator for outgoing prompt tokens; uses a ceiling-division heuristic (1 token β‰ˆ 4 characters) across all message types and tool schemas

us.nineworlds.book.domain.agentloop.compaction

  • CompactionPolicy.kt: Decides whether proactive context compaction is needed by comparing max(localEstimate, providerInputTokens) against a configurable threshold fraction (default 70 %) of the model’s context window; falls back to a configurable window size when model metadata is unavailable

us.nineworlds.book.domain.agentloop.compaction.pruners

  • OrphanedToolResultPruner.kt: Removes ToolResultMessage`s whose `toolCallId has no matching AssistantContent.ToolCall anywhere in the message list β€” prevents Koog from synthesising a non-JSON placeholder call that breaks LiteLLM’s Bedrock converter

  • EmptyArgumentCallPruner.kt: Removes empty-argument ({}) call/result pairs from subsequent LLM context β€” prevents [ARGUMENTS MISSING] history accumulation before the error-pattern pruner or tool-result stubber run

  • ToolErrorPatternPruner.kt: Collapses repeated equivalent tool errors inside the recent window into one representative error plus a compact suppression summary, breaking dense negative few-shot error spirals without losing the first diagnostic instance

  • ToolResultPruner.kt: Replaces old ToolResultMessage bodies with short stubs (see below); stubs for [ARGUMENTS MISSING] errors are replaced with a neutral one-liner β€” no excerpt echoed back β€” breaking the amplifier loop

  • AssistantMessagePruner.kt: Strips reasoning text from old AssistantMessage entries

  • ThinkingPruner.kt: Removes all AssistantContent.Thinking blocks before each LLM call

The Cycle

Each "Run" of the agent loop consists of multiple "Turns". A turn is a single exchange where the agent processes the current conversation and decides what to do next.

Phase 1: Context Preparation

Before calling the LLM the loop applies a behaviour-quality and token-quality pruning pipeline to the message history, followed by a proactive compaction check:

Pruning pipeline (applied in order):

  1. OrphanedToolResultPruner β€” removes ToolResultMessage`s whose `toolCallId has no matching AssistantContent.ToolCall anywhere in the message list. This prevents Koog v0.8.0 from synthesising a non-JSON placeholder call ("Synthesized call for result") that breaks LiteLLM’s Bedrock converter. Orphans arise when a prior turn’s pruning (e.g. EmptyArgumentCallPruner or AssistantMessagePruner) removed the AssistantMessage containing the matching call.

  2. EmptyArgumentCallPruner β€” scans AssistantMessage entries for tool calls whose argument object is {} and removes both the empty-arg call and its paired ToolResultMessage from the context sent to the provider. This prevents [ARGUMENTS MISSING] responses from accumulating in the model’s view of history.

  3. ToolErrorPatternPruner β€” scans all ToolResultMessage(isError = true) entries in the (now cleaned) window and collapses repeated identical error signatures (same tool name + same normalised error text) into one representative error plus a single compact suppression summary such as [bash β€” 2 repeated equivalent error results suppressed]. Different error messages and successful results are always left intact. The suppression record is inserted in-place at the position of the first duplicate, preserving the tool_use β†’ tool_result adjacency invariant required by the provider API.

  4. ToolResultPruner β€” replaces ToolResultMessage bodies outside the last 20 entries with compact stubs that include the original tool arguments and a 200-character excerpt. This reduces O(N) per-turn token growth to O(1) without the model losing track of which calls were made.

  5. AssistantMessagePruner — strips reasoning text from assistant messages outside the last 300, replacing each with a summary stub. Tool calls are always preserved so the call→result pair stays coherent for the model.

  6. ThinkingPruner β€” removes all AssistantContent.Thinking blocks. Thinking blocks are the model’s internal scratch-work (typically 1k–5k tokens each); their conclusions are already captured in the companion Text content, so re-sending them wastes tokens without benefit.

Pruning can be disabled globally via AgentLoopConfig.isPruningDisabled (populated from BOOK_DISABLE_PRUNING=true at CLI startup). When disabled, the raw accumulated history is sent to the provider unmodified and proactive compaction is also skipped.

Proactive compaction check (after pruning):

After the prune pipeline, AgentLoop estimates the outgoing payload size (pruned messages + tool schemas) using OutgoingContextEstimator and consults CompactionPolicy before every provider call. See Context Compaction below for details.

Phase 2: Thinking

After context preparation, the loop sends the history to the LLM via Agent.nextTurn(). The agent decides whether to:

  1. Provide a text response to the user.

  2. Call one or more tools.

  3. Ask a clarifying question.

Streaming TextDelta and ThinkingDelta events are forwarded by TurnProcessor.handleStreamEvent to stateMachine.onTextDelta() and stateMachine.onThinkingDelta(), which update AgentState.partialAssistantMessage and AgentState.partialThinking respectively β€” AgentLoop no longer mutates state directly. This drives real-time TUI feedback.

Phase 3: Executing Tools

If the agent decides to use tools, the loop transitions to the EXECUTING_TOOLS phase.

  • AgentLoop delegates the entire execution batch to ToolCallExecutor, which selects parallel or sequential dispatch based on AgentLoopConfig.toolExecution and per-tool executionMode.

  • Each tool execution can report progress updates back to the UI via ToolExecutionUpdate events.

Cache-first path (pure tools): For deterministic tools (read_file, grep, ls), the PureToolResultCache is checked first. On a cache hit the tool is never re-executed β€” the cached content is returned immediately, saving both latency and provider tokens.

Cache ejection β€” mutation tools: After a write_file or edit_file call completes without error, ToolCallExecutor calls PureToolResultCache.invalidateByPath(path) with the target file path. This eagerly evicts any stale cache entries whose stored path equals the written path or is an ancestor directory of it β€” so a grep entry covering /src is also evicted when /src/Foo.kt is written. Both the stored key path and the mutation path are normalised to canonical absolute form via File.canonicalPath before comparison, meaning relative and absolute forms of the same path always resolve to the same entry. If the mutation returns an error, no eviction occurs β€” the existing cached read is left intact.

Cache TTL β€” turn-based expiry: Each entry carries the turn counter at which it was written (writtenAtTurn). At the start of every agent turn, ToolCallExecutor.onTurnAdvanced() calls PureToolResultCache.advanceTurn(), which increments the internal turn counter then eagerly evicts every entry whose age (currentTurn βˆ’ writtenAtTurn) exceeds maxTurnAge (default 5, configured via AgentLoopConfig.cacheMaxTurnAge / BOOK_CACHE_MAX_TURN_AGE at CLI startup). The boundary is strictly greater-than: an entry at exactly maxTurnAge turns old is still live. Because eviction is eager, get() never needs a TTL check β€” any entry present in the store is guaranteed to be within its age window.

Image exclusion: Content.Image results are never stored in the cache. If a tool result contains any Content.Image part, the entire result is skipped on put() β€” even when the tool name is in pureToolNames. This prevents stale base64 blobs from accumulating in memory across a long session.

Loop guard (non-cacheable tools): For bash, write_file, and similar side-effecting tools, the RepeatCallDetector tracks each unique tool+args combination using a sliding window of the most-recent windowSize (default 20) calls. Once a key appears more than maxCallsPerKey (default 4) times within that window it returns a LOOP DETECTED error, explicitly telling the model it is repeating itself and needs a different approach. Calls that age out of the window are no longer counted — preventing false positives in long TDD sessions while still catching rapid-burst and oscillating (A→B→A→B) loops.

Results are collected and formatted into ToolResultMessage objects.

Phase 4: Feedback

The results of the tool executions are appended to the message history. The loop then automatically triggers Phase 1 again (context preparation + thinking), providing the agent with the "eyes" to see the results.


Context Compaction

Context compaction reduces accumulated message history when it grows too large to fit within the model’s context window. Book uses proactive compaction, driven by local outgoing-payload estimation rather than solely by provider-reported token counts.

Compaction Decision (CompactionPolicy)

Before every provider call, AgentLoop invokes CompactionPolicy.shouldCompact() using:

max(localEstimate, providerInputTokens) > contextWindow Γ— thresholdFraction
  • localEstimate: conservative token count from OutgoingContextEstimator over the pruned messages and current tool schemas (1 token β‰ˆ 4 chars heuristic).

  • providerInputTokens: AgentState.lastTurnInputTokens β€” the input token count reported by the provider/gateway for the most recent completed turn. May be zero, stale, or under-reported by some gateways.

  • contextWindow: from ModelMetadata.contextWindow; falls back to a configurable fallbackContextWindow (default 32 000) when metadata is unavailable.

  • thresholdFraction: configurable fraction (default 0.70) β€” conservative relative to the old hard 80 % check so compaction is triggered slightly earlier while still allowing a meaningful context budget.

Using max() of both estimates means compaction triggers correctly even when the gateway under-reports or omits usage data.

Compaction Flow (per turn, runs at most once)

When CompactionPolicy says to compact:

  1. Compact β€” older messages are summarised via an LLM call: the history is split, all but the last 5 messages are sent as a summarisation prompt, and the resulting SystemMessage("CONTEXT SUMMARY: …") replaces them.

  2. Re-intercept β€” ContextEvent is re-fired so extensions see the compacted messages.

  3. Re-prune β€” the full pruner pipeline is re-applied to the compacted, intercepted messages.

  4. Re-estimate β€” OutgoingContextEstimator runs once more (for logging/state; no second policy check β€” compaction runs at most once per turn to prevent recursive loops).

  5. The compacted, pruned messages are sent to the provider.

When CompactionPolicy says no compaction is needed, the pruned messages from Phase 1 are sent directly to the provider.

Legacy isCompactionNeeded(): AgentLoop retains the older isCompactionNeeded() method which checks AgentState.lastTurnInputTokens against 80 % of modelMetadata.contextWindow. This is no longer used in the main turn loop β€” it is preserved for backward-compatibility with external callers and extensions that may observe it.


No-Progress Cap

To prevent runaway empty-argument spirals, TurnProcessor tracks consecutive unproductive turns via TurnSession.unproductiveTurns. After every turn, isTurnProductive(assistantMessage, toolResults) (from TurnProgress.kt) classifies the turn:

Condition Productive?

β‰₯1 ToolResultMessage with isError == false

βœ… Yes

AssistantMessage contains non-blank AssistantContent.Text

βœ… Yes

All tool results have isError == true and assistant text is blank/absent

❌ No

  • A productive turn resets session.unproductiveTurns to zero.

  • An unproductive turn increments session.unproductiveTurns.

  • When session.unproductiveTurns reaches maxUnproductiveTurns (default 3), TurnProcessor calls abortTurn(…​) (emitting TurnEnd, BookEvent.TurnEnd, stateMachine.onError(reason), and AgentEvent.Error(reason)) and returns TurnOutcome.StopError(reason) β€” stopping the spiral well before maxTurns (default 200).

The threshold is configurable via AgentLoopConfig.maxUnproductiveTurns (default 3, populated from the environment variable BOOK_MAX_UNPRODUCTIVE_TURNS at CLI startup). The counter lives inside TurnSession and resets automatically on every new user message (each new run() call).


Empty-Argument Guard Policy

Four cooperative layers prevent empty-argument ({}) tool calls from consuming tokens and polluting the context window:

  1. EmptyArgumentGuard (pre-execution fast-fail): intercepts any tool call whose arguments are genuinely empty ({}) when the tool declares required parameters. Returns a corrective ToolResult(isError = true) with the marker [ARGUMENTS MISSING] and the list of required keys β€” without ever executing the tool or touching RepeatCallDetector.

  2. EmptyArgumentCircuitBreaker (runtime safety fuse): tracks consecutive empty-argument strikes within ToolCallExecutor. After a configurable number of consecutive empty-argument calls (default 3 strikes), it returns a concise circuit-break ToolResult(isError = true) with a terse reason string such as Empty-argument circuit breaker tripped for tool 'bash' at strike 3/3. and does not execute the tool. AgentLoop detects this reason via EmptyArgumentCircuitBreaker.TRIP_REASON_PREFIX and immediately stops the run with AgentEvent.Error, bypassing the generic no-progress cap.

    • A valid non-empty tool call resets the strike counter to zero.

    • The circuit breaker is a per-ToolCallExecutor instance (session-scoped) β€” it is not reset between run() calls.

  3. PureToolResultCache (defensive caching): guards both put and get against empty arguments ({}) and empty content. An empty-arg call is never stored in or served from the cache β€” even if the tool is deterministic.

  4. EmptyArgumentCallPruner + ToolResultPruner (context de-amplifiers):

    • EmptyArgumentCallPruner removes empty-arg call/result pairs from the context window before the next provider call β€” the model does not see a growing history of malformed calls.

    • ToolResultPruner additionally replaces any surviving [ARGUMENTS MISSING] stub with a neutral one-liner [<toolName> β€” malformed call omitted; do not repeat], suppressing the amplifier loop that would otherwise re-inject the marker into every subsequent turn.


Recent-Window Error Suppression (ToolErrorPatternPruner)

Even when ToolResultPruner stubs old results (outside the last 20 messages), repeated identical tool errors inside the recent window can create a dense negative few-shot pattern that reinforces broken behaviour in the model.

ToolErrorPatternPruner runs before ToolResultPruner in the pruning pipeline and addresses this:

  • It scans all ToolResultMessage(isError = true) entries in the current message list.

  • Two error messages are considered equivalent when they share the same toolName and the same normalised (trimmed, lowercased) error text.

  • The first occurrence of each unique error signature is preserved verbatim.

  • All subsequent duplicates are removed and a single compact suppression summary is appended:

` [bash β€” 2 repeated equivalent error results suppressed] ` The suppression message uses isError = false so it is never itself treated as an error by isTurnProductive() or the circuit breaker.

  • Non-error (isError = false) results are never touched.

  • Different error messages for the same tool are each preserved independently. The suppression record is inserted in-place at the position of the first duplicate, preserving the tool_use β†’ tool_result adjacency invariant required by the provider API. Suppression records are never appended to the tail of the history.

This interacts cleanly with EmptyArgumentCallPruner: empty-arg call/result pairs are deleted entirely before ToolErrorPatternPruner runs, so the pattern pruner never needs to handle [ARGUMENTS MISSING] orphans.


Streaming Pipeline

StreamFrameHandler β€” Frame Dispatch

StreamFrameHandler (us.nineworlds.book.providers.koog) processes each StreamFrame emitted by the Koog executor and converts it into zero or more `AgentEvent`s. The dispatch table is:

StreamFrame type Action

TextDelta

Append to assistantText; emit AgentEvent.TextDelta

ReasoningDelta

Append to assistantThinking; emit AgentEvent.ThinkingDelta

ToolCallComplete (named name)

Start a new tool call entry, seed arg accumulator if content non-blank; emit AgentEvent.ToolCallStarted

ToolCallComplete (blank name)

Accumulate content chunk into the arg accumulator for the target tool call (LiteLLM / Bedrock incremental streaming path)

ToolCallDelta (non-blank name)

Start a new tool call entry β€” same as named ToolCallComplete; emit AgentEvent.ToolCallStarted

ToolCallDelta (null / blank name)

Accumulate content chunk into the arg accumulator for the target tool call (OpenAI delta-streaming path)

End

Finalize all accumulated arguments, build AssistantMessage, emit AgentEvent.Completed

anything else

Log at DEBUG level and discard

Paired-Frame De-Duplication (Double-Emitting Gateways)

Some gateways double-emit every tool-call event: each logical event arrives as a StreamFrame.ToolCallDelta immediately followed by an identical StreamFrame.ToolCallComplete (the Delta always first, the Complete second). This was observed on the LiteLLM proxy β†’ claude-sonnet-4-6 path. Without de-duplication each named start frame would create the tool call twice (toolCalls=2) and each argument chunk would be accumulated twice and interleaved (raw=[[[{"c{"comommand": mand": "pwd"}"pwd"}]]]), corrupting the JSON and shipping`arguments = {}.

StreamFrameHandler collapses these pairs with a single-frame look-back (dedupePairedFrame). It records the signature of the most recently processed tool-call frame and skips the next frame when it is the duplicate half of a pair. A frame is treated as a duplicate if and only if the stored frame:

  • is the opposite type (Delta ↔ Complete), and

  • matches on id + normalized name + content + index (the name is normalized so null/blank β†’ "").

When a pair is detected the stored signature is consumed (cleared) so a subsequent genuine same-content frame is not also skipped; the duplicate frame returns an empty event list and is logged at DEBUG (deduplicated paired … frame). This applies to both the named-start path and the blank-name argument-chunk path, so each chunk is accumulated exactly once and parses to valid JSON.

What is not de-duplicated (de-dup fires only on opposite-type adjacency with a full signature match):

  • Pure ToolCallDelta streaming (same-type consecutive frames) β€” the standard OpenAI-compatible delta path is untouched.

  • Pure blank-name ToolCallComplete streaming (same-type consecutive frames) β€” the legacy LiteLLM / Bedrock incremental path is untouched.

  • Opposite-type frames with different content β€” e.g. a Delta carrying {"a":1, followed by a Complete carrying "b":2}. The signature mismatch means both chunks are accumulated normally (β†’ {"a":1,"b":2}), guarding against false-positive de-duplication of legitimate finalization frames.

Tool-Call Argument Accumulation

Arguments for a single tool call may arrive as a stream of incremental chunks via either of two provider-specific frame types:

  • ToolCallDelta (blank name) β€” the standard OpenAI-compatible delta streaming path. Each chunk carries a content string fragment and an optional index identifying which tool call it belongs to.

  • ToolCallComplete (blank name) β€” the LiteLLM / Bedrock incremental accumulation path. Chunk routing is identical to ToolCallDelta (including the index fallback).

Both paths feed the same index-keyed accumulator (toolCallArgAccumulators: Map<Int, StringBuilder>):

  • If the frame carries an explicit index field, the chunk is routed to the accumulator at that key. This handles interleaved / parallel tool-call streams correctly: frames for index N may arrive before frames for index 0 without cross-contamination.

  • If index is null (legacy path), the chunk is appended to the accumulator for the last-started tool call (toolCalls.size - 1). This preserves backwards compatibility with providers that do not emit an index.

Argument Finalization β€” Both End and Fallback Paths

finalizeToolCallArgs() parses every accumulator string into a JsonObject and writes it back into the matching toolCalls entry. It is called in two places to guarantee completeness:

  1. Normal path β€” at the top of handleEnd(), before building the final AssistantMessage.

  2. Stall / timeout path β€” at the top of buildFallbackMessage(), before building the fallback AssistantMessage. This ensures that when InactivityWatchdog fires (or the stream is cancelled for any other reason) before a StreamFrame.End arrives, the accumulated argument chunks are still written into the tool calls rather than being lost as {}.

finalizeToolCallArgs() is idempotent: re-parsing the same accumulated content produces the same JsonObject without corruption. No sentinel guard is required.

InactivityWatchdog β€” Timeout Defaults

InactivityWatchdog (us.nineworlds.book.providers.koog.watchdog) monitors the stream for inactivity and cancels it if no frame arrives within the idle threshold while content has already been buffered. The default values are tuned for large tool-call generations (e.g. write_file with multi-KB content) where providers can pause more than 5 s between token bursts and total generation may exceed 60 s:

Parameter Default Rationale

streamTimeout

600 s (10 min)

Overall wall-clock budget for a single stream. Raised from 60 s to accommodate long tool-argument generations.

thresholdMs

30 000 ms (30 s)

Maximum idle gap between frames before the watchdog fires. Raised from 5 s for the same reason.

checkInterval

1 s

How often the watchdog polls the idle timer.

Callers that need tighter SLAs (e.g. test code, short conversational turns) can pass explicit values via the constructor. KoogAgent constructs InactivityWatchdog() with no arguments and therefore always inherits these defaults automatically.

Reasoning Frames Count as Activity

StreamOrchestrator calls watchdog.recordFrame() unconditionally for every collected StreamFrame β€” including StreamFrame.ReasoningDelta. This is deliberate: extended reasoning ("thinking") phases can produce no visible text output for tens of seconds while the model works, and treating those gaps as idleness would cancel healthy streams mid-think. Each reasoning delta therefore resets the idle timer exactly like a text delta, so a stream survives as long as the provider keeps emitting reasoning tokens. The watchdog still fires if the provider stalls entirely (reasoning or otherwise) past thresholdMs, and its stall/timeout fallback path (see above) finalizes any accumulated tool-call arguments. Contract pinned by InactivityWatchdogReasoningDeltaTest (orchestrator-level recordFrame() verification plus controlled-clock keep-alive/stall tests).

Cancellation & Unwinding Semantics

The agent loop distinguishes three cancellation sources to balance interactive user control against stream resilience:

Cancellation Source Cause Mechanism Behavior

User Job Cancel

User presses Ctrl+C (cancelAgent()) or cancels outer Job

Cancels caller coroutine Job

Full Unwind: CancellationException rethrows through StreamOrchestrator, ToolCallExecutor, and BashTool. Child process trees are killed. Agent run halts cleanly.

Inactivity Watchdog

Idle gap exceeds threshold (e.g. 30s) or stream total timeout (600s)

Cancels internal watchdog Job

Soft-Stop: StreamOrchestrator catches cancellation, checks ensureActive(), logs warning, finalizes accumulated tool args, and emits fallback AgentEvent.Completed.

Turn Boundary Cap

Loop reaches max turns limit or empty argument guard triggers

Controlled loop exit

Normal Terminal: Emits terminal AgentEvent.Completed without throwing.

Discrimination Rule (StreamOrchestrator)

When a CancellationException is caught during streaming collection:

  1. StreamOrchestrator executes currentCoroutineContext().ensureActive().

  2. Caller Job Cancelled: If the calling coroutine context is inactive, ensureActive() rethrows CancellationException. This unwinds the stream, tool execution, and loop state immediately.

  3. Watchdog Job Cancelled Only: If the calling coroutine context remains active, ensureActive() succeeds. The orchestrator logs a warning, finalizes any partial tool arguments via finalizeToolCallArgs(), and emits fallback AgentEvent.Completed.

Tool & Process Cleanup

  • ToolCallExecutor & BashTool: Both explicitly rethrow CancellationException before broad catch (e: Exception) blocks, preventing cancellation from being wrapped as an error ToolResult.

  • ProcessBuilderRunner: On flow cancellation, awaitClose destroys the spawned process and all descendant child processes (ProcessHandle.descendants()). If child processes do not terminate within a grace period (100ms), they are forcibly terminated (destroyForcibly()). '''

Sequence Diagrams

Main Agent Cycle

Diagram

Tool Execution Strategy (with Cache & Loop Guard)

Diagram

Token Optimisation Pipeline

Diagram

Class Diagrams

Main Execution Cycle β€” Classes

Diagram

Covers: AgentLoop, AgentState, AgentPhase, AgentLoopConfig, all context/result types, Agent, ModelMetadata, the full AgentEvent sealed hierarchy, Message hierarchy, AssistantContent, Content, Usage/Cost, and all token-optimisation classes.

Tool Execution Strategy β€” Classes

Diagram

Focused view covering: ToolCallExecutor (extracted execution pipeline, owned by AgentLoop), AgentLoopConfig (before/afterToolCall hooks), Tool, ToolRegistry, ToolResult, PureToolResultCache, RepeatCallDetector, and the AgentEvent.ToolExecution* events.


Hooks and Configuration

The AgentLoop behavior can be customized via the AgentLoopConfig interface:

Turn Execution Limits & Pruning Properties

  • maxTurns: Maximum agent loop iterations (tool-call turns) per run before stopping with MaxTurnsReached (default 200).

  • isPruningDisabled: Disables message pruning pipeline and proactive compaction (default false).

  • maxUnproductiveTurns: Maximum consecutive unproductive turns before stopping with StopError (default 3).

  • cacheMaxTurnAge: Cache TTL in agent turns for deterministic tool results (default 5).

Lifecycle Hooks

  • beforeToolCall: Kotlin host-code gate called before every tool execution. Receives the full AgentContext (messages, system prompt, tool list). Return BeforeToolCallResult(block = true) to block the call. Default implementation returns null (allow). This hook fires before any script interceptors β€” it is the programmatic host-code layer; script-based approval runs separately in the ToolCall extension interceptor.

  • Opt-in interactive approval: By default all tools execute freely ("yolo mode"). Install tool_approval.bk.kts in ~/.bk/tools/ or .bk/tools/ to enable interactive APPROVE / DENY / ALWAYS_APPROVE prompts. The ToolCall intercept (via ExtensionRegistry) is the hook scripts use β€” see Extension API: Opt-in Tool Approval.

  • afterToolCall: Modify the result of a tool call before it’s sent back to the LLM.

  • shouldStopAfterTurn: Decide if the loop should terminate early.

  • getSteeringMessages: Inject "steering" prompts (like "STOP" or "Redirect") while the agent is thinking.

  • getFollowUpMessages: Inject follow-up messages when the agent finishes but there is no tool call.

  • prepareNextTurn: Optionally replace the full context for the next turn. '''

Test Seams

The AgentLoop constructor accepts an AgentLoopStateMachine parameter β€” tests can inject a DefaultAgentLoopStateMachine directly or a custom fake to assert on state transitions independently of agent loop orchestration:

val stateMachine = DefaultAgentLoopStateMachine()
val agentLoop = AgentLoop(agent, toolRegistry, extensionRegistry, stateMachine = stateMachine)

The token-optimisation and context-hardening subsystems are injected via internal var properties, allowing unit tests to swap in controlled instances:

// Pruning pipeline
agentLoop.orphanPruner            = OrphanedToolResultPruner()
agentLoop.emptyArgPruner          = EmptyArgumentCallPruner()
agentLoop.errorPatternPruner      = ToolErrorPatternPruner()
agentLoop.pruner                  = ToolResultPruner(keepLastN = 1)
agentLoop.assistantPruner         = AssistantMessagePruner(keepLastN = 1)
agentLoop.thinkingPruner          = ThinkingPruner()

// Proactive compaction
agentLoop.outgoingContextEstimator = OutgoingContextEstimator()
agentLoop.compactionPolicy         = CompactionPolicy()

// Tool execution
agentLoop.toolCallExecutor.toolResultCache             = PureToolResultCache()
agentLoop.toolCallExecutor.repeatCallDetector          = RepeatCallDetector()
agentLoop.toolCallExecutor.emptyArgumentCircuitBreaker = EmptyArgumentCircuitBreaker()

Note: PureToolResultCache, RepeatCallDetector, and EmptyArgumentCircuitBreaker are owned by ToolCallExecutor and are intentionally not reset between run() calls β€” all three are session-scoped and persist for the lifetime of the AgentLoop instance. Tests that need a clean state must inject fresh instances via agentLoop.toolCallExecutor before calling run().