> For the complete documentation index, see [llms.txt](https://hallway.gitbook.io/embed/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hallway.gitbook.io/embed/cloud-agent-api/run-a-task.md). Agents can also search and read this documentation through its [MCP server](https://hallway.gitbook.io/embed/~gitbook/mcp).

# Run a Task

Send a task to your cloud agent and stream back its progress and answer.

```http
POST https://hallway.ai/api/v1/agent/run
```

## Request

### Headers

| Header          | Value                 |
| --------------- | --------------------- |
| `Authorization` | `Bearer YOUR_API_KEY` |
| `Content-Type`  | `application/json`    |

### Body

| Field          | Type   | Required | Description                                                                                                                                                                       |
| -------------- | ------ | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `task`         | string | Yes      | What you want the agent to do, in plain language. Up to 20,000 characters.                                                                                                        |
| `sessionId`    | string | No       | Continue an existing conversation. Leave it out to start a new one.                                                                                                               |
| `model`        | string | No       | Model for the run: `gemini-3.8-flash` (default), `gemini-4-hydrogen`, or `gemini-3.5-flash-lite`.                                                                                 |
| `browser`      | object | No       | Run in a browser you host instead of your Hallway browser. See [Bring Your Own Browser](https://hallway.gitbook.io/embed/cloud-agent-api/bring-your-own-browser.md).              |
| `resultSchema` | object | No       | A JSON Schema for the result. The run returns `result` as JSON that matches it. See [Structured Results](https://hallway.gitbook.io/embed/cloud-agent-api/structured-results.md). |

Other fields are rejected with a `400` error.

### Example

{% tabs %}
{% tab title="cURL" %}

```bash
curl -N "https://hallway.ai/api/v1/agent/run" \
  -H "Authorization: Bearer $HALLWAY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"task":"Summarize the page in my browser"}'
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const response = await fetch("https://hallway.ai/api/v1/agent/run", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.HALLWAY_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ task: "Summarize the page in my browser" }),
});

if (!response.ok) throw new Error((await response.json()).error);

const sessionId = response.headers.get("X-Hallway-Session");

const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
let buffer = "";
while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  buffer += value;
  const lines = buffer.split("\n");
  buffer = lines.pop();
  for (const line of lines) {
    if (!line.trim()) continue;
    const event = JSON.parse(line);
    if (event.type === "text.delta") process.stdout.write(event.text);
    if (event.type === "run.completed") {
      if (event.status === "completed") console.log("\nAnswer:", event.answer);
      else console.error(`\nRun ${event.status}:`, event.error?.message ?? event.reason);
    }
  }
}
```

{% endtab %}

{% tab title="Python" %}

```python
import json
import os
import requests

response = requests.post(
    "https://hallway.ai/api/v1/agent/run",
    headers={"Authorization": f"Bearer {os.environ['HALLWAY_API_KEY']}"},
    json={"task": "Summarize the page in my browser"},
    stream=True,
    timeout=800,
)
response.raise_for_status()

session_id = response.headers["X-Hallway-Session"]

for line in response.iter_lines(decode_unicode=True):
    if not line:
        continue
    event = json.loads(line)
    if event["type"] == "text.delta":
        print(event["text"], end="", flush=True)
    elif event["type"] == "run.completed":
        if event["status"] == "completed":
            print("\nAnswer:", event["answer"])
        else:
            print(f"\nRun {event['status']}:", (event.get("error") or {}).get("message") or event.get("reason"))
```

{% endtab %}
{% endtabs %}

## Response

The response streams back as [newline-delimited JSON](https://github.com/ndjson/ndjson-spec): one JSON event per line, sent as the agent works. Read it line by line rather than waiting for one JSON document.

The `X-Hallway-Session` response header holds the conversation ID. Send it as `sessionId` to continue the conversation.

### Events

Each event has a `type`. There are four:

| Type            | Fields                                                        | Description                                                                                               |
| --------------- | ------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
| `status`        | `status`                                                      | What the agent is doing: `starting`, `waiting_for_browser`, `working`, or `saving`. Sent when it changes. |
| `step`          | `action`                                                      | An action the agent took, like `Clicking: Submit` or `Navigating: example.com`.                           |
| `text.delta`    | `text`                                                        | A piece of the answer, streamed as it's written.                                                          |
| `run.completed` | `status`, `answer`, and sometimes `result`, `reason`, `error` | How the run ended. Always the last event, sent exactly once.                                              |

#### `run.completed`

| Field    | Description                                                                                                                                                                        |
| -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `status` | `completed`, `failed`, `stopped`, or `incomplete`.                                                                                                                                 |
| `answer` | The agent's answer as text. It may be partial if the run didn't complete.                                                                                                          |
| `result` | The structured result, when you sent `resultSchema` and `status` is `completed`. See [Structured Results](https://hallway.gitbook.io/embed/cloud-agent-api/structured-results.md). |
| `reason` | Why a `stopped` or `incomplete` run ended: `user` (someone stopped it), `max_steps` (it hit its step limit), or `credits_exhausted` (your team ran out of credits).                |
| `error`  | For `failed` runs: `{ "code", "message" }`. See [Errors during a task](https://hallway.gitbook.io/embed/cloud-agent-api/errors-and-limits.md#errors-during-a-task).                |

Example stream:

```json
{"type":"status","status":"starting"}
{"type":"status","status":"working"}
{"type":"step","action":"Reading page"}
{"type":"text.delta","text":"Here is "}
{"type":"text.delta","text":"the summary."}
{"type":"status","status":"saving"}
{"type":"run.completed","status":"completed","answer":"Here is the summary."}
```

{% hint style="warning" %}
A `200` status only means the task started. Check `run.completed.status` to know whether the task succeeded. Only `completed` means it finished.
{% endhint %}

## Continue a conversation

To ask a follow-up, send the `sessionId` from the first response:

```bash
curl -N "https://hallway.ai/api/v1/agent/run" \
  -H "Authorization: Bearer $HALLWAY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"task":"Give me more detail","sessionId":"SESSION_ID"}'
```

The agent remembers earlier messages in the conversation. You can also continue conversations your team started on the Cloud Agent page.

If the conversation uses your own browser, send `browser` again with each follow-up. See [Follow-ups](https://hallway.gitbook.io/embed/cloud-agent-api/bring-your-own-browser.md#follow-ups).

{% hint style="info" %}
If the connection drops, don't resend the task automatically. The agent may have already finished it. Check the conversation with [Read a Conversation](https://hallway.gitbook.io/embed/cloud-agent-api/read-a-conversation.md) first.
{% endhint %}
