> This page is for version v1 (default).
> For other versions, use one of these documentation indexes:
> - v1 (default): https://docs.rightbrain.ai/v-1/llms.txt

> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.rightbrain.ai/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.rightbrain.ai/_mcp/server.

# Run Task Agent

POST https://app.rightbrain.ai/api/v1/org/{org_id}/project/{project_id}/task-agent/{task_agent_id}/run
Content-Type: application/json

Execute the Task Agent with a user message.

The agent will:

1. Process the message using the configured LLM
2. Reason about which task tools to invoke
3. Execute relevant Tasks as needed
4. Return a streaming response

Send `application/json` for text, correlation fields, and optional base64-encoded
files. Send `multipart/form-data` to upload binary files directly. Both formats
require `message`.

Responses are streamed using Server-Sent Events (SSE).

The first SSE event emitted after successful stream setup is:

* `event_type: "session_id"` with the resolved `session_id` in `metadata`

Use `revision_id` to execute a specific TaskAgent revision. New sessions can run
any revision belonging to the TaskAgent. Existing sessions remain pinned to their
original revision; passing a conflicting `revision_id` is rejected.

Subsequent events include tool calls/results, text responses, metadata-only
`memory_compaction` events when compaction memory runs, and the terminal `done`
or `error` event. Compaction metadata may include token-threshold configuration
such as `trigger: "auto"`, `token_threshold`, and `event_retention_size` when
token-aware compaction is active.

If the model proposes a tool call gated behind `require_approval`, the stream
ends early with an `event_type: "approval_required"` event instead of a
terminal `done`/`error` event. Its `metadata` carries `approval_request_id`,
`tool_type`, `tool_name`, `tool_args_preview`, optional `agent_reason`, and
`expires_at`; the run's status becomes `waiting_for_human` and stays paused
until a human approves or rejects the request (see the approval-request
endpoints) and a caller invokes the resume endpoint. Treat `agent_reason` as
plain untrusted model-authored text.

Example stream for a normal run — the agent classifies the message, looks up
the account in a connected integration, drafts a reply with a Task tool marked
as the output formatter, and completes:

```
data: {"event_type": "session_id", "metadata": {"session_id": "..."}, ...}

data: {"event_type": "tool_call", "tool_name": "customer_support_analyzer", "tool_args": {"message": "..."}, ...}

data: {"event_type": "tool_result", "tool_name": "customer_support_analyzer", "tool_result": {"result": {"sentiment": "concerned", ...}, "task_run_id": "..."}, "tool_outcome": "success", ...}

data: {"event_type": "tool_call", "tool_name": "sheets_spreadsheets_values_get", "tool_args": {"spreadsheet_id": "...", "range": "Customers!A2:F500"}, ...}

data: {"event_type": "tool_result", "tool_name": "sheets_spreadsheets_values_get", "tool_result": {"range": "Customers!A2:F2", "values": [[...]]}, "tool_outcome": "success", ...}

data: {"event_type": "tool_call", "tool_name": "draft_support_reply", "tool_args": {"ticket_summary": "...", "customer_record": {...}}, ...}

data: {"event_type": "formatted_output", "content": "Hi Dana, ...", "tool_outcome": "success", "metadata": {"is_formatter_output": true, "task_run_id": "..."}, ...}

data: {"event_type": "done", "metadata": {"run_id": "...", "session_id": "...", "duration_ms": 9130, "total_tokens": 2250, "used_fallback_model": false, "fallback_model_id": null}, ...}
```

Terminal `done` and `error` SSE events include fallback metadata when a run is
known: `used_fallback_model` and `fallback_model_id`. Terminal `error` events
also include stable `error_code` and `termination_reason` values. Current error
codes are `CONTEXT_WINDOW_EXCEEDED`, `INTEGRATION_NOT_CONNECTED`,
`INTEGRATION_REAUTH_REQUIRED`, `INTEGRATION_AUTH_REQUIRED`,
`UNSUPPORTED_INTEGRATION_TYPE`, `INSUFFICIENT_CREDITS`,
`APPROVAL_CAPTURE_FAILED`, `FORMATTER_FAILED`, `FORMATTER_EMPTY_OUTPUT`,
`TASK_AGENT_NOT_FOUND`, and `EXECUTION_ERROR`.

Reference: https://docs.rightbrain.ai/api-reference/api-reference/agents/run-task-agent

## Authentication

- `Authorization` header (bearer token, required) — API key or access token, sent as `Authorization: Bearer <token>`. The simplest option: create an API key in your dashboard under Settings, then paste it here.

## Servers

- `https://app.rightbrain.ai/api/v1` (Production, default)
- `https://app.rightbrain.ai/api/v1` (Staging API)
- `https://app.rblocal.dev/api/v1` (Local development)

## Request

### Path parameters

- `org_id` (string, required) — The unique identifier of the organization.
- `project_id` (string, required) — The unique identifier of the project.
- `task_agent_id` (string, required) — The specific Task Agent to reference.

### Query parameters

- `revision_id` (string, optional, nullable) — Optional TaskAgent revision ID to use for execution. If omitted, new sessions use the active revision and continuations use the session's pinned revision.

### Body (application/json)

This endpoint expects an object.

- `message` (string, required) — User message to send to the agent.
- `session_id` (string, optional, nullable) — Server-generated session ID from an earlier run. Omit to start a new session.
- `reference` (string, optional, nullable) — Optional reference for external correlation.
- `context_id` (string, optional, nullable) — Optional context ID for grouping runs. The `eval:` prefix is reserved.
- `files` (list of OrgOrgIdProjectProjectIdTaskAgentTaskAgentIdRunPostRequestBodyContentApplicationJsonSchemaFilesItems, optional, nullable) — Optional base64-encoded files.
- `chaos` (OrgOrgIdProjectProjectIdTaskAgentTaskAgentIdRunPostRequestBodyContentApplicationJsonSchemaChaos, optional, nullable) — Optional bounded run-scoped chaos policy.

## Response

### 200

Streaming response

- Streaming response of `string`.

## Errors

### 400 Bad Request Error

Bad Request - Invalid request **Common causes:** - Invalid UUID format in path or query parameters - Missing required fields in the request body - Invalid enum value provided - Type mismatch (e.g., string instead of number) **Resolution:** Check the request body and parameters match the schema.

- `detail` (ErrorResponseDetail, required) — A plain error message, a list of field-level validation errors, a service validation error, or a domain error object with `reason` and `message`.

### 401 Unauthorized Error

Unauthorized - Authentication failed **Common causes:** - Missing `Authorization` header - Expired access token - Invalid or malformed token - Using API key in wrong format **Resolution:** Ensure you're including a valid Bearer token or API key in the Authorization header.

- `detail` (ErrorResponseDetail, required) — A plain error message, a list of field-level validation errors, a service validation error, or a domain error object with `reason` and `message`.

### 403 Forbidden Error

Forbidden - Insufficient permissions for task_agent **Common causes:** - Your role lacks the required permission for this action - The task_agent belongs to a different organization or project - The action requires admin or owner privileges **Resolution:** Contact your organization admin to request appropriate access.

- `RunTaskAgentRequestForbiddenError`
  - PermissionCheckFailedErrorResponse: PermissionCheckFailedErrorResponse
  - MissingAuthenticationErrorResponse: MissingAuthenticationErrorResponse

### 404 Not Found Error

Task Agent not found

- `detail` (ErrorResponseDetail, required) — A plain error message, a list of field-level validation errors, a service validation error, or a domain error object with `reason` and `message`.

### 422 Unprocessable Entity Error

Validation Error

- `detail` (list of ValidationError, optional)

### 500 Internal Server Error

Internal Server Error - Failed to run Task Agent

- `detail` (ErrorResponseDetail, required) — A plain error message, a list of field-level validation errors, a service validation error, or a domain error object with `reason` and `message`.

## Types

### OrgOrgIdProjectProjectIdTaskAgentTaskAgentIdRunPostRequestBodyContentApplicationJsonSchemaFilesItems

- `content` (string, required) — Base64-encoded file content.
- `filename` (string, optional) — Original filename. The server generates one when omitted.

### OrgOrgIdProjectProjectIdTaskAgentTaskAgentIdRunPostRequestBodyContentApplicationJsonSchemaChaos

Optional bounded run-scoped chaos policy.

- `enabled` (boolean, optional, default: true)
- `max_faults` (integer, optional, default: 1)
- `modes` (list of TaskAgentChaosConfigModesItems, optional)
- `run_index` (integer, optional, default: 0)
- `seed` (string, optional, nullable)

### ErrorResponseDetail

A plain error message, a list of field-level validation errors, a service validation error, or a domain error object with `reason` and `message`.

- string
- list of ErrorResponseDetailOneOf1Items
- ErrorResponseDetail2
- ErrorResponseDetail3
- ErrorResponseDetail4

### PermissionCheckFailedErrorResponse

- `detail` (PermissionCheckFailedErrorPayload, required) — The error payload.

### MissingAuthenticationErrorResponse

- `detail` (MissingAuthenticationErrorPayload, required) — The error payload.

### ValidationError

- `loc` (list of ValidationErrorLocItems, required)
- `msg` (string, required)
- `type` (string, required)
- `input` (any, optional)
- `ctx` (ValidationErrorCtx, optional)

### TaskAgentChaosConfigModesItems

- `type`: `model_error` (TaskAgentChaosModelErrorMode)
  - `error` (enum, required)
    - Allowed values: `timeout`, `rate_limit`, `provider_unavailable`, `transient_internal`
  - `probability` (double, required)
- `type`: `tool_error` (TaskAgentChaosToolErrorMode)
  - `probability` (double, required)
  - `retryable` (boolean, optional, default: false)
  - `targets` (TaskAgentChaosTargets, optional, nullable) — Tool targets eligible for a chaos mode.
  - `variant` (enum, optional, nullable)
    - Allowed values: `empty_result`, `missing_fields`, `null_fields`, `unexpected_nesting`, `truncated_result`, `stale_result`
- `type`: `tool_latency` (TaskAgentChaosToolLatencyMode)
  - `latency_ms` (TaskAgentChaosLatencyRange, required) — Bounded per-fault latency injection range.
  - `probability` (double, required)
  - `targets` (TaskAgentChaosTargets, optional, nullable) — Tool targets eligible for a chaos mode.

### ErrorResponseDetailOneOf1Items

- `type` (string, required) — Error type identifier
- `loc` (list of ErrorResponseDetailOneOf1ItemsLocItems, optional) — Path to the error location. Integer segments index into a list.
- `msg` (string, optional) — Human-readable error message. Present on errors produced by FastAPI's own request validation.
- `message` (string, optional) — Human-readable error message. Used instead of `msg` by Rightbrain's own validators.

### ErrorResponseDetail2

Validation error returned by a service after request parsing, such as a Task clone dependency failure.

- `type` ("validation_error", required)
- `errors` (list of ErrorResponseDetailOneOf2ErrorsItems, required)

### ErrorResponseDetail3

Domain error raised via a brain.exc.BaseError subclass. The exact extra field name and shape vary by error type.

- `reason` (string, required) — Machine-readable, upper-snake-case error reason, e.g. RESOURCE_NOT_FOUND, PERMISSION_CHECK_FAILED, TAG_NAME_CONFLICT.
- `message` (string, required) — Human-readable error message

### ErrorResponseDetail4

Integration precondition failure. Uses `code` rather than `reason`, and carries no extra field. Raised by the Gmail trigger routes when the underlying integration is not authorized.

- `code` (string, required) — Machine-readable code, e.g. GMAIL_INTEGRATION_AUTH_REQUIRED.
- `message` (string, required) — Human-readable error message

### PermissionCheckFailedErrorPayload

- `message` (string, required) — Human readable representation of the error
- `reason` (enum, required) — The machine-readable error reason.
  - Allowed values: `PERMISSION_CHECK_FAILED`
- `permissionCheckFailedError` (PermissionCheckFailedErrorDetails, required) — Metadata detailing more information about the error.

### MissingAuthenticationErrorPayload

- `message` (string, required) — Human readable representation of the error
- `reason` (enum, required) — The machine-readable error reason.
  - Allowed values: `MISSING_AUTHENTICATION`
- `missingAuthenticationError` (EmptyErrorDetails, required) — Metadata detailing more information about the error.

### ValidationErrorLocItems

- string
- integer

### ValidationErrorCtx

### TaskAgentChaosTargets

Tool targets eligible for a chaos mode.

- `tool_names` (list of string, optional, nullable)
- `sources` (list of enum, optional, nullable)
  - Allowed values: `task`, `mcp`, `integration`, `registered_tool`

### TaskAgentChaosLatencyRange

Bounded per-fault latency injection range.

- `min` (integer, required)
- `max` (integer, required)

### ErrorResponseDetailOneOf1ItemsLocItems

- string
- integer

### ErrorResponseDetailOneOf2ErrorsItems

- `type` (string, required) — Error type identifier
- `loc` (list of ErrorResponseDetailOneOf2ErrorsItemsLocItems, optional) — Path to the error location. Integer segments index into a list.
- `msg` (string, optional) — Human-readable error message. Present on errors produced by FastAPI's own request validation.
- `message` (string, optional) — Human-readable error message. Used instead of `msg` by Rightbrain's own validators.

### PermissionCheckFailedErrorDetails

- `permission` (string, required)
- `subject` (IAMObjectErrorDetails, optional, nullable)
- `resource` (IAMObjectErrorDetails, optional, nullable)

### EmptyErrorDetails

### ErrorResponseDetailOneOf2ErrorsItemsLocItems

- string
- integer

### IAMObjectErrorDetails

- `type` (string, required)
- `id` (string, optional, nullable)

## Examples

### Auto-run tools only: classify, look up the account, draft the reply, done

**Request**

```json
{
  "message": "Subject: Charged twice for June invoice\n\nHi, I think we've been billed twice for our June bookkeeping retainer — I can see two charges of £450 on the 3rd and the 5th. Could someone check our account and let me know what's going on? Our account email is dana@northfieldjoinery.co.uk.\n\nThanks,\nDana"
}
```

**SDK Code**

```python Auto-run tools only: classify, look up the account, draft the reply, done
import json
import os
import httpx


def read_agent_stream(response):
    response.raise_for_status()
    if "text/event-stream" not in response.headers.get("content-type", ""):
        raise RuntimeError("Expected a text/event-stream response")

    session_id = None
    data = []
    for line in response.iter_lines():
        if line.startswith("data:"):
            data.append(line[5:].removeprefix(" "))
        elif line == "" and data:
            event = json.loads("\n".join(data))
            data = []
            kind = event["event_type"]
            if kind == "session_id":
                session_id = event["metadata"]["session_id"]
            elif kind == "text":
                print(event.get("content") or "", end="", flush=True)
            elif kind == "formatted_output":
                print("\nStructured output:", event.get("content"))
            elif kind == "error":
                raise RuntimeError(f"Agent run failed: {event.get('error')}")
            elif kind in ("done", "approval_required"):
                return {
                    "status": "completed" if kind == "done" else "waiting_for_human",
                    "session_id": session_id,
                    "metadata": event.get("metadata"),
                }
            elif kind in ("tool_call", "tool_result"):
                print("\nTool event:", event)
            # Ignore unknown event types so new events remain compatible.

    raise RuntimeError("Stream ended without done or approval_required; inspect the run before retrying")


base = f"https://app.rightbrain.ai/api/v1/org/{os.environ['RB_ORG']}/project/{os.environ['RB_PROJECT']}"
url = f"{base}/task-agent/{os.environ['RB_AGENT']}/run"
headers = {
    "Authorization": f"Bearer {os.environ['RB_TOKEN']}",
    "Accept": "text/event-stream",
}
payload = {"message": "Triage this review: My toaster exploded during breakfast and set the bread on fire."}

with httpx.stream("POST", url, headers=headers, json=payload, timeout=None) as response:
    outcome = read_agent_stream(response)
    print("\nOutcome:", outcome)
```

```typescript Auto-run tools only: classify, look up the account, draft the reply, done
async function readAgentStream(response: Response) {
  if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
  if (!response.headers.get("content-type")?.includes("text/event-stream") || !response.body) {
    throw new Error("Expected a text/event-stream response");
  }

  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  let buffer = "";
  let data: string[] = [];
  let sessionId: string | undefined;

  try {
    while (true) {
      const { value, done } = await reader.read();
      buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });
      let newline: number;
      while ((newline = buffer.indexOf("\n")) !== -1) {
        const line = buffer.slice(0, newline).replace(/\r$/, "");
        buffer = buffer.slice(newline + 1);
        if (line.startsWith("data:")) {
          data.push(line.slice(5).replace(/^ /, ""));
        } else if (line === "" && data.length) {
          const event = JSON.parse(data.join("\n"));
          data = [];
          switch (event.event_type) {
            case "session_id":
              sessionId = event.metadata.session_id;
              break;
            case "text":
              process.stdout.write(event.content ?? "");
              break;
            case "formatted_output":
              console.log("\nStructured output:", event.content);
              break;
            case "error":
              throw new Error(`Agent run failed: ${event.error}`);
            case "done":
            case "approval_required":
              return {
                status: event.event_type === "done" ? "completed" : "waiting_for_human",
                sessionId,
                metadata: event.metadata,
              };
            case "tool_call":
            case "tool_result":
              console.log("\nTool event:", event);
              break;
            // Ignore unknown event types so new events remain compatible.
          }
        }
      }
      if (done) throw new Error("Stream ended without done or approval_required; inspect the run before retrying");
    }
  } finally {
    await reader.cancel().catch(() => {});
    reader.releaseLock();
  }
}

const base = `https://app.rightbrain.ai/api/v1/org/${process.env.RB_ORG}/project/${process.env.RB_PROJECT}`;
const response = await fetch(`${base}/task-agent/${process.env.RB_AGENT}/run`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.RB_TOKEN}`,
    "Content-Type": "application/json",
    Accept: "text/event-stream",
  },
  body: JSON.stringify({
    message: "Triage this review: My toaster exploded during breakfast and set the bread on fire.",
  }),
});
const outcome = await readAgentStream(response);
console.log("\nOutcome:", outcome);
```

```go Auto-run tools only: classify, look up the account, draft the reply, done
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://app.rightbrain.ai/api/v1/org/org_id/project/project_id/task-agent/task_agent_id/run"

	payload := strings.NewReader("{\n  \"message\": \"Subject: Charged twice for June invoice\\n\\nHi, I think we've been billed twice for our June bookkeeping retainer — I can see two charges of £450 on the 3rd and the 5th. Could someone check our account and let me know what's going on? Our account email is dana@northfieldjoinery.co.uk.\\n\\nThanks,\\nDana\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby Auto-run tools only: classify, look up the account, draft the reply, done
require 'uri'
require 'net/http'

url = URI("https://app.rightbrain.ai/api/v1/org/org_id/project/project_id/task-agent/task_agent_id/run")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"message\": \"Subject: Charged twice for June invoice\\n\\nHi, I think we've been billed twice for our June bookkeeping retainer — I can see two charges of £450 on the 3rd and the 5th. Could someone check our account and let me know what's going on? Our account email is dana@northfieldjoinery.co.uk.\\n\\nThanks,\\nDana\"\n}"

response = http.request(request)
puts response.read_body
```

```java Auto-run tools only: classify, look up the account, draft the reply, done
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://app.rightbrain.ai/api/v1/org/org_id/project/project_id/task-agent/task_agent_id/run")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"message\": \"Subject: Charged twice for June invoice\\n\\nHi, I think we've been billed twice for our June bookkeeping retainer — I can see two charges of £450 on the 3rd and the 5th. Could someone check our account and let me know what's going on? Our account email is dana@northfieldjoinery.co.uk.\\n\\nThanks,\\nDana\"\n}")
  .asString();
```

```php Auto-run tools only: classify, look up the account, draft the reply, done
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://app.rightbrain.ai/api/v1/org/org_id/project/project_id/task-agent/task_agent_id/run', [
  'body' => '{
  "message": "Subject: Charged twice for June invoice\\n\\nHi, I think we\'ve been billed twice for our June bookkeeping retainer — I can see two charges of £450 on the 3rd and the 5th. Could someone check our account and let me know what\'s going on? Our account email is dana@northfieldjoinery.co.uk.\\n\\nThanks,\\nDana"
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp Auto-run tools only: classify, look up the account, draft the reply, done
using RestSharp;

var client = new RestClient("https://app.rightbrain.ai/api/v1/org/org_id/project/project_id/task-agent/task_agent_id/run");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"message\": \"Subject: Charged twice for June invoice\\n\\nHi, I think we've been billed twice for our June bookkeeping retainer — I can see two charges of £450 on the 3rd and the 5th. Could someone check our account and let me know what's going on? Our account email is dana@northfieldjoinery.co.uk.\\n\\nThanks,\\nDana\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift Auto-run tools only: classify, look up the account, draft the reply, done
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = ["message": "Subject: Charged twice for June invoice

Hi, I think we've been billed twice for our June bookkeeping retainer — I can see two charges of £450 on the 3rd and the 5th. Could someone check our account and let me know what's going on? Our account email is dana@northfieldjoinery.co.uk.

Thanks,
Dana"] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://app.rightbrain.ai/api/v1/org/org_id/project/project_id/task-agent/task_agent_id/run")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```

### Stream ends early because the next tool call requires human approval

**Request**

```json
{
  "message": "Refund the duplicate charge on invoice INV-1042."
}
```

**SDK Code**

```python Stream ends early because the next tool call requires human approval
import json
import os
import httpx


def read_agent_stream(response):
    response.raise_for_status()
    if "text/event-stream" not in response.headers.get("content-type", ""):
        raise RuntimeError("Expected a text/event-stream response")

    session_id = None
    data = []
    for line in response.iter_lines():
        if line.startswith("data:"):
            data.append(line[5:].removeprefix(" "))
        elif line == "" and data:
            event = json.loads("\n".join(data))
            data = []
            kind = event["event_type"]
            if kind == "session_id":
                session_id = event["metadata"]["session_id"]
            elif kind == "text":
                print(event.get("content") or "", end="", flush=True)
            elif kind == "formatted_output":
                print("\nStructured output:", event.get("content"))
            elif kind == "error":
                raise RuntimeError(f"Agent run failed: {event.get('error')}")
            elif kind in ("done", "approval_required"):
                return {
                    "status": "completed" if kind == "done" else "waiting_for_human",
                    "session_id": session_id,
                    "metadata": event.get("metadata"),
                }
            elif kind in ("tool_call", "tool_result"):
                print("\nTool event:", event)
            # Ignore unknown event types so new events remain compatible.

    raise RuntimeError("Stream ended without done or approval_required; inspect the run before retrying")


base = f"https://app.rightbrain.ai/api/v1/org/{os.environ['RB_ORG']}/project/{os.environ['RB_PROJECT']}"
url = f"{base}/task-agent/{os.environ['RB_AGENT']}/run"
headers = {
    "Authorization": f"Bearer {os.environ['RB_TOKEN']}",
    "Accept": "text/event-stream",
}
payload = {"message": "Triage this review: My toaster exploded during breakfast and set the bread on fire."}

with httpx.stream("POST", url, headers=headers, json=payload, timeout=None) as response:
    outcome = read_agent_stream(response)
    print("\nOutcome:", outcome)
```

```typescript Stream ends early because the next tool call requires human approval
async function readAgentStream(response: Response) {
  if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
  if (!response.headers.get("content-type")?.includes("text/event-stream") || !response.body) {
    throw new Error("Expected a text/event-stream response");
  }

  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  let buffer = "";
  let data: string[] = [];
  let sessionId: string | undefined;

  try {
    while (true) {
      const { value, done } = await reader.read();
      buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });
      let newline: number;
      while ((newline = buffer.indexOf("\n")) !== -1) {
        const line = buffer.slice(0, newline).replace(/\r$/, "");
        buffer = buffer.slice(newline + 1);
        if (line.startsWith("data:")) {
          data.push(line.slice(5).replace(/^ /, ""));
        } else if (line === "" && data.length) {
          const event = JSON.parse(data.join("\n"));
          data = [];
          switch (event.event_type) {
            case "session_id":
              sessionId = event.metadata.session_id;
              break;
            case "text":
              process.stdout.write(event.content ?? "");
              break;
            case "formatted_output":
              console.log("\nStructured output:", event.content);
              break;
            case "error":
              throw new Error(`Agent run failed: ${event.error}`);
            case "done":
            case "approval_required":
              return {
                status: event.event_type === "done" ? "completed" : "waiting_for_human",
                sessionId,
                metadata: event.metadata,
              };
            case "tool_call":
            case "tool_result":
              console.log("\nTool event:", event);
              break;
            // Ignore unknown event types so new events remain compatible.
          }
        }
      }
      if (done) throw new Error("Stream ended without done or approval_required; inspect the run before retrying");
    }
  } finally {
    await reader.cancel().catch(() => {});
    reader.releaseLock();
  }
}

const base = `https://app.rightbrain.ai/api/v1/org/${process.env.RB_ORG}/project/${process.env.RB_PROJECT}`;
const response = await fetch(`${base}/task-agent/${process.env.RB_AGENT}/run`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.RB_TOKEN}`,
    "Content-Type": "application/json",
    Accept: "text/event-stream",
  },
  body: JSON.stringify({
    message: "Triage this review: My toaster exploded during breakfast and set the bread on fire.",
  }),
});
const outcome = await readAgentStream(response);
console.log("\nOutcome:", outcome);
```

```go Stream ends early because the next tool call requires human approval
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://app.rightbrain.ai/api/v1/org/org_id/project/project_id/task-agent/task_agent_id/run"

	payload := strings.NewReader("{\n  \"message\": \"Refund the duplicate charge on invoice INV-1042.\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby Stream ends early because the next tool call requires human approval
require 'uri'
require 'net/http'

url = URI("https://app.rightbrain.ai/api/v1/org/org_id/project/project_id/task-agent/task_agent_id/run")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"message\": \"Refund the duplicate charge on invoice INV-1042.\"\n}"

response = http.request(request)
puts response.read_body
```

```java Stream ends early because the next tool call requires human approval
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://app.rightbrain.ai/api/v1/org/org_id/project/project_id/task-agent/task_agent_id/run")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"message\": \"Refund the duplicate charge on invoice INV-1042.\"\n}")
  .asString();
```

```php Stream ends early because the next tool call requires human approval
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://app.rightbrain.ai/api/v1/org/org_id/project/project_id/task-agent/task_agent_id/run', [
  'body' => '{
  "message": "Refund the duplicate charge on invoice INV-1042."
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp Stream ends early because the next tool call requires human approval
using RestSharp;

var client = new RestClient("https://app.rightbrain.ai/api/v1/org/org_id/project/project_id/task-agent/task_agent_id/run");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"message\": \"Refund the duplicate charge on invoice INV-1042.\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift Stream ends early because the next tool call requires human approval
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = ["message": "Refund the duplicate charge on invoice INV-1042."] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://app.rightbrain.ai/api/v1/org/org_id/project/project_id/task-agent/task_agent_id/run")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```