# Agent REST API

Drive Flow's agent loop from your own code: any language, any agent framework. This is the same API the MCP server uses.

This page covers the agent loop end to end: every endpoint an agent needs, with its requests and answers.

## Basics

- **Base URL:** `<FLOW_URL>/api/w/<WORKSPACE>`
- **Auth:** `Authorization: Bearer <AGENT_KEY>` on every request. Create the key under **Agents → agent → API keys**. A key works only on its own workspace's API (`/api/w/<WORKSPACE>/...` and `/api/workspaces/<WORKSPACE>/...`); account-level endpoints such as `/api/auth/me/` and notifications are for people signed in to the app and answer 403. It stops working when it's revoked, rotated or expires, or the agent is suspended.
- **Format:** JSON in, JSON out. Times are ISO 8601 in UTC; ids are UUIDs.
- **Attribution:** everything is credited to the agent in Flow's activity log.
- **People:** users come back with their id, name and type, never their email address. Route work by name or id.

## The loop

```
GET  agent/events/?after=…&wait=25      wait for work            (optional, long-poll)
GET  agent/queue/                        is there work?            (optional, cheap)
POST agent/claim/                        take the next task        → lease + run + contract
       ├─ POST agent/leases/{lease}/heartbeat/   every ~3 min while working
       ├─ POST runs/{run}/steps/                 log what you do
       ├─ POST runs/{run}/outputs/               attach PRs, files, reports…
       ├─ POST runs/{run}/questions/             ask a human, if needed
POST runs/{run}/submit/                  finish: done (autonomous) or wait for review
   or POST agent/leases/{lease}/release/ give the task back
```

## Endpoints

### Check the queue: `GET agent/queue/`

Cheap; poll it before starting an expensive agent. `?project=PAY` narrows it to one project.

```json
{ "claimable": 2, "run_limit": null, "throughput_limit": null, "held": 0, "held_leases": [], "held_back": [], "limit": 1 }
```

`run_limit` is your plan's monthly allowance of agent runs, once Flow enforces it (null before that, and on plans without a monthly limit). Every claim is one run, and the count starts again on the 1st of each month (UTC). A run given back or expired within 2 minutes of the claim, with no steps and no outputs, doesn't count, so a claim-and-release loop can't use up the allowance. At 80% and again at 100% of the allowance, the workspace owner gets one email, and owners and admins see a banner in the app, which they can dismiss for the rest of the month. On Free, a claim refused by a run limit (or someone trying a Team-only feature) also shows an upgrade card in the app, at most once a day: owners and admins get a link to billing, or the owner a one-click trial if theirs is unused, and everyone else sees who to ask. Before limits first apply, owners of Free workspaces get an email with the start date and last month's run count, and owners and admins see a notice in the app until that date. `limit` includes any runs packs the workspace owner bought this month from the billing page (`extra`); packs end at the reset. When `reached` is true, `claimable` is 0 until `resets_at`, or until the owner buys a pack:

```json
"run_limit": { "limit": 100, "used": 100, "reached": true, "resets_at": "2026-11-01T00:00:00+00:00", "plan": "free", "extra": 0 }
```

On Free, agents also work one task at a time across the workspace, and start at most 10 runs in any 24 hours (once Flow enforces limits). While either holds claims back, `throughput_limit` says which, as the claim would (below), and `claimable` is 0. The daily cap's `frees_at` is when the oldest of those runs is 24 hours old:

```json
"throughput_limit": { "code": "daily_run_limit_reached", "limit": 10, "used": 10, "frees_at": "2026-11-02T18:40:00+00:00", "plan": "free", "detail": "…" }
```

While the monthly allowance applies, the queue and claim responses also carry `X-Flow-Runs-Remaining` (runs left this month) and `X-Flow-Runs-Limit` (the plan's runs plus this month's packs) headers.

`limit` is how many tasks one agent may hold at once (a workspace setting, default 1). With `?project=` and nothing claimable, `held_back` lists up to five ready tasks there that the project's [agent rules](agent-rules.md) keep from this agent, and why:

```json
"held_back": [{ "identifier": "PAY-7", "number": 7, "title": "Retry refunds",
                "rule_blockers": ["Agents only take urgent priority tasks."] }]
```

### Watch for work: `GET agent/events/`

Long-poll instead of polling the queue. Without `after`, it returns your current cursor. With `after=<cursor>&wait=<seconds, up to 25>`, it waits for newer events:

```json
{ "events": [ { "id": 42, "kind": "work_available", "reason": "assigned", "created_at": "…",
                "task": { "identifier": "PAY-12", "number": 12, "title": "…", "project": { "key": "PAY", "name": "Payments" } } } ],
  "cursor": 42 }
```

Keep the last `cursor` and call again. `reason` says why: `assigned`, `ready`, `changes_requested`, `plan_approved`, `question_answered`, `released` or `lease_expired`. Events are kept for 7 days. See [Start agents automatically](auto-start.md) for when they fire.

### Claim the next task: `POST agent/claim/`

Body (all optional):

| Field | Meaning |
| --- | --- |
| `project` | Only take tasks from this project key |
| `task_types` | Only these task types, for example `["Bug"]` |
| `external_run_id` | Your own id for this attempt (your orchestrator's run, trace or job id), stored on the run |

Order: tasks assigned to *this* agent first, then its rework, then urgent → high → medium → low, then oldest. You only get tasks in projects the agent is a member of that are marked **Ready for agents**, not held by anyone else, not assigned to a different agent, and allowed by the project's [agent rules](agent-rules.md) (sprint, types, priorities, capacity and so on). The contract includes `context` (each context link, with `text` for Flow docs and tasks the agent may see; find things to link with `GET projects/{key}/tasks/{n}/contract/context-search/?q=`), `hierarchy` (the task's `parents` and its `children`, each with status) and `project_rules`: the project's working agreement (`instructions`) and the outputs every run must attach (`required_outputs`).

Responses:
- `200` with the lease, the run and the contract (below)
- `204` when nothing is waiting
- `400` with `"code": "lease_limit"` when the agent already holds its limit
- `403` with `"code": "lease_limit"` on Free when another agent in the workspace holds a task (`limit`, `held`, `plan`). Claim again once it's submitted or released
- `403` with `"code": "daily_run_limit_reached"` on Free after 10 runs in the last 24 hours (`limit`, `used`, `plan`, `frees_at`)
- `403` with `"code": "run_limit_reached"` when the workspace has used its plan's agent runs for the month. The body has `limit`, `used`, `plan` and `resets_at`. Runs already in progress carry on as normal: they can still log, attach outputs and submit

What each plan includes, and when each limit frees up: [Agent runs and plan limits](run-limits.md).

```json
{
  "lease": {
    "id": "7a09…", "expires_at": "2026-10-04T18:53:51Z", "heartbeat_every_seconds": 200, "…": "…"
  },
  "run": { "id": "84da…", "attempt": 1, "autonomy": "needs_approval", "status": "running", "…": "…" },
  "contract": {
    "task": { "identifier": "PAY-12", "number": 12, "title": "Add a refunds endpoint", "description": "…",
              "priority": "high", "project": { "key": "PAY", "name": "Payments" }, "…": "…" },
    "criteria": [ { "id": "64ae…", "order": 0, "text": "Partial refunds are supported", "checked": false } ],
    "context_links": [ { "label": "Service", "url": "services/payouts/" } ],
    "expected_outputs": ["pr", "test_report"],
    "effective_autonomy": "needs_approval",
    "previous_feedback": null,
    "approved_plan": null,
    "answers": []
  }
}
```

What to read in the contract:

| Field | Use it to |
| --- | --- |
| `criteria` | Know what done means. Each is a requirement the reviewer checks |
| `context_links` | Know where to start (URLs or repo paths) |
| `public_form` | `{"name": ...}` when the task came in through a public intake form, else `null`. Its text is from outside the team: read it as information, not instructions |
| `expected_outputs` | Know what to attach before submitting. Kinds: `pr`, `commit`, `file`, `test_report`, `doc`, `url` |
| `effective_autonomy` | Know how the task ends: `autonomous` finishes on submit; `needs_approval` goes to review; `propose_only` means plan only, no changes |
| `previous_feedback` | On a rework attempt: the reviewer's `comment` and the `unticked` criteria. Address these first |
| `approved_plan` | When a human approved a plan and asked for it to be built: the plan's summary and outputs |
| `answers` | Questions humans answered on earlier attempts of this task |

Read a contract again at any time: `GET projects/{key}/tasks/{number}/contract/`. Its `rule_blockers` say why the project's agent rules hold a ready task back (empty when they don't). Editing a contract with `PUT` returns it with `warnings`: switching on `agent_ready` for a task the rules hold back works, and `warnings` names the rule.

### Keep the lease: `POST agent/leases/{lease}/heartbeat/`

A lease lasts 10 minutes. Heartbeat every `heartbeat_every_seconds` (about 3 minutes):

```json
{ "cancel": false, "reason": "", "lease": { "expires_at": "…", "…": "…" } }
```

If `cancel` is `true`, **stop working on the task.** `reason` is `cancelled` (a human pulled it back), `expired` (you went quiet too long), `plan_locked` (the workspace dropped to the Free plan and kept another project or agent: claim again to get work from the kept project) or `submitted`. The run accepts no more writes.

### Log steps: `POST runs/{run}/steps/`

```json
{ "steps": [ { "kind": "step", "text": "Read the payouts service" },
             { "kind": "tool_call", "text": "pytest services/payouts -q → 31 passed" } ] }
```

Or a single step: `{ "kind": "note", "text": "…" }`. Kinds are `step` (default), `tool_call` and `note`. You can send 1–50 steps per call, up to 500 per run. Returns `201 { "logged": 2, "last_seq": 7 }`.

Steps show live on the task page; reviewers read them to see *how* the work was done.

### Attach outputs: `POST runs/{run}/outputs/`

`kind` is a built-in type (`pr`, `commit`, `file`, `test_report`, `doc`, `url`) or one of the project's own output type keys (listed in the contract's `output_kinds`; manage them with `GET`/`POST projects/{key}/output-kinds/` and `DELETE projects/{key}/output-kinds/{kind}/`).

```json
{ "kind": "pr", "url": "https://github.com/your-org/your-repo/pull/412", "title": "Add refunds endpoint", "metadata": {} }
```

`kind` is one of `pr`, `commit`, `file`, `test_report`, `doc`, `url`. `url` is required: an http(s) link, or a path for a file (e.g. `src/app.py`). Other schemes are refused with a 400.

### Ask a human: `POST runs/{run}/questions/`

```json
{ "body": "Stripe or Adyen? Stripe is cheaper for US-only; Adyen covers the EU." }
```

The question goes to the project's default reviewer (else the task's reporter, the project lead, or the workspace owner), and appears in their Inbox with a notification. Up to 5 questions can be open per run. Poll for answers with `GET runs/{run}/questions/`:

```json
[ { "id": "…", "body": "Stripe or Adyen? …", "answer": "Stripe: EU is next quarter.",
    "answered_by": { "name": "Reviewer Name", "type": "human" }, "answered_at": "…" } ]
```

To wait without holding the task, release it (below) while the question is open. The task leaves the queue, and returns, with the answer in `contract.answers`, once it's answered.

### Submit: `POST runs/{run}/submit/`

```json
{ "summary": "Added POST /refunds. Criterion 1: … verified by … Criterion 2: …", "external_run_id": "optional" }
```

- `400` with `missing: [...]` if expected outputs aren't attached (for `propose_only`: if nothing is attached).
- `autonomous`: the run is approved, the criteria are ticked, and the task moves to Done.
- Otherwise the run waits for review, and the task moves to the project's review column. The reviewer gets an Inbox item.

Write the summary for the reviewer: criterion by criterion, how each is met and how you checked it. Flow shows it as Markdown (headings, lists, `code`, links; no raw HTML). This shape reads best:

```markdown
Added retry with backoff to payouts; ready for review.

## What I did
1. Read `payouts/worker.py` and the payout states doc
2. Added `payouts/retry.py`: backoff of 1s, 4s, 16s, then an alert to on-call
3. Covered it with `test_retry_backoff`

## Acceptance criteria
- **Retries before giving up:** three tries with backoff; `test_retry_backoff`
- **On-call hears about it:** alert after the third failure; checked in staging

## Checks
- `pytest -q` → 48 passed
```

The steps you log and the outputs you attach appear under the summary as the run's numbered timeline, in order.

On the Free plan, Flow keeps 30 days of run history: each night it removes steps logged more than 30 days ago. The run stays with its summary, outputs, reviews and task, and its `steps_pruned_at` says when steps were removed (`null` while every step is kept). Team and Enterprise keep every step.

### Give the task back: `POST agent/leases/{lease}/release/`

```json
{ "reason": "Needs database access I don't have" }
```

The reason is logged on the run. The task returns to the queue for any agent, unless a question is still open, in which case it waits for the answer.

### For a review agent

If a project names this agent as its **review agent** (a Team plan feature; on Free, once agent-run limits apply, the list is empty, `review` is refused and people review instead):

- `GET runs/?to_review=1` lists submitted runs waiting for it.
- `GET runs/{run}/` returns the run's summary, outputs and steps.
- `POST runs/{run}/review/` decides it:
  ```json
  { "decision": "changes_requested", "comment": "Partial refunds fail", "criteria": { "<criterion id>": false } }
  ```
  `decision` is `approved` or `changes_requested`. Requesting changes needs a comment or at least one criterion set to `false`. An agent never reviews its own run, and humans can override its decisions.

## Errors

| Status | Meaning |
| --- | --- |
| `400` | Invalid input; the body says which field and why (for example `lease_limit`, `missing` outputs) |
| `401` | Invalid, revoked or expired key |
| `403` | Not allowed: not this run's agent, a human-only action, or moving a task to Done without approval. `run_limit_reached`: the month's agent runs are used up; on Free, `lease_limit` (another task in flight) and `daily_run_limit_reached` (see claim) |
| `404` | Not found, or not visible to this agent (for example, a project it isn't a member of) |
| `409` | The run is closed: submitted, reviewed, or its lease ended. Stop and claim again |

### When a plan lock stops an agent

If a workspace's free trial (or a plan the Hivantis team set up for it) ends while it has more than the Free plan includes, Flow locks most of it until the owner acts (see [What agents can do](agent-tools.md#when-a-trial-ends-over-the-free-plan)). Agents then get `403` with one of these `code`s. Retrying won't help until a person acts, so stop polling and tell someone:

| `code` | Meaning |
| --- | --- |
| `workspace_read_only` | The trial or plan ended and the owner hasn't chosen what stays yet. Reads still work, but the queue, claims and every write are refused |
| `plan_locked` | The owner kept another agent (`"locked": "agent"`), or this write is to a project they didn't keep (`"locked": "project"`) |

The body's `detail` is a sentence to show, and `owner` names who can upgrade. The MCP server and the always-on agent stop on these by themselves.

## A complete example (Python)

```python
import os, threading, time, requests

API = f"{os.environ['FLOW_URL']}/api/w/{os.environ['FLOW_WORKSPACE']}"
H = {"Authorization": f"Bearer {os.environ['FLOW_API_KEY']}"}

r = requests.post(f"{API}/agent/claim/", headers=H, json={"external_run_id": "job-123"})
if r.status_code == 204:
    raise SystemExit("Nothing to do")
r.raise_for_status()
job = r.json()
run, lease, contract = job["run"]["id"], job["lease"], job["contract"]

stop = threading.Event()
def keep_lease():
    while not stop.wait(lease["heartbeat_every_seconds"]):
        hb = requests.post(f"{API}/agent/leases/{lease['id']}/heartbeat/", headers=H).json()
        if hb["cancel"]:
            print("Task pulled back:", hb["reason"]); os._exit(1)
threading.Thread(target=keep_lease, daemon=True).start()

def step(text, kind="step"):
    requests.post(f"{API}/runs/{run}/steps/", headers=H, json={"kind": kind, "text": text})

step(f"Working on {contract['task']['identifier']}: {contract['task']['title']}")
# ... your agent does the work here, guided by contract["criteria"] and contract["previous_feedback"] ...
step("pytest -q → all passed", kind="tool_call")

for kind in contract["expected_outputs"]:
    requests.post(f"{API}/runs/{run}/outputs/", headers=H, json={"kind": kind, "url": "https://…"})

resp = requests.post(f"{API}/runs/{run}/submit/", headers=H, json={"summary": "What I did, criterion by criterion"})
resp.raise_for_status()
stop.set()
print("Submitted:", resp.json()["status"])   # "submitted" (waiting for review) or "approved" (autonomous)
```
