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

# Runs: Lifecycle, Statuses, and How a Run Ends

> Understand the states a run moves through, what each final status means, and how to tell why a run ended

A run is one execution of a goal in a browser. Every call to the Web Agent creates a run, and the run moves through a fixed set of statuses until it reaches one of three final ones: `COMPLETED`, `FAILED`, or `CANCELLED`.

The status tells you whether the run finished. It doesn't tell you whether the goal was met, or why the agent stopped. That's the most important thing to understand about runs, and most of this page is about it.

## Run lifecycle

```mermaid theme={null}
stateDiagram-v2
  direction LR

  state "Request rejected · HTTP 4xx, no run is created" as REJECTED

  [*] --> PENDING: /run-async · /run-batch · /run-sse
  [*] --> REJECTED: bad key, bad body, rate limit or wallet issue

  PENDING --> RUNNING: browser starts · live view available
  PENDING --> CANCELLED: cancel request or billing rejected

  RUNNING --> COMPLETED: agent returns a result
  RUNNING --> FAILED: error (system or agent)
  RUNNING --> CANCELLED: cancel request · work so far is discarded

  COMPLETED --> [*]
  FAILED --> [*]
  CANCELLED --> [*]

  note right of COMPLETED
    Includes wrap-ups at login walls, bot blocks, step/time limits.
    Check result (add status/reason to your schema).
  end note
  note right of FAILED: Check error.category (error.code on sync /run only)
  note right of CANCELLED: Check error.category (UNKNOWN if stopped on purpose, BILLING_FAILURE if billing-rejected)
  note left of PENDING: Sync /run waits and returns only the final run

  classDef happy stroke:#D74B28,stroke-width:2px
  classDef rejected stroke-dasharray:5 5
  class COMPLETED happy
  class REJECTED rejected
```

| Status | Meaning | Final? |
| - | - | - |
| `PENDING` | Created and queued, waiting for a browser | No |
| `RUNNING` | The browser is working on your goal | No |
| `COMPLETED` | The run finished and the agent returned a result. Check `result` to see whether the goal was met | Yes |
| `FAILED` | The run stopped with an error. `error` says why | Yes |
| `CANCELLED` | The run was stopped before it finished, by a cancel request or the billing check | Yes |

A run only moves forward. Once it reaches a final status it never changes again, so you can stop polling as soon as you see one.

While a run is `PENDING` or `RUNNING`, `result` and `num_of_steps` are `null` and `streaming_url` shows the live browser. When it reaches a final status, `finished_at` and `num_of_steps` are filled in, and the recording moves to `video_url`.

How you see the lifecycle depends on the endpoint you used. `/run` waits and returns only the final run, so you never see the earlier statuses and you can't cancel it. `/run-async` and `/run-batch` return a `run_id` straight away for you to poll. `/run-sse` streams events (`STARTED`, `STREAMING_URL`, `PROGRESS`, `HEARTBEAT`, then `COMPLETE` with the final status). Runs from these three can be cancelled. See [Endpoints](https://docs.tinyfish.ai/tinyagent/api/agent/endpoints.md).

A request that's rejected before it starts, such as a bad API key, a malformed body, or a wallet that can't cover the run, returns an HTTP error and doesn't create a run at all.

In an organization, which runs a key can list and cancel depends on the kind of key. See [Who sees what](https://docs.tinyfish.ai/key-concepts/organizations.md#who-sees-what).

## Watching runs live

Every run has a `streaming_url` where you can watch the browser in real time. It's useful for debugging, for demos, and for telling a slow run from a stuck one. It works while the run is active. Once the run reaches a final status, use `video_url` on the run object for the recording instead. That link is signed and expires after 15 minutes, so fetch the run again when you need it.

## COMPLETED doesn't mean the goal succeeded

> [!WARNING]
>
> `COMPLETED` means the run finished, not that it did what you asked. Always check `result`.

The agent decides when it's done. If it gets everything you asked for, it returns the data. If it can't, because the page wants a login, a bot check stops it, or it runs out of steps, it usually still ends the run normally and writes what happened into `result`. The run is `COMPLETED` and `error` is `null` either way.

**Goal met.** A single-page product list:

```json theme={null}
{
  "status": "COMPLETED",
  "num_of_steps": 2,
  "error": null,
  "result": {
    "status": "success",
    "reason": "All 16 products with names and prices listed from the page.",
    "products": [{ "name": "Bulbasaur", "price": "£63.00" }]
  }
}
```

**Goal not met.** A five-page product list with a 3-step limit:

```json theme={null}
{
  "status": "COMPLETED",
  "num_of_steps": 4,
  "error": null,
  "result": {
    "status": "incomplete",
    "reason": "Ran out of steps before reaching page 5; only completed pages 1 and 2 of the required five pages.",
    "products": ["Page 1: Bulbasaur, Ivysaur, Venusaur, Charmander, ...", "Page 2: Pidgeotto, Pidgeot, Rattata, Raticate, ..."]
  }
}
```

Both of these returned a `status` and `reason` inside `result` because the request included an output schema asking for them. Without one, the explanation comes back as free text in `result`, worded however the agent chose. The next section explains why that matters.

## How a run ends

There are a handful of reasons a run stops, and each one needs a different response from you. These are the finish reasons:

| Finish reason | What happened | Where you usually see it | What helps |
| - | - | - | - |
| **Success** | The agent got what you asked for | `COMPLETED`, data in `result` | Nothing |
| **Auth required** | The page asked the agent to sign in, and the run had no way to log in | `COMPLETED` with `error: null`, and an empty field or an explanation in `result` | A TinyProfile or Vault credentials |
| **Blocked** | A CAPTCHA, a "verify you are human" page, or a bot-protection service stopped the agent | `COMPLETED` with `error: null`, and an explanation in `result` | The stealth browser and a proxy, or a TinyProfile |
| **Budget exhausted** | The run hit `max_steps` or `max_duration_seconds` before finishing | `COMPLETED` with `error: null`, and partial data plus a note in `result` | A higher limit, or smaller runs |
| **No finish** | The run ended without a result: it failed, it was cancelled, or it never came back | `FAILED` or `CANCELLED`, with `result: null` and an `error` | Depends on `error.category`; see below |

### There is no finish-reason field

The API doesn't return the finish reason as a field. For the first four reasons, the run is usually `COMPLETED` with `error: null`, and the reason is only in `result`. Here's the same login page twice. Without an output schema, the field you asked for is just empty:

```json theme={null}
{
  "status": "COMPLETED",
  "num_of_steps": 3,
  "error": null,
  "result": { "name": null }
}
```

With an output schema that asks for a `status` and `reason`, the same page explains itself:

```json theme={null}
{
  "status": "auth_required",
  "reason": "The page requires sign in to GitHub. No credentials are configured for this account, so login cannot succeed. The task cannot be completed without authentication."
}
```

A bot check looks the same. On a review page behind bot protection, with the default browser and no schema, the run ended `COMPLETED` after 5 steps with `error: null`, and the only sign of the block was in the text:

```txt theme={null}
Unable to extract the overall star rating. The G2.com page for Tinyfish reviews is blocked by a security challenge (DataDome)... shows a human verification form...
```

This is why the reliable way to get a finish reason is to ask for one. Add a `status` field with the reasons you care about (`success`, `auth_required`, `blocked`, `incomplete`) and a `reason` field to your output schema, and say in the goal what each one means. Your code can then branch on a value instead of reading prose. Keep only `status` and `reason` required: if a data field is required and the agent can't reach the data, it fills the field with a placeholder rather than leave it out. [Troubleshoot Runs](https://docs.tinyfish.ai/tinyagent/how-to/troubleshoot-runs.md#make-every-run-report-how-it-ended) has the full schema and goal.

### Sometimes the run fails instead

The same three problems can also end a run `FAILED`, with an error code that names them — but `error.code` is only returned by the synchronous `/run` endpoint. Polling `runs.get` and the SSE stream don't include `code`, only `error.category`, which doesn't distinguish between these three (all three fall under `AGENT_FAILURE`):

| Finish reason | `error.code` (sync `/run` only) |
| - | - |
| Auth required | `TASK_FAILED`, with a message about authentication |
| Blocked | `SITE_BLOCKED` |
| Budget exhausted | `MAX_STEPS_EXCEEDED`, when the run stops at the step limit without producing a result |

A run that a TinyProfile could fix may also carry a `profile_hint`, with a `reason` of `auth_wall` or `bot_challenge`, a `message`, and a `setup_url` that opens profile setup for that site. On a `COMPLETED` run — the auth-required or blocked case above — it's a top-level field next to `result`. On a `FAILED` run it sits inside `error` instead. It's the closest thing the API has to a finish-reason field, but it only appears when a profile would actually help, not on every auth wall or block.

So handle both: check `error` (and `error.profile_hint`) when the run failed, and your schema's `status` plus the top-level `profile_hint` when it completed.

### How the limits end a run

`max_steps` and `max_duration_seconds` don't cut a run off mid-step. When either runs out, the agent takes one more step to write up what it has, then ends the run `COMPLETED`:

* A run with `max_steps: 3` reports `num_of_steps: 4`. Expect one step over the cap.
* A run with `max_duration_seconds: 10` ran for about 21 seconds. One with `max_duration_seconds: 60` ran for 70.

The write-up says how far the agent got, but on a long run it can leave out the data itself. A 20-page product list with a 60-second limit came back with this:

```json theme={null}
{
  "status": "incomplete",
  "reason": "Only completed pages 1–5 of 20 due to budget exhaustion before the time limit. 80 products extracted across 5 pages.",
  "products": [],
  "last_page": 5
}
```

Treat a budget-exhausted result as a record of where the run stopped, not as the data. Goals that fit inside their limits don't have this problem, which is why splitting a big goal into small runs works better than raising the limit. See [Agent Mode, Max Steps, and Max Duration](https://docs.tinyfish.ai/tinyagent/explanation/agent-modes.md) for what each limit is for.

### No finish

A run that ends `FAILED` or `CANCELLED` has `result: null`, so there's nothing to read except `error`. `error.category` tells you how to react:

| `category` | Meaning | Examples |
| - | - | - |
| `SYSTEM_FAILURE` | A problem on the TinyFish side. Retry, after `retry_after` seconds if it's set | `SERVICE_BUSY`, `TIMEOUT` |
| `AGENT_FAILURE` | The run couldn't do the task. Change the input before you try again | `TASK_FAILED`, `SITE_BLOCKED`, `MAX_STEPS_EXCEEDED` |
| `BILLING_FAILURE` | The run was rejected at the billing check before it started. Add money at [agent.tinyfish.ai/wallet](https://agent.tinyfish.ai/wallet) (minimum top-up \$10), or add credits on a legacy account | `BILLING_REJECTED` |
| `UNKNOWN` | Not classified. Usually retryable | |

One case needs care: **a cancelled run also has an error, but its category depends on why it was cancelled.** A run stopped on purpose (yours or a cancel request) carries `category: "UNKNOWN"`. A run cancelled by the billing check carries `category: "BILLING_FAILURE"` instead — check `error.category`, not just `status`, before deciding whether to retry. Here's a run cancelled about a minute after it started:

```json theme={null}
{
  "status": "CANCELLED",
  "num_of_steps": 0,
  "result": null,
  "error": {
    "message": "Run cancelled by user",
    "category": "UNKNOWN",
    "retry_after": null,
    "help_url": "https://docs.tinyfish.ai/error-codes",
    "help_message": "Need help? See our error reference for troubleshooting tips."
  }
}
```

If your code retries on `UNKNOWN`, check `status` first, or it will restart runs that were stopped on purpose. Cancelling also discards the run's work: the result is `null` even if the agent had collected data before the cancel. The full list of codes is in [Error Codes](https://docs.tinyfish.ai/error-codes.md).

### Who runs into which

Which finish reason you hit depends mostly on the kind of site and task:

* **Auth required** comes up most when the task is in your own account: an admin dashboard, a Google or Microsoft form you're creating or editing, or a job application. Those pages need a signed-in session, so plan for a TinyProfile or Vault from the start.
* **Blocked** comes up most on travel, shopping, review, and social sites, which use bot protection heavily. Price comparisons and collecting posts or reviews hit it often.
* **Budget exhausted** and **no finish** come up most on long, multi-site work, such as comparing prices across several sites or paging through a long list in one run. Splitting the work into one run per site or page avoids both.
* Single-page extraction with an output schema, which is most API and SDK use, mostly ends in **success**. When it doesn't, the schema's `status` says why.

## Handling run results

Put it together by checking the final status first, then the right field for that status:

**Python**

```py theme={null}
from tinyfish import TinyFish, RunStatus

client = TinyFish()


def handle_run(run):
    if run.status in (RunStatus.CANCELLED, RunStatus.FAILED):
        category = run.error.category if run.error else "UNKNOWN"
        # A billing-rejected run also ends CANCELLED, not just FAILED — check
        # category before treating CANCELLED as "stopped on purpose, don't retry."
        if run.status == RunStatus.CANCELLED and category != "BILLING_FAILURE":
            return {"ok": False, "ended": "cancelled", "retry": False}
        retry = category in ("SYSTEM_FAILURE", "UNKNOWN")
        return {"ok": False, "ended": category, "retry": retry}

    # COMPLETED: the run finished. Read your schema's status to see how.
    outcome = run.result or {}
    if outcome.get("status") == "success":
        return {"ok": True, "data": outcome}
    return {"ok": False, "ended": outcome.get("status"), "reason": outcome.get("reason")}


run_id = "7c2b641f-ec9c-4aa5-b47d-435f310d26ad"  # from client.agent.queue() or the STARTED event
run = client.runs.get(run_id)
print(handle_run(run))
```

**TypeScript**

```ts theme={null}
import { TinyFish, RunStatus } from "@tiny-fish/sdk";
import type { Run } from "@tiny-fish/sdk";

const client = new TinyFish();

function handleRun(run: Run) {
  if (run.status === RunStatus.CANCELLED || run.status === RunStatus.FAILED) {
    const category = run.error?.category ?? "UNKNOWN";
    // A billing-rejected run also ends CANCELLED, not just FAILED — check
    // category before treating CANCELLED as "stopped on purpose, don't retry."
    if (run.status === RunStatus.CANCELLED && category !== "BILLING_FAILURE") {
      return { ok: false, ended: "cancelled", retry: false };
    }
    const retry = category === "SYSTEM_FAILURE" || category === "UNKNOWN";
    return { ok: false, ended: category, retry };
  }

  // COMPLETED: the run finished. Read your schema's status to see how.
  const outcome = (run.result ?? {}) as { status?: string; reason?: string };
  if (outcome.status === "success") return { ok: true, data: outcome };
  return { ok: false, ended: outcome.status, reason: outcome.reason };
}

const runId = "7c2b641f-ec9c-4aa5-b47d-435f310d26ad"; // from client.agent.queue() or the STARTED event
const run = await client.runs.get(runId);
console.log(handleRun(run));
```

This assumes an output schema with a `status` field, as described above. To see the steps the agent took before it ended, read `steps` on `GET /v1/runs/{id}`. Each step has a timestamp, a status, and the action taken, and screenshots are available per step. See [Runs Reference](https://docs.tinyfish.ai/tinyagent/api/runs.md).

## Agent mode and limits

`agent_config` controls how the agent behaves (`mode`) and how far it's allowed to go (`max_steps`, `max_duration_seconds`). See [Agent Mode, Max Steps, and Max Duration](https://docs.tinyfish.ai/tinyagent/explanation/agent-modes.md) for when to use each.

Runs can also sign in to sites. Pass `use_profile: true` to start from a saved TinyProfile, or `use_vault: true` (and optionally `credential_item_ids`) to log in with credentials from your connected password manager. See [TinyProfiles](https://docs.tinyfish.ai/key-concepts/tinyprofile.md) and [Vault Credentials](https://docs.tinyfish.ai/key-concepts/credentials.md).

## Related

> [card] [Troubleshoot Runs](https://docs.tinyfish.ai/tinyagent/how-to/troubleshoot-runs.md)
>
> Fix each finish reason

> [card] [Recover Stuck Runs](https://docs.tinyfish.ai/tinyagent/how-to/recover-stuck-runs.md)
>
> Stop, recover, and split long runs

> [card] [Runs Reference](https://docs.tinyfish.ai/tinyagent/api/runs.md)
>
> List, get, cancel, batch, and per-step screenshots and HTML

> [card] [Endpoints](https://docs.tinyfish.ai/tinyagent/api/agent/endpoints.md)
>
> Choose sync, async, batch, or streaming

> [card] [Agent Mode, Max Steps, and Max Duration](https://docs.tinyfish.ai/tinyagent/explanation/agent-modes.md)
>
> Default vs Strict mode, step and time limits

> [card] [Structured output](https://docs.tinyfish.ai/tinyagent/how-to/structured-output.md)
>
> Define the shape of `result`

> [card] [Error Codes](https://docs.tinyfish.ai/error-codes.md)
>
> Every code and how to handle it

> [card] [TinyProfiles](https://docs.tinyfish.ai/key-concepts/tinyprofile.md)
>
> Run as a signed-in user


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.