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

# Execute Agent

> Directly execute a research agent

# Execute Agent

Execute a research agent. The request blocks until the agent finishes execution (synchronous).

<Warning>
  **Client timeout caveat.** This endpoint holds the HTTP connection until `executeAgentRun`
  completes all of LLM inference, tool invocations (browsing/search), RAG, and graph
  extraction. Typical runs take **10 seconds to several minutes** depending on the task.

  If the client times out (default 30–120s in most HTTP libraries), the connection is
  dropped — **but the server keeps running** and the result is persisted to chat history,
  not returned to the caller. You can recover it later via [`GET /turn/list`](/en/api-reference/list-turns).

  **Recommendation**: use [Execute Agent (Streaming)](/en/api-reference/stream-agent-run) for
  anything beyond trivial Q\&A. SSE returns the `runId` immediately in the first event and
  can be resumed with `/agent/run/stream/{runId}` if the connection drops. If you must use
  this non-streaming endpoint, set your client timeout to **at least 300 seconds**.
</Warning>

## Request

```
POST /api/v1/agent/run
```

### Headers

| Header          | Required | Description                           |
| --------------- | -------- | ------------------------------------- |
| `Authorization` | Yes      | API key in `Bearer snorbe_...` format |
| `Content-Type`  | Yes      | `application/json`                    |

### Request Body

```json theme={null}
{
  "modelName": "gpt-5-mini-2025-08-07",
  "inputText": "Research the latest semiconductor trends",
  "promptKey": "chat-routing",
  "locale": "en",
  "fileUrls": []
}
```

### Parameters

| Parameter                | Type        | Required | Description                                                                                                                                                                                              |
| ------------------------ | ----------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `modelName`              | `string`    | Yes      | Model name                                                                                                                                                                                               |
| `inputText`              | `string`    | Yes      | Input text for the agent                                                                                                                                                                                 |
| `promptKey`              | `string`    | Yes      | Prompt key (typically `"chat-routing"`)                                                                                                                                                                  |
| `locale`                 | `string`    | Yes      | `"ja"` or `"en"`                                                                                                                                                                                         |
| `fileUrls`               | `string[]`  | No       | Attached file URLs (max 10). Default: `[]`                                                                                                                                                               |
| `agentId`                | `string`    | No       | Agent ID. Defaults to the default agent                                                                                                                                                                  |
| `mentions`               | `Mention[]` | No       | @mention references (entities, agent runs, sources, **other Agents**). Default: `[]`. Including `type: "agent"` lets the target Agent delegate via `mentionAgent`. See "Agent-to-Agent delegation" below |
| `maxBrowsingSteps`       | `number`    | No       | Max browsing steps (1-100)                                                                                                                                                                               |
| `maxChainSteps`          | `number`    | No       | Maximum depth of Agent-to-Agent mention chains (1-50, default 10). Recursive `mentionAgent` fan-outs are capped at this value                                                                            |
| `maxRetries`             | `number`    | No       | Retry count (0-5)                                                                                                                                                                                        |
| `retryDelayMs`           | `number`    | No       | Retry delay in ms (0-10000)                                                                                                                                                                              |
| `includeOthersEntities`  | `boolean`   | No       | Include other users' entities in RAG search. Default: `true`                                                                                                                                             |
| `extendedContextEnabled` | `boolean`   | No       | Extended context (uses 80% of model max tokens). Default: `false`                                                                                                                                        |
| `matrixEditContext`      | `object`    | No       | Matrix edit context (`sourceRunId` + `selection`)                                                                                                                                                        |
| `matrixContinueContext`  | `object`    | No       | Matrix continue context (`sourceRunId`)                                                                                                                                                                  |
| `matrixSelectionContent` | `string`    | No       | Matrix selection XML (`<matrix_selection>` format)                                                                                                                                                       |

<Note>
  `workspaceId` is not required. It is automatically resolved from the API key.
</Note>

## Response

```json theme={null}
{
  "text": "Research results...",
  "finishReason": "stop",
  "model": {
    "id": "gpt-5-mini-2025-08-07",
    "provider": "openai"
  },
  "runId": "clxyz...",
  "status": "completed",
  "assistantTurnId": "clxyz...",
  "agentId": "clxyz...",
  "agentName": "agent"
}
```

### Response Fields

| Field          | Type     | Description                                       |
| -------------- | -------- | ------------------------------------------------- |
| `text`         | `string` | Agent response text                               |
| `finishReason` | `string` | Finish reason (`"stop"`, `"tool-calls"`, etc.)    |
| `model`        | `object` | Model information used                            |
| `runId`        | `string` | Agent run ID                                      |
| `status`       | `string` | Execution status (`"completed"`, `"error"`, etc.) |

## Examples

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://app.snorbe.deskrex.ai/api/v1/agent/run" \
    -H "Authorization: Bearer snorbe_your_api_key_here" \
    -H "Content-Type: application/json" \
    -d '{
      "modelName": "gpt-5-mini-2025-08-07",
      "inputText": "Research the latest semiconductor trends",
      "promptKey": "chat-routing",
      "locale": "en"
    }'
  ```

  ```python Python theme={null}
  import requests

  # Set a generous timeout — agent runs with tools/RAG/graph extraction
  # regularly take several minutes. If you hit the client timeout, the server
  # still finishes; recover the result via GET /turn/list.
  resp = requests.post(
      "https://app.snorbe.deskrex.ai/api/v1/agent/run",
      headers={
          "Authorization": "Bearer snorbe_your_api_key_here",
          "Content-Type": "application/json",
      },
      json={
          "modelName": "gpt-5-mini-2025-08-07",
          "inputText": "Research the latest semiconductor trends",
          "promptKey": "chat-routing",
          "locale": "en",
      },
      timeout=600,
  )
  data = resp.json()
  print(data["text"])
  print(f"Run ID: {data['runId']}")
  ```

  ```typescript TypeScript theme={null}
  const resp = await fetch("https://app.snorbe.deskrex.ai/api/v1/agent/run", {
    method: "POST",
    headers: {
      Authorization: "Bearer snorbe_your_api_key_here",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      modelName: "gpt-5-mini-2025-08-07",
      inputText: "Research the latest semiconductor trends",
      promptKey: "chat-routing",
      locale: "en",
    }),
  });
  const data = await resp.json();
  console.log(data.text);
  console.log(`Run ID: ${data.runId}`);
  ```
</CodeGroup>

## Retrieving detailed run data after completion

`GET /agent/run/{runId}/status` is lightweight — it returns only `status` and
`pending*Draft` flags. **To recover full run details (browse steps, tool calls, plan
and report and matrix drafts, graph extraction events, referenced sources), use
[`GET /turn/list`](/en/api-reference/list-turns)**.

Each turn entry includes:

* `agentRun.process` — the persisted timeline of every SSE event emitted during the
  run (`config`, `delta`, `step`, `browse-*`, `plan-*`, `report-structure-*`, `matrix-*`,
  `source-summary-*`, `graph-*`)
* `agentRun.publicSourceAgentRuns` / `privateSourceAgentRuns` — URL sources the
  agent referenced, including `bodyLinks` metadata
* `agentRun.agent` — agent metadata

There is no direct `GET /agent/run/{runId}` endpoint. To find a specific `runId`,
paginate `/turn/list` (newest first) and match `turns[].agentRun.id`.

## Agent-to-Agent delegation

Including `type: "agent"` entries in `mentions` lets the target Agent delegate to mentioned peers mid-run.

### Single target

```json theme={null}
{
  "inputText": "Ask [agent-beta](agent://b-id) for their favorite color in one word",
  "mentions": [
    { "id": "b-id", "type": "agent", "label": "agent-beta" }
  ]
}
```

What happens:

1. The initial Agent (e.g. agent-alpha) starts its run
2. Its LLM selects the `mentionAgent` tool and writes a final message like `[@agent-beta](agent://b-id) favorite color in one word`
3. After alpha completes, the server automatically starts a new AgentRun for agent-beta, using alpha's final message as input
4. beta runs independently and its reply is persisted to chat history

The response `runId` is for the **parent run (alpha) only**. To retrieve child runs, use `/turn/list` or `/agent/run/{childRunId}/status`.

### Multiple targets

When two or more agents are mentioned, a server-side LLM classifier decides `parallel` vs `chain` from the message intent.

* **parallel** (independent opinions): all mentioned agents run concurrently. Example: "Ask A and B for their **independent** opinions"
* **chain** (sequential): the primary agent runs first and chains to the others via `mentionAgent`. Example: "A drafts a plan, then B reviews it"

### Guards

* **Self-loop prevention**: targets that match the caller's own agentId are skipped
* **Depth limit**: `maxChainSteps` (1-50, default 10) caps recursive `mentionAgent` fan-outs
* **Error isolation**: one child's failure does not block other siblings from spawning

## Error Responses

| HTTP Status | Code                    | Description           |
| ----------- | ----------------------- | --------------------- |
| 400         | `BAD_REQUEST`           | Validation error      |
| 401         | `UNAUTHORIZED`          | Invalid API key       |
| 429         | `TOO_MANY_REQUESTS`     | Rate limit exceeded   |
| 500         | `INTERNAL_SERVER_ERROR` | Agent execution error |
