Cancel Task

PATCHhttps://agent.blackbox.ai/api/v1/tasks/{runId}

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 and click Get an API Key (requires a Pro subscription)
  2. Once provisioning completes, you will be redirected to your 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

Authorizationstringrequired

API Key of the form Bearer <api_key>.

Example: Bearer sk_b41b647ffbfed27f616560

Content-Typestringrequired

Must be set to application/json.

Path Parameters

runIdstringrequired

The unique run identifier of the task to cancel or update.

Example: a1b2c3d4-e5f6-7890-abcd-ef1234567890

Request Body

actionstring

Action to perform. Use "cancel" to stop the running task.

Must be "cancel" when provided.

titlestring

New title for the task's chat thread. Length: 1–200 characters.

Example: "Stripe Integration Task"

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

Response Fields

successboolean

Whether the operation succeeded.

statusstring

The current status of the run after the operation.

messagestring

Human-readable description of the result.

Request Example
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" }'
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" }'
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}`);
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']}")
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))
}
Response Example
{
  "success": true,
  "status": "cancelled",
  "message": "Task a1b2c3d4-e5f6-7890-abcd-ef1234567890 cancelled successfully"
}
{
  "success": false,
  "status": "completed",
  "message": "Task is not in a cancellable state (already completed, failed, or not found)"
}
{
  "success": true,
  "status": "completed",
  "message": "Task title updated"
}
{
  "error": "Task not found"
}
{
  "error": "No valid action provided. Use action: 'cancel' or provide a title."
}

Use Cases

Cancel with Timeout Guard

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

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