# Executions API

Track and manage agent execution history, monitor running tasks, and view execution trees with the TeamDay Executions API.

# Executions API

Executions represent instances when agents run. Each execution captures the complete history of messages, tool usage, results, and performance metrics. Use the Executions API to monitor agent activity, track task completion, and analyze execution patterns.

**Base URL:** `https://cc.teamday.ai/api/v1/executions`

**Authentication:** [Personal Access Token](https://docs.teamday.ai/api/authentication) required

---

## Endpoints Overview

| Method | Endpoint | Description | Status |
|--------|----------|-------------|--------|
| GET | `/executions` | List executions | 🟡 Untested |
| GET | `/executions/[id]` | Get execution details | 🟡 Untested |
| GET | `/executions/[id]/tree` | Get execution tree (subagents) | 🟡 Untested |
| POST | `/executions/[id]/cancel` | Cancel running execution | 🟡 Untested |

**Implementation Status:** Complete but untested in production

---

## Execution Object

### Properties

```typescript
{
  id: string              // Execution ID (format: exec-{timestamp}-{random})
  agentId: string         // Agent that executed
  organizationId: string  // Owner organization
  userId?: string         // User who triggered execution
  chatId: string          // Associated chat ID
  sessionId: string       // Claude Code session ID
  status: string          // "pending" | "running" | "completed" | "failed" | "cancelled"
  message: string         // User's message (singular)
  result?: string         // Agent's response
  error?: string          // Error message (if failed)
  agentName?: string      // Agent display name (for notifications)
  parentExecutionId?: string  // Parent execution (if delegated)
  delegationDepth: number // Depth in delegation chain
  startedAt: string       // ISO 8601 timestamp
  completedAt?: string    // ISO 8601 timestamp (if finished)
  duration?: number       // Milliseconds
  tokensInput?: number    // Input tokens used
  tokensOutput?: number   // Output tokens used
  cost?: number           // Execution cost
}
```

### Example Object

```json
{
  "id": "exec-1734567890-abc",
  "agentId": "abc123def456",
  "organizationId": "org_456",
  "userId": "user_789",
  "chatId": "chat_abc123",
  "sessionId": "session_xyz789",
  "status": "completed",
  "message": "Analyze this sales data",
  "result": "Based on the sales data analysis, revenue increased 23% YoY...",
  "agentName": "Research Assistant",
  "delegationDepth": 0,
  "startedAt": "2025-12-09T10:30:00Z",
  "completedAt": "2025-12-09T10:30:45Z",
  "duration": 45000,
  "tokensInput": 856,
  "tokensOutput": 378,
  "cost": 0.0045
}
```

---

## List Executions

Retrieve execution history for your organization, optionally filtered by agent.

### Request

```http
GET /api/v1/executions
```

**Headers:**
```http
Authorization: Bearer td_xxxxx...
```

**Query Parameters:**
- `agentId` (string, optional) - Filter by specific agent
- `limit` (number, optional) - Maximum results (default: 50, max: 100)

### Response

**Success (200 OK):**
```json
{
  "success": true,
  "executions": [
    {
      "id": "exec-1734567890-abc",
      "agentId": "abc123def456",
      "organizationId": "org_456",
      "userId": "user_789",
      "chatId": "chat_abc123",
      "sessionId": "session_xyz789",
      "status": "completed",
      "message": "Analyze this sales data",
      "result": "Based on the sales data analysis...",
      "delegationDepth": 0,
      "startedAt": "2025-12-09T10:30:00Z",
      "completedAt": "2025-12-09T10:30:45Z",
      "duration": 45000,
      "tokensInput": 856,
      "tokensOutput": 378,
      "cost": 0.0045
    },
    {
      "id": "exec-1734571200-def",
      "agentId": "abc123def456",
      "organizationId": "org_456",
      "userId": "user_789",
      "chatId": "chat_def456",
      "sessionId": "session_abc123",
      "status": "running",
      "message": "Generate weekly report",
      "delegationDepth": 0,
      "startedAt": "2025-12-09T11:00:00Z"
    }
  ]
}
```

**Empty result:**
```json
{
  "success": true,
  "executions": []
}
```

**Error (401 Unauthorized):**
```json
{
  "error": true,
  "statusCode": 401,
  "statusMessage": "Unauthorized",
  "message": "Unauthorized. Invalid or expired token"
}
```

### Examples

**List all executions:**
```bash
curl https://cc.teamday.ai/api/v1/executions \
  -H "Authorization: Bearer $TEAMDAY_TOKEN"
```

**Filter by agent:**
```bash
curl "https://cc.teamday.ai/api/v1/executions?agentId=abc123def456" \
  -H "Authorization: Bearer $TEAMDAY_TOKEN"
```

**Limit results:**
```bash
curl "https://cc.teamday.ai/api/v1/executions?limit=10" \
  -H "Authorization: Bearer $TEAMDAY_TOKEN"
```

**Combine filters:**
```bash
curl "https://cc.teamday.ai/api/v1/executions?agentId=abc123def456&limit=25" \
  -H "Authorization: Bearer $TEAMDAY_TOKEN"
```

---

## Get Execution Details

Retrieve complete details for a specific execution, including full message history and tool calls.

### Request

```http
GET /api/v1/executions/[id]
```

**Headers:**
```http
Authorization: Bearer td_xxxxx...
```

**Path Parameters:**
- `id` (string) - Execution ID (format: `exec-{timestamp}-{random}`)

### Response

**Success (200 OK):**
```json
{
  "success": true,
  "execution": {
    "id": "exec-1734567890-abc",
    "agentId": "abc123def456",
    "organizationId": "org_456",
    "userId": "user_789",
    "chatId": "chat_abc123",
    "sessionId": "session_xyz789",
    "status": "completed",
    "message": "Analyze this sales data and provide insights",
    "result": "Based on the sales data analysis:\n\n1. Revenue increased 23% YoY\n2. Top performing region: West Coast (35% of total)\n3. Q4 shows strongest growth (+42%)\n\nRecommendations:\n- Focus marketing efforts on West Coast\n- Replicate Q4 strategies in other quarters\n- Investigate underperforming regions",
    "agentName": "Research Assistant",
    "delegationDepth": 0,
    "startedAt": "2025-12-09T10:30:00Z",
    "completedAt": "2025-12-09T10:30:45Z",
    "duration": 45000,
    "tokensInput": 1523,
    "tokensOutput": 1324,
    "cost": 0.0089
  }
}
```

**Error (404 Not Found):**
```json
{
  "error": true,
  "statusCode": 404,
  "statusMessage": "Not Found",
  "message": "Execution not found"
}
```

**Error (401 Unauthorized):**
```json
{
  "error": true,
  "statusCode": 401,
  "statusMessage": "Unauthorized",
  "message": "Unauthorized. Invalid or expired token"
}
```

### Example

```bash
curl https://cc.teamday.ai/api/v1/executions/exec-1734567890-abc \
  -H "Authorization: Bearer $TEAMDAY_TOKEN"
```

---

## Get Execution Tree

Retrieve the execution tree showing parent-child relationships when agents delegate work to subagents.

### Request

```http
GET /api/v1/executions/[id]/tree
```

**Headers:**
```http
Authorization: Bearer td_xxxxx...
```

**Path Parameters:**
- `id` (string) - Execution ID (format: `exec-{timestamp}-{random}`)

### Response

The tree response is a recursive structure: each execution object may contain a `children` array of the same shape (`Execution & { children?: ExecutionTree[] }`).

**Success (200 OK):**
```json
{
  "success": true,
  "tree": {
    "id": "exec-1734567890-abc",
    "agentId": "abc123def456",
    "organizationId": "org_456",
    "chatId": "chat_abc123",
    "sessionId": "session_xyz789",
    "status": "completed",
    "message": "Research and write a report on AI trends",
    "result": "Here is the completed report...",
    "delegationDepth": 0,
    "startedAt": "2025-12-09T10:00:00Z",
    "completedAt": "2025-12-09T10:05:00Z",
    "children": [
      {
        "id": "exec-1734567920-def",
        "agentId": "ghi789jkl012",
        "organizationId": "org_456",
        "chatId": "chat_abc123",
        "sessionId": "session_xyz789",
        "status": "completed",
        "message": "Research AI trends for 2025",
        "result": "Key findings: ...",
        "parentExecutionId": "exec-1734567890-abc",
        "delegationDepth": 1,
        "startedAt": "2025-12-09T10:00:30Z",
        "completedAt": "2025-12-09T10:02:00Z",
        "children": []
      },
      {
        "id": "exec-1734568050-ghi",
        "agentId": "mno345pqr678",
        "organizationId": "org_456",
        "chatId": "chat_abc123",
        "sessionId": "session_xyz789",
        "status": "completed",
        "message": "Write the report based on research",
        "result": "Report draft completed...",
        "parentExecutionId": "exec-1734567890-abc",
        "delegationDepth": 1,
        "startedAt": "2025-12-09T10:02:30Z",
        "completedAt": "2025-12-09T10:05:00Z",
        "children": []
      }
    ]
  }
}
```

**Single execution (no subagents):**
```json
{
  "success": true,
  "tree": {
    "id": "exec-1734567890-abc",
    "agentId": "abc123def456",
    "organizationId": "org_456",
    "chatId": "chat_abc123",
    "sessionId": "session_xyz789",
    "status": "completed",
    "message": "Analyze this sales data",
    "result": "Based on the analysis...",
    "delegationDepth": 0,
    "startedAt": "2025-12-09T10:30:00Z",
    "completedAt": "2025-12-09T10:30:45Z"
  }
}
```

**Error (404 Not Found):**
```json
{
  "error": true,
  "statusCode": 404,
  "statusMessage": "Not Found",
  "message": "Execution not found"
}
```

### Example

```bash
curl https://cc.teamday.ai/api/v1/executions/exec-1734567890-abc/tree \
  -H "Authorization: Bearer $TEAMDAY_TOKEN"
```

### Use Cases

**Monitoring delegation:**
- Track when agents delegate to subagents
- Measure efficiency of agent collaboration
- Debug complex multi-agent workflows

**Performance analysis:**
- Identify bottlenecks in delegated tasks
- Compare serial vs. parallel delegation
- Optimize agent orchestration

---

## Cancel Execution

Stop a running execution. Only executions in `pending` or `running` status can be cancelled.

### Request

```http
POST /api/v1/executions/[id]/cancel
```

**Headers:**
```http
Authorization: Bearer td_xxxxx...
```

**Path Parameters:**
- `id` (string) - Execution ID (format: `exec-{timestamp}-{random}`)

**Body:** None

### Response

**Success (200 OK):**
```json
{
  "success": true,
  "message": "Execution cancelled"
}
```

**Error (400 Bad Request - Already completed):**
```json
{
  "error": true,
  "statusCode": 400,
  "statusMessage": "Bad Request",
  "message": "Cannot cancel execution: already completed"
}
```

**Error (404 Not Found):**
```json
{
  "error": true,
  "statusCode": 404,
  "statusMessage": "Not Found",
  "message": "Execution not found"
}
```

### Example

```bash
curl -X POST https://cc.teamday.ai/api/v1/executions/exec-1734567890-abc/cancel \
  -H "Authorization: Bearer $TEAMDAY_TOKEN"
```

### Notes

**Cancellation behavior:**
- Execution immediately marked as `cancelled`
- Agent stops processing (best effort)
- Partial results may be saved
- Cannot resume cancelled execution
- Subagents (if any) are also cancelled

**When to cancel:**
- Long-running execution taking too long
- Agent stuck in infinite loop
- User changed requirements
- Testing/debugging purposes

---

## Execution Status

Executions progress through the following states:

### Pending

**Status:** `"pending"`

**Description:** Execution created but not yet started. Waiting for resources or queued.

**Duration:** Usually < 1 second

**Next states:** `running`, `cancelled`

### Running

**Status:** `"running"`

**Description:** Agent actively processing. May involve multiple tool calls and API requests.

**Duration:** Varies (seconds to minutes)

**Next states:** `completed`, `failed`, `cancelled`

### Completed

**Status:** `"completed"`

**Description:** Execution finished successfully. Results available.

**Terminal state:** Yes (no further transitions)

### Failed

**Status:** `"failed"`

**Description:** Execution encountered an error and stopped. Check `error` field for details.

**Terminal state:** Yes (no further transitions)

**Common causes:**
- API errors (rate limits, service unavailable)
- Invalid tool calls
- Permission errors
- Timeout

### Cancelled

**Status:** `"cancelled"`

**Description:** Execution manually stopped via cancel endpoint.

**Terminal state:** Yes (no further transitions)

---

## Filtering & Pagination

### By Agent

Filter executions for a specific agent:

```bash
curl "https://cc.teamday.ai/api/v1/executions?agentId=abc123def456" \
  -H "Authorization: Bearer $TEAMDAY_TOKEN"
```

### By Status (Future)

**Coming soon:** Filter by execution status

```bash
# Future feature
curl "https://cc.teamday.ai/api/v1/executions?status=running" \
  -H "Authorization: Bearer $TEAMDAY_TOKEN"
```

### Pagination

Control result count:

```bash
# Get first 10 executions
curl "https://cc.teamday.ai/api/v1/executions?limit=10" \
  -H "Authorization: Bearer $TEAMDAY_TOKEN"

# Get up to 100 executions
curl "https://cc.teamday.ai/api/v1/executions?limit=100" \
  -H "Authorization: Bearer $TEAMDAY_TOKEN"
```

**Defaults:**
- Default limit: 50
- Maximum limit: 100
- Results ordered by `startedAt` (newest first)

**Offset-based pagination (Future):**
```bash
# Future feature
curl "https://cc.teamday.ai/api/v1/executions?limit=50&offset=50" \
  -H "Authorization: Bearer $TEAMDAY_TOKEN"
```

---

## Performance Metrics

Execution objects include performance data directly as top-level fields:

### Duration

**Field:** `duration` (milliseconds)

**Calculation:** `completedAt - startedAt`

**Use cases:**
- Track average agent response time
- Identify slow executions
- Optimize agent prompts

### Token Usage

**Fields:** `tokensInput` (number), `tokensOutput` (number)

**Description:** Input and output tokens consumed separately.

**Use cases:**
- Estimate API costs
- Optimize prompt length
- Monitor token efficiency

### Cost

**Field:** `cost` (number)

**Description:** Estimated cost for this execution in USD.

**Use cases:**
- Budget tracking
- Cost optimization
- Per-agent cost analysis

---

## Common Patterns

### Monitor Running Executions

Poll for running executions to monitor agent activity:

```javascript
async function getRunningExecutions() {
  const response = await fetch('https://cc.teamday.ai/api/v1/executions', {
    headers: {
      'Authorization': `Bearer ${process.env.TEAMDAY_TOKEN}`
    }
  })

  const data = await response.json()

  return data.executions.filter(exec => exec.status === 'running')
}

// Check every 5 seconds
setInterval(async () => {
  const running = await getRunningExecutions()
  console.log(`${running.length} executions running`)
}, 5000)
```

### Track Agent Performance

Calculate average execution time per agent:

```javascript
async function getAgentPerformance(agentId) {
  const response = await fetch(
    `https://cc.teamday.ai/api/v1/executions?agentId=${agentId}&limit=100`,
    {
      headers: {
        'Authorization': `Bearer ${process.env.TEAMDAY_TOKEN}`
      }
    }
  )

  const data = await response.json()
  const executions = data.executions

  const completed = executions.filter(e => e.status === 'completed')

  const avgDuration = completed.reduce((sum, e) => {
    return sum + (e.duration || 0)
  }, 0) / completed.length

  const avgTokens = completed.reduce((sum, e) => {
    return sum + (e.tokensInput || 0) + (e.tokensOutput || 0)
  }, 0) / completed.length

  return {
    totalExecutions: executions.length,
    completedExecutions: completed.length,
    avgDuration: Math.round(avgDuration),
    avgTokens: Math.round(avgTokens)
  }
}
```

### Cancel Long-Running Executions

Auto-cancel executions exceeding a timeout:

```javascript
async function cancelLongRunning(timeoutMs = 300000) { // 5 minutes
  const response = await fetch('https://cc.teamday.ai/api/v1/executions', {
    headers: {
      'Authorization': `Bearer ${process.env.TEAMDAY_TOKEN}`
    }
  })

  const executions = await response.json()
  const now = Date.now()

  for (const exec of executions) {
    if (exec.status !== 'running') continue

    const startedAt = new Date(exec.startedAt).getTime()
    const elapsed = now - startedAt

    if (elapsed > timeoutMs) {
      console.log(`Cancelling execution ${exec.id} (running ${elapsed}ms)`)

      await fetch(`https://cc.teamday.ai/api/v1/executions/${exec.id}/cancel`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${process.env.TEAMDAY_TOKEN}`
        }
      })
    }
  }
}
```

---

## Error Handling

### Common Errors

**400 Bad Request:**
- Attempting to cancel completed/failed execution
- Invalid query parameters

**401 Unauthorized:**
- Missing `Authorization` header
- Invalid or expired token

**404 Not Found:**
- Execution ID doesn't exist
- Execution belongs to different organization

**500 Internal Server Error:**
- Database connectivity issues
- Service temporarily unavailable

### Retry Strategy

For transient failures, implement exponential backoff:

```javascript
async function getExecutionWithRetry(executionId, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const response = await fetch(
        `https://cc.teamday.ai/api/v1/executions/${executionId}`,
        {
          headers: {
            'Authorization': `Bearer ${process.env.TEAMDAY_TOKEN}`
          }
        }
      )

      if (!response.ok) {
        const error = await response.json()

        // Don't retry client errors
        if (response.status >= 400 && response.status < 500) {
          throw new Error(error.message)
        }

        // Retry server errors
        if (i === maxRetries - 1) throw new Error(error.message)

        await new Promise(resolve =>
          setTimeout(resolve, Math.pow(2, i) * 1000)
        )
        continue
      }

      return await response.json()

    } catch (err) {
      if (i === maxRetries - 1) throw err
    }
  }
}
```

---

## Best Practices

### Monitoring

**Poll frequency:**
- Running executions: 2-5 seconds
- Completed executions: No polling needed (use webhooks when available)

**What to monitor:**
- Executions stuck in `running` > 5 minutes
- High failure rate (> 10%)
- Unusual token usage spikes

### Storage

**Execution retention:**
- Keep recent executions (last 30 days) for debugging
- Archive older executions for compliance
- Delete sensitive data per retention policy

**Note:** TeamDay currently retains all executions indefinitely. Self-service deletion coming soon.

### Performance

**Optimize agent prompts:**
- Monitor `tokensInput` and `tokensOutput` to reduce costs
- Track `duration` to improve response time
- Review `cost` to monitor spending per execution

**Parallel execution:**
- Run multiple agents concurrently (no API limits currently)
- Use execution trees for delegation patterns
- Monitor total active executions

---

## Related Resources

- [Agents API](https://docs.teamday.ai/api/agents) - Create and manage agents
- [Tasks API](https://docs.teamday.ai/api/tasks) - Manage agent tasks
- [Authentication](https://docs.teamday.ai/api/authentication) - PAT token setup
- [Error Reference](https://docs.teamday.ai/api/errors) - Complete error documentation

---

## Need Help?

**Issues with executions?**
- Check [error reference](https://docs.teamday.ai/api/errors) for troubleshooting
- Monitor execution status and error messages
- Use execution trees to debug delegation

**Questions?**
- 📧 Email: support at teamday.ai
- 💬 Discord: [Join community](https://discord.gg/teamday)
- 🐛 Report bugs: [GitHub Issues](https://github.com/TeamDay-AI/teamday/issues)

---

**Last Updated:** February 19, 2026
