> ## Documentation Index
> Fetch the complete documentation index at: https://phaseo.app/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Events, Retries, and Errors

> Observe synchronous Rust agent runs and handle model or tool failures.

## Lifecycle events

Use `run_with_events(...)` or `continue_with_events(...)` to receive events synchronously:

```rust theme={null}
use phaseo_agent::{AgentEvent, RunOptions};

let mut on_event = |event: &AgentEvent| {
    println!(
        "{} run={} details={}",
        event.event_type,
        event.run_id,
        event.details
    );
};

let result = agent.run_with_events(
    &mut client,
    RunOptions::new("Check project health"),
    Some(&mut on_event),
)?;
```

The runtime currently emits:

* `run.started`
* `model.request.started`
* `model.response.completed`
* `tool.started`
* `tool.completed`
* `run.paused`
* `run.resumed`
* `run.completed`
* `run.stopped`

Callbacks execute on the run's thread. Keep them fast or hand work to another component.

## Model retries

```rust theme={null}
use std::time::Duration;

let definition = AgentDefinition::new(
    "resilient-agent",
    "openai/gpt-5.6-sol",
)
.model_retries(2, Duration::from_millis(250));
```

`max_retries` counts additional attempts after the first request. `RunStep.model_attempts` records how many attempts produced the successful model response.

## Usage

`RunResult.usage` aggregates:

* `input_tokens`
* `output_tokens`
* `cached_tokens`
* `total_tokens`
* `cost`, when the model client populates it

Each `RunStep` also contains its own usage summary, request ID, provider, model, and finish reason.

The built-in `0.1` Gateway adapter does not map Gateway `cost_nanos` or `cost_cents` into `UsageSummary.cost`. Read the Gateway response or generation record when exact spend is required.

## Errors

All runtime failures use `AgentError`:

```rust theme={null}
match agent.run(&mut client, options) {
    Ok(result) => println!("{}", result.output),
    Err(error) => eprintln!("Agent failed: {}", error.message()),
}
```

Gateway `PhaseoError` values are converted into `AgentError`. If an application needs the original Gateway status and body, call the `phaseo` client directly or implement a custom `ModelClient` that preserves those fields in its own error handling.

Local tool executor errors are returned to the model as tool results instead of ending the run immediately.

## Step limits

`AgentDefinition::max_steps(...)` sets the default model-turn limit. Override it for one run:

```rust theme={null}
let mut options = RunOptions::new("Investigate this issue");
options.max_steps = Some(4);
```

When the limit is reached, `run.status` is `stopped` and `run.stop_reason` is `max_steps:<limit>`.
