<!-- source: https://deepwiki.com/qhkm/zeptoclaw/3.2-agent-loop -->

# Agent Loop

- src/agent/context.rs
- src/agent/loop.rs
- src/agent/middleware/injection_scan.rs
- src/agent/middleware/memory_injection.rs
- src/agent/middleware/metrics.rs
- src/agent/middleware/mod.rs
- src/agent/middleware/provider_resolution.rs
- src/agent/middleware/session.rs
- src/agent/middleware/session_save.rs
- src/agent/mod.rs
- src/agent/pipeline.rs
- src/channels/telegram.rs

The Agent Loop is the core message processing component responsible for orchestrating LLM interactions, tool executions, and conversation management. It receives inbound messages from the `MessageBus`, builds conversation context, calls LLM providers, executes requested tools, and returns responses.

In the latest architecture, the Agent Loop logic is increasingly being decomposed into a **Middleware Pipeline** [src/agent/middleware/mod.rs1-18](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/middleware/mod.rs#L1-L18) where cross-cutting concerns like token budgeting, session management, and safety scanning are handled by discrete middleware components.

## AgentLoop Structure

The `AgentLoop` struct coordinates all agent operations. It is defined in [src/agent/loop.rs362-423](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/loop.rs#L362-L423) and serves as the primary executor.

**Sources:** [src/agent/loop.rs362-423](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/loop.rs#L362-L423) [src/agent/mod.rs67-74](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/mod.rs#L67-L74)

## Component Relationships

**Diagram: AgentLoop Core Components**

```

```

**Sources:** [src/agent/loop.rs362-423](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/loop.rs#L362-L423) [src/agent/context.rs1-101](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/context.rs#L1-L101) [src/agent/budget.rs1-30](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/budget.rs#L1-L30) [src/agent/tool_call_limit.rs1-32](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/tool_call_limit.rs#L1-L32)

## Middleware Pipeline Execution

The system uses a `Pipeline` [src/agent/pipeline.rs19-22](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/pipeline.rs#L19-L22) to process messages through a chain of `Middleware` [src/agent/middleware/mod.rs68-78](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/middleware/mod.rs#L68-L78)

**Diagram: Middleware Execution Order**

```

```

### Key Middlewares

1. SessionMiddleware : Loads the Session using the session_key from the inbound message src/agent/middleware/session.rs 43-52
2. InjectionScanMiddleware : Scans for prompt injection. It blocks messages from webhook channels if patterns are detected src/agent/middleware/injection_scan.rs 55-72
3. ProviderResolutionMiddleware : Resolves the LLM provider and model, prioritizing metadata overrides like provider_override src/agent/middleware/provider_resolution.rs 48-65
4. MemoryInjectionMiddleware : Searches LongTermMemory and populates ctx.memory_override with relevant facts src/agent/middleware/memory_injection.rs 40-60
5. SessionSaveMiddleware : Persists the session to the SessionManager only if the pipeline execution was successful src/agent/middleware/session_save.rs 43-68

**Sources:** [src/agent/middleware/mod.rs1-18](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/middleware/mod.rs#L1-L18) [src/agent/pipeline.rs1-115](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/pipeline.rs#L1-L115) [src/agent/middleware/session.rs22-67](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/middleware/session.rs#L22-L67) [src/agent/middleware/injection_scan.rs23-93](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/middleware/injection_scan.rs#L23-L93)

## Context Building

The `ContextBuilder` in [src/agent/context.rs](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/context.rs) assembles the message context for LLM calls.

### RuntimeContext

`RuntimeContext` provides environment awareness at [src/agent/context.rs88-102](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/context.rs#L88-L102) It captures:

- Channel : "telegram", "cli", "discord", etc. src/agent/context.rs 122-125
- Available Tools : List of names registered in the ToolRegistry src/agent/context.rs 131-134
- Timezone : Local time computed dynamically via chrono::Local src/agent/context.rs 151-154
- Platform : OS and architecture (e.g., "linux aarch64") src/agent/context.rs 166-172

**Sources:** [src/agent/context.rs21-172](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/context.rs#L21-L172) [src/agent/context.rs354-376](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/context.rs#L354-L376)

## Tool Execution Loop

Tool execution in [src/agent/loop.rs1294-1481](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/loop.rs#L1294-L1481) follows a pipeline with parallel execution and safety checks.

### Sequential vs Parallel Execution

The agent determines whether to execute tools in parallel or sequentially based on their categories [src/agent/loop.rs108-124](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/loop.rs#L108-L124):

- Sequential : ToolCategory::FilesystemWrite or ToolCategory::Shell tools are executed one-by-one to preserve side-effect ordering src/agent/loop.rs 117-120
- Parallel : All other tools are executed concurrently using futures::join_all src/agent/loop.rs 1309

### Loop Guard and Repetition Detection

The `LoopGuard` detects repeated tool calls to prevent infinite loops.

- Warn : Repetition threshold approaching; a system message is added to history src/agent/loop.rs 143-154
- CircuitBreak : High frequency of repetitions; the entire agent loop is terminated src/agent/loop.rs 161-171

**Sources:** [src/agent/loop.rs108-124](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/loop.rs#L108-L124) [src/agent/loop.rs129-205](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/loop.rs#L129-L205) [src/agent/loop_guard.rs1-170](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/loop_guard.rs#L1-L170)

## Context Management and Compaction

### Context Compaction

When the `ContextMonitor` detects that history exceeds the configured `context_limit`, the agent performs a **Memory Flush** [src/agent/loop.rs1138-1150](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/loop.rs#L1138-L1150) This triggers a silent LLM turn instructing the agent to save important facts to `LongTermMemory` using the `MEMORY_FLUSH_PROMPT` [src/agent/loop.rs36-40](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/loop.rs#L36-L40)

### Token Budget

The `TokenBudget` tracks token usage atomically [src/agent/budget.rs12-30](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/budget.rs#L12-L30) The agent loop checks if the budget is exceeded before every LLM call [src/agent/loop.rs1196-1201](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/loop.rs#L1196-L1201)

**Sources:** [src/agent/loop.rs36-40](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/loop.rs#L36-L40) [src/agent/loop.rs1138-1157](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/loop.rs#L1138-L1157) [src/agent/budget.rs1-30](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/agent/budget.rs#L1-L30)
