# Runs

> FlyMy.AI run lifecycle, streaming events, follow-up messages, freezing a run into a reusable Markdown instruction, re-running with variables.

A **Run** is a single execution of an agent. You start a run, the agent works autonomously using its configured goal and tools, and you get output when it finishes. Every run is logged with a full event timeline for debugging and observability.

## Run Lifecycle

```mermaid
stateDiagram-v2
    [*] --> pending
    pending --> running
    pending --> cancelled
    running --> completed
    running --> failed
    running --> cancelled
    completed --> [*]
    failed --> [*]
    cancelled --> [*]
```

| Status | Description |
|--------|-------------|
| `pending` | Queued, waiting to start |
| `running` | Agent is actively executing -- planning, calling tools, reasoning |
| `completed` | Finished successfully, output available |
| `failed` | Something went wrong -- error string available |
| `cancelled` | Cancelled by the user before completion |

## Starting a Run

A run is started by specifying the agent ID. The agent uses the goal configured at creation time.

**Python**

```python
from flymyai import AgentClient

client = AgentClient(api_key="fly-***")

run = client.runs.create(agent_id="agent_abc123")
```

**JavaScript**

```javascript
import { AgentClient } from "flymyai-js-client";

const client = new AgentClient({ apiKey: "fly-***" });

const run = await client.runs.create({ agentId: "agent_abc123" });
```

### Passing Variables

If the agent has an [`input_schema`](./inputs.md) and uses `{{ placeholders }}` in its goal, pass concrete values as `variables`. They are validated against the schema and rendered into the goal for this run:

```python
run = client.runs.create(
    agent_id="agent_abc123",
    variables={"topic": "AI agents in enterprise", "depth": "deep"},
)
```

Without an `input_schema`, `variables` are ignored and `{{ placeholders }}` are sent to the model as literal text. See [Inputs, Outputs & Variables](https://docs.flymy.ai/agents/concepts/inputs.md).

## Run Events

Every run emits `ExecutionLog` events that provide full visibility into what the agent is doing. Each event has `.type`, `.message`, `.data`, and `.created_at`.

| Event Type | Description |
|-----------|-------------|
| `declared_functions` | Agent declared the functions it plans to use |
| `tool_called` | Agent invoked a tool |
| `tool_call_exception` | A tool call failed with an error |
| `task_cancelled` | The run was cancelled |

### Streaming Events

`client.runs.stream_events(run_id)` yields `ExecutionLog` objects using polling-based delivery (not SSE).

**Python**

```python
for event in client.runs.stream_events(run.id):
    if event.type == "declared_functions":
        print(f"Functions: {event.data}")
    elif event.type == "tool_called":
        print(f"Tool called: {event.message}")
        print(f"Details: {event.data}")
    elif event.type == "tool_call_exception":
        print(f"Tool error: {event.message}")
    elif event.type == "task_cancelled":
        print("Run was cancelled")
```

**JavaScript**

```javascript
for await (const event of client.runs.streamEvents(run.id)) {
    console.log(`[${event.type}] ${event.message || ""}`);
    if (event.data) {
        console.log("  Data:", event.data);
    }
}
```

Example event stream:

```
[declared_functions]     Declared: tavily_search, browser_navigate
[tool_called]            Called tavily_search with query "renewable energy trends 2026"
[tool_called]            Called browser_navigate to extract page content
[tool_called]            Called tavily_search with query "solar cost decline statistics"
```

## Getting Results

A completed run provides `.status`, `.output`, `.error`, `.logs`, `.messages`, and `.original_prompt`.

**Python**

```python
# Wait synchronously (polls until terminal status)
result = client.runs.wait(run.id, timeout=300, poll_interval=2.0)

print(f"Status: {result.status}")
print(f"Output: {result.output}")

# Or fetch the current state without waiting
result = client.runs.get(run.id)
```

**JavaScript**

```javascript
const result = await client.runs.wait(run.id, { timeout: 300, pollInterval: 2.0 });
console.log(result.output);
```

### Run Detail Fields

| Field | Description |
|-------|-------------|
| `status` | Current run status (see lifecycle above) |
| `output` | The agent's result (alias for `agent_result`) |
| `error` | Error message string (when status is `failed`) |
| `logs` | List of `ExecutionLog` entries |
| `messages` | Conversation messages from the run |
| `original_prompt` | The prompt that was sent to the agent |

## Follow-up Messages

You can append a follow-up message to a run:

```python
client.runs.append_message(run.id, text="Can you also check competitor pricing?")
```

Over REST, `POST /api/v1/agents/executions/{execution_id}/append-message/` takes an optional `Idempotency-Key` (`operation_key` on the MCP tool `append_message`). A retry with the same key and text within 30 days returns the first answer with `Idempotent-Replayed: true` instead of adding the message again and starting a second run; another text under the same key gets 409 `idempotency_key_reused`. Without a key the call works as before.

## Cancelling a Run

Cancel a run that is still in progress:

```python
client.runs.cancel(run.id)
```

## Listing Runs

```python
# All runs for an agent
runs = client.runs.list(agent_id="agent_abc123")

for run in runs:
    print(f"{run.id}: {run.status} ({run.created_at})")
```

## Error Handling

When a run fails, `run.error` contains a plain error string describing what went wrong.

```python
result = client.runs.get(run.id)

if result.status == "failed":
    print(f"Error: {result.error}")
```

> **Tip**
>
> Use `stream_events()` alongside `wait()` to get real-time visibility into what the agent is doing. Events of type `tool_call_exception` can help you diagnose tool-related failures before the run finishes.

## Freeze & Re-run

> **Tip: Freeze anything you'll run more than once**
>
> An agent runs in one of two modes: **execute** it directly (one-off or interactive), or **freeze** it for repeated runs. If the same pipeline will run again - on a schedule, for each item in a list, or many times at scale - freeze it. The frozen `instruction_md` replays a fixed plan instead of re-planning on every run, which cuts token cost, lowers latency, and makes output deterministic. A genuine one-off doesn't need a freeze. ("Freeze" and "compile" are the same operation; the SDK surface is `client.compilations`.) Unsure whether the task repeats? Ask the user before deciding.

Once a run does what you wanted, you can **freeze** it. The backend reads the chat, the agent's [`input_description` / `output_description`](./inputs.md#plain-text-descriptions), and the schemas, then distills the canonical input → output pipeline into a Markdown instruction. Future executions skip exploration and follow that frozen plan.

```python
# Step 1 - freeze the run (returns once status is "compiled")
compilation = client.agents.compile_from_run(run.id, timeout=120)
print(compilation.instruction_md)

# Step 2a - re-run without variables (agent has no input_schema)
result = client.compilations.run_instruction_and_wait(compilation.id)

# Step 2b - re-run with fresh variables (agent has an input_schema)
result = client.compilations.run_instruction_and_wait(
    compilation.id,
    variables={"website_url": "https://example.com"},
)

print(result.output)                  # shaped by output_schema
print(result.output["score"])         # individual fields
```

What gets dropped: any chat turn outside the input → output path defined by your descriptions and schemas. Exploratory questions, one-off favors, abandoned branches — none of them survive the freeze. See the [Python SDK reference](https://docs.flymy.ai/agents/sdk/python.md#clientcompilations) for the lower-level building blocks (`freeze`, `run_instruction`, `wait`).

## Next Steps

- **[Tools](https://docs.flymy.ai/agents/concepts/tools.md)** -- browse the catalog, configure, and attach tools
- **[Agents](https://docs.flymy.ai/agents/concepts/agents.md)** -- configure the agent that runs execute
