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

# Delete agent

<Warning>
  **This is a destructive operation that cannot be undone.** Deleting an agent permanently removes all associated data including usage statistics, configuration, and history.
</Warning>

## Overview

Permanently delete an agent and all its associated data. This endpoint can only be used when the agent status is `ended`. The operation removes the agent from your account, cleans up external resources (GoLogin profiles), and deletes all usage statistics.

## Prerequisites

* Agent must have status `ended`
* You must have access to the agent (same team)
* Agent must exist in your account

## Use Cases

* **Account Cleanup**: Remove agents that are no longer needed
* **Data Management**: Clean up ended agents to reduce clutter
* **Resource Management**: Free up agent slots in your account
* **Compliance**: Permanently remove agent data for privacy requirements

## Path Parameters

<ParamField path="id" type="string" required>
  The unique identifier of the agent to delete
</ParamField>

## Response Examples

### Success Response

```json theme={null}
{
  "message": "Agent deleted successfully"
}
```

### Error Responses

```json theme={null}
// Agent not found
{
  "error": "not_found",
  "message": "Agent not found"
}

// No access to agent
{
  "error": "forbidden", 
  "message": "You do not have access to this agent"
}

// Invalid agent status
{
  "error": "invalid_status",
  "message": "Agent can only be deleted when status is ended",
  "currentStatus": "running"
}

// Internal server error
{
  "error": "internal_error",
  "message": "An internal error occurred"
}
```

## Testing Examples

```bash theme={null}
# Delete an ended agent
curl -X DELETE "https://api.kakiyo.com/v1/agents/agent_123" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json"
```

```javascript theme={null}
// JavaScript/Node.js
const deleteAgent = async (agentId) => {
  const response = await fetch(`https://api.kakiyo.com/v1/agents/${agentId}`, {
    method: 'DELETE',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    }
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(`Failed to delete agent: ${error.message}`);
  }

  return await response.json();
};

// Usage with error handling
try {
  const result = await deleteAgent('agent_123');
  console.log('Agent deleted:', result.message);
} catch (error) {
  console.error('Delete failed:', error.message);
}
```

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

def delete_agent(agent_id):
    """Permanently delete an agent"""
    response = requests.delete(
        f'https://api.kakiyo.com/v1/agents/{agent_id}',
        headers={
            'Authorization': 'Bearer YOUR_API_KEY',
            'Content-Type': 'application/json'
        }
    )
    
    if response.status_code == 200:
        return response.json()
    else:
        error_data = response.json()
        raise Exception(f"Failed to delete agent: {error_data['message']}")

# Usage with error handling
try:
    result = delete_agent('agent_123')
    print(f"Agent deleted: {result['message']}")
except Exception as e:
    print(f"Delete failed: {e}")
```

## Error Handling

### Status Code Reference

| Status Code | Error Code       | Description                 | Action                                   |
| ----------- | ---------------- | --------------------------- | ---------------------------------------- |
| 200         | -                | Success                     | Agent deleted successfully               |
| 400         | `invalid_status` | Agent status is not 'ended' | Wait for agent to end or manually end it |
| 403         | `forbidden`      | No access to agent          | Verify agent belongs to your team        |
| 404         | `not_found`      | Agent doesn't exist         | Check agent ID is correct                |
| 500         | `internal_error` | Server error                | Retry request or contact support         |

### Comprehensive Error Handling

```javascript theme={null}
const safeDeleteAgent = async (agentId) => {
  try {
    const response = await fetch(`https://api.kakiyo.com/v1/agents/${agentId}`, {
      method: 'DELETE',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      }
    });

    const data = await response.json();

    if (!response.ok) {
      switch (data.error) {
        case 'not_found':
          throw new Error('Agent not found. Please check the agent ID.');
        case 'forbidden':
          throw new Error('You do not have permission to delete this agent.');
        case 'invalid_status':
          throw new Error(`Agent cannot be deleted. Current status: ${data.currentStatus}. Agent must be ended first.`);
        case 'internal_error':
          throw new Error('Server error occurred. Please try again later.');
        default:
          throw new Error(`Unexpected error: ${data.message}`);
      }
    }

    return data;
  } catch (error) {
    console.error('Delete agent error:', error.message);
    throw error;
  }
};
```

## Integration Examples

### Safe Deletion Workflow

```javascript theme={null}
const safeAgentDeletion = async (agentId) => {
  try {
    // First, check agent status
    const agent = await fetch(`https://api.kakiyo.com/v1/agents/${agentId}`, {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    }).then(r => r.json());

    if (agent.status !== 'ended') {
      console.log(`Agent status is ${agent.status}. Cannot delete until ended.`);
      return { success: false, reason: 'Agent not ended' };
    }

    // Confirm deletion (in a real app, this would be user confirmation)
    const confirmed = true; // Replace with actual confirmation logic

    if (!confirmed) {
      return { success: false, reason: 'User cancelled' };
    }

    // Proceed with deletion
    const result = await deleteAgent(agentId);
    
    return { 
      success: true, 
      message: result.message 
    };

  } catch (error) {
    return { 
      success: false, 
      error: error.message 
    };
  }
};
```

### Bulk Agent Cleanup

```javascript theme={null}
const cleanupEndedAgents = async () => {
  try {
    // Get all agents
    const agents = await fetch('https://api.kakiyo.com/v1/agents', {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    }).then(r => r.json());

    // Filter ended agents
    const endedAgents = agents.filter(agent => agent.status === 'ended');
    
    console.log(`Found ${endedAgents.length} ended agents to clean up`);

    const results = [];
    for (const agent of endedAgents) {
      try {
        await deleteAgent(agent.id);
        results.push({ id: agent.id, success: true });
        console.log(`✓ Deleted agent ${agent.id}`);
      } catch (error) {
        results.push({ id: agent.id, success: false, error: error.message });
        console.log(`✗ Failed to delete agent ${agent.id}: ${error.message}`);
      }
    }

    return results;
  } catch (error) {
    console.error('Bulk cleanup failed:', error.message);
    throw error;
  }
};
```

## Best Practices

1. **Status Verification**: Always verify agent status is 'ended' before attempting deletion
2. **User Confirmation**: Implement confirmation dialogs for destructive operations
3. **Error Handling**: Handle all possible error scenarios gracefully
4. **Logging**: Log deletion operations for audit trails
5. **Backup Consideration**: Consider exporting important data before deletion
6. **Batch Operations**: Use rate limiting when deleting multiple agents

## Security Considerations

* **Authorization**: Ensure proper API key permissions
* **Team Isolation**: Agents can only be deleted by team members
* **Audit Logging**: All deletion operations are logged
* **Data Cleanup**: External resources are properly cleaned up

## What Gets Deleted

When an agent is deleted, the following data is permanently removed:

* **Agent Configuration**: All settings, credentials, and preferences
* **Usage Statistics**: Historical usage data and metrics
* **External Resources**: GoLogin profiles and proxy assignments
* **Task History**: All completed and pending tasks
* **Alert History**: All alerts and notifications
* **Integration Data**: Any connected third-party service data

<Warning>
  This operation cannot be undone. Make sure you have exported any important data before proceeding with deletion.
</Warning>
