> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/nearai/ironclaw/llms.txt
> Use this file to discover all available pages before exploring further.

# Agent Module

> Core agent logic for orchestrating jobs, sessions, and tool execution

## Overview

The agent module orchestrates the core functionality of IronClaw:

* Message routing from channels
* Job scheduling and execution
* Tool invocation with safety guardrails
* Self-repair for stuck jobs
* Proactive heartbeat execution
* Routine-based scheduled and reactive jobs
* Turn-based session management with undo
* Context compaction for long conversations

## Core Types

### Agent

The main agent orchestrator that processes incoming messages and manages execution.

<ParamField path="user_id" type="String">
  User identifier for the agent session
</ParamField>

<ParamField path="session" type="Session">
  Current session state with threads and turns
</ParamField>

<ParamField path="workspace" type="Workspace">
  Persistent memory storage for the agent
</ParamField>

<ParamField path="tools" type="ToolRegistry">
  Available tools for the agent to use
</ParamField>

#### Example

```rust theme={null}
use ironclaw::agent::{Agent, AgentDeps};

let deps = AgentDeps {
    llm: Arc::new(llm_provider),
    workspace: Arc::new(workspace),
    tools: Arc::new(tool_registry),
};

let agent = Agent::new("user_123", deps);
```

### Session

A session contains one or more threads representing conversations with the agent.

<ParamField path="id" type="Uuid">
  Unique session identifier
</ParamField>

<ParamField path="user_id" type="String">
  User who owns this session
</ParamField>

<ParamField path="active_thread" type="Option<Uuid>">
  Currently active thread ID
</ParamField>

<ParamField path="threads" type="HashMap<Uuid, Thread>">
  All threads in this session
</ParamField>

<ParamField path="auto_approved_tools" type="HashSet<String>">
  Tools that have been auto-approved for this session
</ParamField>

#### Methods

<ResponseField name="new" type="fn(user_id: impl Into<String>) -> Self">
  Create a new session for a user
</ResponseField>

<ResponseField name="create_thread" type="fn(&mut self) -> &mut Thread">
  Create a new thread in this session and make it active
</ResponseField>

<ResponseField name="active_thread" type="fn(&self) -> Option<&Thread>">
  Get the currently active thread
</ResponseField>

<ResponseField name="is_tool_auto_approved" type="fn(&self, tool_name: &str) -> bool">
  Check if a tool has been auto-approved
</ResponseField>

<ResponseField name="auto_approve_tool" type="fn(&mut self, tool_name: impl Into<String>)">
  Add a tool to the auto-approved set
</ResponseField>

#### Example

```rust theme={null}
use ironclaw::agent::Session;

let mut session = Session::new("user_123");
let thread = session.create_thread();

// Auto-approve a tool for this session
session.auto_approve_tool("file_read");
assert!(session.is_tool_auto_approved("file_read"));
```

### Thread

A thread represents a conversation sequence with turns (request/response pairs).

<ParamField path="id" type="Uuid">
  Unique thread identifier
</ParamField>

<ParamField path="session_id" type="Uuid">
  Parent session ID
</ParamField>

<ParamField path="turns" type="Vec<Turn>">
  Conversation history as turns
</ParamField>

<ParamField path="state" type="ThreadState">
  Current state (Active, Interrupted, Completed)
</ParamField>

### Turn

A single request/response pair in a conversation.

<ParamField path="id" type="Uuid">
  Unique turn identifier
</ParamField>

<ParamField path="user_message" type="String">
  User's input message
</ParamField>

<ParamField path="assistant_message" type="Option<String>">
  Agent's response (None if turn incomplete)
</ParamField>

<ParamField path="tool_calls" type="Vec<ToolCall>">
  Tool invocations made during this turn
</ParamField>

<ParamField path="state" type="TurnState">
  Current state (Pending, InProgress, Completed, Failed)
</ParamField>

### Routine

A scheduled or reactive job that runs automatically.

<ParamField path="id" type="Uuid">
  Unique routine identifier
</ParamField>

<ParamField path="name" type="String">
  Human-readable routine name
</ParamField>

<ParamField path="trigger" type="Trigger">
  When this routine should execute
</ParamField>

<ParamField path="action" type="RoutineAction">
  What the routine should do
</ParamField>

#### Trigger Types

<ResponseField name="Cron" type="String">
  Execute on a cron schedule (e.g., "0 9 \* \* \*")
</ResponseField>

<ResponseField name="Interval" type="Duration">
  Execute every N seconds/minutes/hours
</ResponseField>

<ResponseField name="Event" type="String">
  Execute when a specific event occurs
</ResponseField>

#### Example

```rust theme={null}
use ironclaw::agent::{Routine, RoutineAction, Trigger};
use std::time::Duration;

let routine = Routine {
    id: Uuid::new_v4(),
    name: "Daily standup reminder".to_string(),
    trigger: Trigger::Cron("0 9 * * 1-5".to_string()),
    action: RoutineAction::SendMessage {
        content: "Time for standup!".to_string(),
    },
};
```

### ContextCompactor

Compacts conversation history to save context window space.

<ResponseField name="compact" type="async fn(thread: &Thread) -> Result<CompactionResult>">
  Compact a thread's conversation history by summarizing old turns
</ResponseField>

<ResponseField name="should_compact" type="fn(thread: &Thread) -> bool">
  Check if a thread should be compacted based on size
</ResponseField>

#### CompactionResult

<ResponseField name="original_turns" type="usize">
  Number of turns before compaction
</ResponseField>

<ResponseField name="compacted_turns" type="usize">
  Number of turns after compaction
</ResponseField>

<ResponseField name="summary" type="String">
  Summary of compacted content
</ResponseField>

<ResponseField name="tokens_saved" type="u32">
  Approximate tokens saved by compaction
</ResponseField>

#### Example

```rust theme={null}
use ironclaw::agent::ContextCompactor;

let compactor = ContextCompactor::new(llm_provider);
if compactor.should_compact(&thread) {
    let result = compactor.compact(&thread).await?;
    println!("Saved {} tokens", result.tokens_saved);
}
```

### UndoManager

Manages checkpoints and undo operations for sessions.

<ResponseField name="create_checkpoint" type="fn(&mut self, session: &Session) -> Checkpoint">
  Create a checkpoint of the current session state
</ResponseField>

<ResponseField name="restore_checkpoint" type="fn(&mut self, checkpoint_id: Uuid) -> Result<Session>">
  Restore session to a previous checkpoint
</ResponseField>

<ResponseField name="list_checkpoints" type="fn(&self) -> Vec<Checkpoint>">
  List all available checkpoints
</ResponseField>

#### Example

```rust theme={null}
use ironclaw::agent::UndoManager;

let mut undo_mgr = UndoManager::new();

// Create checkpoint before risky operation
let checkpoint = undo_mgr.create_checkpoint(&session);

// If something goes wrong, restore
if needs_undo {
    let restored_session = undo_mgr.restore_checkpoint(checkpoint.id)?;
}
```

### SelfRepair

Detects and repairs stuck jobs and broken tools.

<ResponseField name="detect_stuck_jobs" type="async fn() -> Vec<StuckJob>">
  Find jobs that have been running too long
</ResponseField>

<ResponseField name="repair" type="async fn(task: RepairTask) -> Result<RepairResult>">
  Attempt to repair a stuck job or broken tool
</ResponseField>

#### RepairTask Types

<ResponseField name="StuckJob" type="{ job_id: Uuid, reason: String }">
  A job that needs to be unstuck
</ResponseField>

<ResponseField name="BrokenTool" type="{ tool_name: String, error: ToolError }">
  A tool that failed and needs repair
</ResponseField>

#### Example

```rust theme={null}
use ironclaw::agent::SelfRepair;

let repair = SelfRepair::new();
let stuck = repair.detect_stuck_jobs().await;

for job in stuck {
    let result = repair.repair(RepairTask::StuckJob {
        job_id: job.id,
        reason: "Timeout".to_string(),
    }).await?;
}
```

## Related Modules

<Card title="Workspace Module" icon="folder" href="/api/workspace">
  Persistent memory storage for agents
</Card>

<Card title="Tools Module" icon="wrench" href="/api/tools">
  Extensible tool system for agent capabilities
</Card>

<Card title="LLM Module" icon="brain" href="/api/llm">
  Language model integration and providers
</Card>
