Agent Loop
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 β constructsTurnProcessorandTurnSession, drives the turn loop, and acts onTurnOutcomevariants; 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 publicexecuteTurn()returningTurnOutcome -
TurnSession.kt: Mutable session state holder β ownscurrentMessages,newMessages,unproductiveTurnscounter, andpendingSteeringMessagesacross turns -
TurnOutcome.kt: Sealed outcome type with 4 variants (Continue,StopComplete,StopError,MaxTurnsReached) returned byexecuteTurn() -
ToolCallExecutor.kt: Tool-call execution pipeline β dispatches parallel/sequential, enforces cache, loop guard, config hooks, and extension intercepts -
TurnProgress.kt: Pure functionisTurnProductive(assistantMessage, toolResults)β returnstruewhen β₯1 tool result succeeded (isError == false) or the assistant produced non-blank text; used byTurnProcessorto 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 toAgentLoopConfig.beforeToolCall()andafterToolCall()respectively β give host Kotlin code access to the fullAgentContext(messages, system prompt, all tools) before/after each tool execution
us.nineworlds.book.domain.agentloop.state
-
AgentState.kt: State data class andAgentPhaseenum (IDLE, THINKING, EXECUTING_TOOLS, COMPLETED, ERROR) -
AgentLoopStateMachine.kt: Interface that ownsMutableStateFlow<AgentState>and all phase transitions β the single authority for state mutation. Transition methods: -
onStart()β transitions toTHINKING -
onTextDelta(text)/onThinkingDelta(text)β accumulates partial assistant content -
onToolsStarted()β transitions toEXECUTING_TOOLS -
onCompleted(message)β transitions toCOMPLETEDand records the finalAssistantMessage -
onError(reason)β transitions toERROR -
onReset()β resets state to a cleanAgentState(model, modelMetadata), discarding all phase, partial-message, and token data. Called byAgentLoop.resetState()when the user runs/newor/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 validAgentPhaseFSM 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 correctiveToolResultwithout 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 exceedsmaxCallsPerKey(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 viainvalidateByPath(path)(evicts the exact path and any ancestor-directory entries) and turn-based TTL viaadvanceTurn()/maxTurnAge(default 5 turns, envBOOK_CACHE_MAX_TURN_AGE).Content.Imageresults are excluded fromput()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 comparingmax(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: RemovesToolResultMessage`s whose `toolCallIdhas no matchingAssistantContent.ToolCallanywhere 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 oldToolResultMessagebodies 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 oldAssistantMessageentries -
ThinkingPruner.kt: Removes allAssistantContent.Thinkingblocks 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):
-
OrphanedToolResultPrunerβ removesToolResultMessage`s whose `toolCallIdhas no matchingAssistantContent.ToolCallanywhere 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.EmptyArgumentCallPrunerorAssistantMessagePruner) removed theAssistantMessagecontaining the matching call. -
EmptyArgumentCallPrunerβ scansAssistantMessageentries for tool calls whose argument object is{}and removes both the empty-arg call and its pairedToolResultMessagefrom the context sent to the provider. This prevents[ARGUMENTS MISSING]responses from accumulating in the model’s view of history. -
ToolErrorPatternPrunerβ scans allToolResultMessage(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 thetool_use β tool_resultadjacency invariant required by the provider API. -
ToolResultPrunerβ replacesToolResultMessagebodies 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. -
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. -
ThinkingPrunerβ removes allAssistantContent.Thinkingblocks. Thinking blocks are the model’s internal scratch-work (typically 1kβ5k tokens each); their conclusions are already captured in the companionTextcontent, 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:
-
Provide a text response to the user.
-
Call one or more tools.
-
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.
-
AgentLoopdelegates the entire execution batch toToolCallExecutor, which selects parallel or sequential dispatch based onAgentLoopConfig.toolExecutionand per-toolexecutionMode. -
Each tool execution can report progress updates back to the UI via
ToolExecutionUpdateevents.
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 fromOutgoingContextEstimatorover 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: fromModelMetadata.contextWindow; falls back to a configurablefallbackContextWindow(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:
-
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. -
Re-intercept β
ContextEventis re-fired so extensions see the compacted messages. -
Re-prune β the full pruner pipeline is re-applied to the compacted, intercepted messages.
-
Re-estimate β
OutgoingContextEstimatorruns once more (for logging/state; no second policy check β compaction runs at most once per turn to prevent recursive loops). -
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():AgentLoopretains the olderisCompactionNeeded()method which checksAgentState.lastTurnInputTokensagainst 80 % ofmodelMetadata.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 |
β Yes |
|
β Yes |
All tool results have |
β No |
-
A productive turn resets
session.unproductiveTurnsto zero. -
An unproductive turn increments
session.unproductiveTurns. -
When
session.unproductiveTurnsreachesmaxUnproductiveTurns(default 3),TurnProcessorcallsabortTurn(…)(emittingTurnEnd,BookEvent.TurnEnd,stateMachine.onError(reason), andAgentEvent.Error(reason)) and returnsTurnOutcome.StopError(reason)β stopping the spiral well beforemaxTurns(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:
-
EmptyArgumentGuard(pre-execution fast-fail): intercepts any tool call whose arguments are genuinely empty ({}) when the tool declares required parameters. Returns a correctiveToolResult(isError = true)with the marker[ARGUMENTS MISSING]and the list of required keys β without ever executing the tool or touchingRepeatCallDetector. -
EmptyArgumentCircuitBreaker(runtime safety fuse): tracks consecutive empty-argument strikes withinToolCallExecutor. After a configurable number of consecutive empty-argument calls (default 3 strikes), it returns a concise circuit-breakToolResult(isError = true)with a terse reason string such asEmpty-argument circuit breaker tripped for tool 'bash' at strike 3/3.and does not execute the tool.AgentLoopdetects this reason viaEmptyArgumentCircuitBreaker.TRIP_REASON_PREFIXand immediately stops the run withAgentEvent.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-
ToolCallExecutorinstance (session-scoped) β it is not reset betweenrun()calls.
-
-
PureToolResultCache(defensive caching): guards bothputandgetagainst empty arguments ({}) and empty content. An empty-arg call is never stored in or served from the cache β even if the tool is deterministic. -
EmptyArgumentCallPruner+ToolResultPruner(context de-amplifiers):-
EmptyArgumentCallPrunerremoves 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. -
ToolResultPruneradditionally 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
toolNameand 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_resultadjacency 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 |
|---|---|
|
Append to |
|
Append to |
|
Start a new tool call entry, seed arg accumulator if |
|
Accumulate |
|
Start a new tool call entry β same as named |
|
Accumulate |
|
Finalize all accumulated arguments, build |
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+ normalizedname+content+index(thenameis 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
ToolCallDeltastreaming (same-type consecutive frames) β the standard OpenAI-compatible delta path is untouched. -
Pure blank-name
ToolCallCompletestreaming (same-type consecutive frames) β the legacy LiteLLM / Bedrock incremental path is untouched. -
Opposite-type frames with different
contentβ e.g. aDeltacarrying{"a":1,followed by aCompletecarrying"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(blankname) β the standard OpenAI-compatible delta streaming path. Each chunk carries acontentstring fragment and an optionalindexidentifying which tool call it belongs to. -
ToolCallComplete(blankname) β the LiteLLM / Bedrock incremental accumulation path. Chunk routing is identical toToolCallDelta(including theindexfallback).
Both paths feed the same index-keyed accumulator (toolCallArgAccumulators: Map<Int, StringBuilder>):
-
If the frame carries an explicit
indexfield, the chunk is routed to the accumulator at that key. This handles interleaved / parallel tool-call streams correctly: frames for indexNmay arrive before frames for index0without cross-contamination. -
If
indexis 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 anindex.
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:
-
Normal path β at the top of
handleEnd(), before building the finalAssistantMessage. -
Stall / timeout path β at the top of
buildFallbackMessage(), before building the fallbackAssistantMessage. This ensures that whenInactivityWatchdogfires (or the stream is cancelled for any other reason) before aStreamFrame.Endarrives, 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 |
|---|---|---|
|
600 s (10 min) |
Overall wall-clock budget for a single stream. Raised from 60 s to accommodate long tool-argument generations. |
|
30 000 ms (30 s) |
Maximum idle gap between frames before the watchdog fires. Raised from 5 s for the same reason. |
|
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 ( |
Cancels caller coroutine |
Full Unwind: |
Inactivity Watchdog |
Idle gap exceeds threshold (e.g. 30s) or stream total timeout (600s) |
Cancels internal watchdog |
Soft-Stop: |
Turn Boundary Cap |
Loop reaches max turns limit or empty argument guard triggers |
Controlled loop exit |
Normal Terminal: Emits terminal |
Discrimination Rule (StreamOrchestrator)
When a CancellationException is caught during streaming collection:
-
StreamOrchestratorexecutescurrentCoroutineContext().ensureActive(). -
Caller Job Cancelled: If the calling coroutine context is inactive,
ensureActive()rethrowsCancellationException. This unwinds the stream, tool execution, and loop state immediately. -
Watchdog Job Cancelled Only: If the calling coroutine context remains active,
ensureActive()succeeds. The orchestrator logs a warning, finalizes any partial tool arguments viafinalizeToolCallArgs(), and emits fallbackAgentEvent.Completed.
Tool & Process Cleanup
-
ToolCallExecutor&BashTool: Both explicitly rethrowCancellationExceptionbefore broadcatch (e: Exception)blocks, preventing cancellation from being wrapped as an errorToolResult. -
ProcessBuilderRunner: On flow cancellation,awaitClosedestroys 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
Tool Execution Strategy (with Cache & Loop Guard)
Token Optimisation Pipeline
Class Diagrams
Main Execution Cycle β Classes
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
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 withMaxTurnsReached(default200). -
isPruningDisabled: Disables message pruning pipeline and proactive compaction (defaultfalse). -
maxUnproductiveTurns: Maximum consecutive unproductive turns before stopping withStopError(default3). -
cacheMaxTurnAge: Cache TTL in agent turns for deterministic tool results (default5).
Lifecycle Hooks
-
beforeToolCall: Kotlin host-code gate called before every tool execution. Receives the fullAgentContext(messages, system prompt, tool list). ReturnBeforeToolCallResult(block = true)to block the call. Default implementation returnsnull(allow). This hook fires before any script interceptors β it is the programmatic host-code layer; script-based approval runs separately in theToolCallextension interceptor. -
Opt-in interactive approval: By default all tools execute freely ("yolo mode"). Install
tool_approval.bk.ktsin~/.bk/tools/or.bk/tools/to enable interactive APPROVE / DENY / ALWAYS_APPROVE prompts. TheToolCallintercept (viaExtensionRegistry) 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, andEmptyArgumentCircuitBreakerare owned byToolCallExecutorand are intentionally not reset betweenrun()calls β all three are session-scoped and persist for the lifetime of theAgentLoopinstance. Tests that need a clean state must inject fresh instances viaagentLoop.toolCallExecutorbefore callingrun().