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

# Cancel Task

> Cancel a running task or rename a task's chat title. Use action: 'cancel' to stop execution.

This endpoint allows you to cancel a running task or rename its chat title. When cancelling, the agent process is terminated and the run status is updated to `cancelled`.

## Authentication

To use this API, you need a BLACKBOX API Key. Follow these steps to get your API key:

1. Go to [app.blackbox.ai/agent-api](https://app.blackbox.ai/agent-api) and click **Get an API Key** (requires a Pro subscription)
2. Once provisioning completes, you will be redirected to your [Dashboard](https://app.blackbox.ai/dashboard)
3. From the Dashboard, create an API key to use with all Agent API requests

Your API key will be in the format: `sk-xxxxxxxxxxxxxxxxxxxxxx`

## Headers

<ParamField header="Authorization" type="string" required>
  API Key of the form `Bearer <api_key>`.

  Example: `Bearer sk_b41b647ffbfed27f616560`
</ParamField>

<ParamField header="Content-Type" type="string" required>
  Must be set to `application/json`.
</ParamField>

## Path Parameters

<ParamField path="runId" type="string" required>
  The unique run identifier of the task to cancel or update.

  Example: `a1b2c3d4-e5f6-7890-abcd-ef1234567890`
</ParamField>

## Request Body

<ParamField body="action" type="string">
  Action to perform. Use `"cancel"` to stop the running task.

  Must be `"cancel"` when provided.
</ParamField>

<ParamField body="title" type="string">
  New title for the task's chat thread. Length: 1–200 characters.

  Example: `"Stripe Integration Task"`
</ParamField>

<Note>
  You must provide either `action: "cancel"` or a `title`. Providing both is allowed — the cancel takes precedence.
</Note>

## Response Fields

<ResponseField name="success" type="boolean">
  Whether the operation succeeded.
</ResponseField>

<ResponseField name="status" type="string">
  The current status of the run after the operation.
</ResponseField>

<ResponseField name="message" type="string">
  Human-readable description of the result.
</ResponseField>

<RequestExample>
  ```bash Cancel Task theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
  curl -X PATCH 'https://agent.blackbox.ai/api/v1/tasks/a1b2c3d4-e5f6-7890-abcd-ef1234567890' \
    -H 'Authorization: Bearer YOUR_API_KEY' \
    -H 'Content-Type: application/json' \
    -d '{ "action": "cancel" }'
  ```

  ```bash Rename Task theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
  curl -X PATCH 'https://agent.blackbox.ai/api/v1/tasks/a1b2c3d4-e5f6-7890-abcd-ef1234567890' \
    -H 'Authorization: Bearer YOUR_API_KEY' \
    -H 'Content-Type: application/json' \
    -d '{ "title": "Stripe Integration Task" }'
  ```

  ```javascript Node.js theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
  const API_KEY = "YOUR_API_KEY";
  const RUN_ID = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";

  const response = await fetch(
    `https://agent.blackbox.ai/api/v1/tasks/${RUN_ID}`,
    {
      method: "PATCH",
      headers: {
        Authorization: `Bearer ${API_KEY}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ action: "cancel" }),
    }
  );

  const data = await response.json();
  console.log(data.message);
  console.log(`Status: ${data.status}`);
  ```

  ```python Python theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
  import requests

  API_KEY = "YOUR_API_KEY"
  RUN_ID = "a1b2c3d4-e5f6-7890-abcd-ef1234567890"

  response = requests.patch(
      f"https://agent.blackbox.ai/api/v1/tasks/{RUN_ID}",
      headers={
          "Authorization": f"Bearer {API_KEY}",
          "Content-Type": "application/json",
      },
      json={"action": "cancel"},
  )
  data = response.json()
  print(data["message"])
  print(f"Status: {data['status']}")
  ```

  ```go Go theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
  package main

  import (
      "bytes"
      "encoding/json"
      "fmt"
      "io"
      "net/http"
  )

  func main() {
      apiKey := "YOUR_API_KEY"
      runId := "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
      url := fmt.Sprintf("https://agent.blackbox.ai/api/v1/tasks/%s", runId)

      body, _ := json.Marshal(map[string]string{"action": "cancel"})

      req, _ := http.NewRequest("PATCH", url, bytes.NewBuffer(body))
      req.Header.Set("Authorization", "Bearer "+apiKey)
      req.Header.Set("Content-Type", "application/json")

      client := &http.Client{}
      resp, _ := client.Do(req)
      defer resp.Body.Close()

      respBody, _ := io.ReadAll(resp.Body)
      fmt.Println(string(respBody))
  }
  ```
</RequestExample>

<ResponseExample>
  ```json Cancel Success theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
  {
    "success": true,
    "status": "cancelled",
    "message": "Task a1b2c3d4-e5f6-7890-abcd-ef1234567890 cancelled successfully"
  }
  ```

  ```json Cancel - Already Completed theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
  {
    "success": false,
    "status": "completed",
    "message": "Task is not in a cancellable state (already completed, failed, or not found)"
  }
  ```

  ```json Rename Success theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
  {
    "success": true,
    "status": "completed",
    "message": "Task title updated"
  }
  ```

  ```json Error - Not Found theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
  {
    "error": "Task not found"
  }
  ```

  ```json Error - No Action theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
  {
    "error": "No valid action provided. Use action: 'cancel' or provide a title."
  }
  ```
</ResponseExample>

## Use Cases

### Cancel with Timeout Guard

```javascript theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
async function runWithTimeout(runId, apiKey, timeoutMs = 300_000) {
  const statusUrl = `https://agent.blackbox.ai/api/v1/tasks/${runId}/status`;
  const cancelUrl = `https://agent.blackbox.ai/api/v1/tasks/${runId}`;
  const DONE = ["completed", "failed", "cancelled", "interrupted"];
  const headers = { Authorization: `Bearer ${apiKey}` };

  const deadline = Date.now() + timeoutMs;

  while (Date.now() < deadline) {
    const res = await fetch(statusUrl, { headers });
    const s = await res.json();
    if (DONE.includes(s.status)) return s;
    await new Promise(r => setTimeout(r, 3000));
  }

  // Timeout — cancel the task
  await fetch(cancelUrl, {
    method: "PATCH",
    headers: { ...headers, "Content-Type": "application/json" },
    body: JSON.stringify({ action: "cancel" }),
  });

  throw new Error("Task cancelled due to timeout");
}
```

### Cancel Multiple Tasks

```javascript theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
async function cancelAll(runIds, apiKey) {
  return Promise.allSettled(
    runIds.map(id =>
      fetch(`https://agent.blackbox.ai/api/v1/tasks/${id}`, {
        method: "PATCH",
        headers: {
          Authorization: `Bearer ${apiKey}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ action: "cancel" }),
      }).then(r => r.json())
    )
  );
}
```

## Error Codes

| Status Code | Error                 | Description                              |
| ----------- | --------------------- | ---------------------------------------- |
| 200         | Success               | Operation completed successfully         |
| 400         | Bad Request           | Invalid JSON or no valid action provided |
| 401         | Unauthorized          | Invalid or missing API key               |
| 403         | Forbidden             | Task belongs to a different user         |
| 404         | Not Found             | Task not found                           |
| 500         | Internal Server Error | Server error                             |
