> ## 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.

# Relaunch agent

## Overview

Relaunch an ended agent by resetting it to `setup_needed` status. This endpoint allows you to restart an agent that has ended, clearing its configuration and allowing it to be set up again from scratch. Unlike deletion, this preserves the agent entity while resetting its state.

## Prerequisites

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

## Use Cases

* **Agent Recovery**: Restart agents that ended due to issues
* **Reconfiguration**: Reset agent to change LinkedIn credentials or country
* **Redeployment**: Restart agents with fresh configuration
* **Testing**: Reset agents for testing different configurations

## Path Parameters

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

## Response Examples

### Success Response

```json theme={null}
{
  "message": "Agent relaunched successfully",
  "status": "setup_needed"
}
```

### 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 relaunched when status is ended",
  "currentStatus": "running"
}

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

## What Happens During Relaunch

When an agent is relaunched, the following changes occur:

* **Status Reset**: Agent status changes from `ended` to `setup_needed`
* **Configuration Cleared**: LinkedIn credentials and passwords are removed
* **External Resources**: GoLogin tokens and proxy assignments are cleared
* **Alerts Cleared**: All alerts and notifications are removed
* **Tasks Cleared**: Current tasks and actions are reset
* **Agent Preserved**: The agent entity and ID remain the same

## Testing Examples

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

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

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

  return await response.json();
};

// Usage with error handling
try {
  const result = await relaunchAgent('agent_123');
  console.log('Agent relaunched:', result.message);
  console.log('New status:', result.status);
} catch (error) {
  console.error('Relaunch failed:', error.message);
}
```

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

def relaunch_agent(agent_id):
    """Relaunch an ended agent"""
    response = requests.post(
        f'https://api.kakiyo.com/v1/agents/{agent_id}/relaunch',
        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 relaunch agent: {error_data['message']}")

# Usage with error handling
try:
    result = relaunch_agent('agent_123')
    print(f"Agent relaunched: {result['message']}")
    print(f"New status: {result['status']}")
except Exception as e:
    print(f"Relaunch failed: {e}")
```

## Error Handling

### Status Code Reference

| Status Code | Error Code       | Description                 | Action                                   |
| ----------- | ---------------- | --------------------------- | ---------------------------------------- |
| 200         | -                | Success                     | Agent relaunched 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 safeRelaunchAgent = async (agentId) => {
  try {
    const response = await fetch(`https://api.kakiyo.com/v1/agents/${agentId}/relaunch`, {
      method: 'POST',
      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 relaunch this agent.');
        case 'invalid_status':
          throw new Error(`Agent cannot be relaunched. 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('Relaunch agent error:', error.message);
    throw error;
  }
};
```

## Integration Examples

### Complete Relaunch Workflow

```javascript theme={null}
const completeAgentRelaunch = async (agentId, newConfig) => {
  try {
    // Step 1: 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') {
      throw new Error(`Agent status is ${agent.status}. Cannot relaunch until ended.`);
    }

    // Step 2: Relaunch agent
    const relaunchResult = await relaunchAgent(agentId);
    console.log('✓ Agent relaunched:', relaunchResult.message);

    // Step 3: Setup agent with new configuration
    const setupResult = await fetch(`https://api.kakiyo.com/v1/agents/${agentId}/setup`, {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(newConfig)
    }).then(r => r.json());

    console.log('✓ Agent setup completed');

    return {
      success: true,
      agentId: agentId,
      status: 'setup_completed',
      message: 'Agent successfully relaunched and configured'
    };

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

// Usage
const newConfig = {
  login: "new_linkedin_email@example.com",
  password: "new_secure_password_456",
  country: "FR"
};

const result = await completeAgentRelaunch('agent_123', newConfig);
console.log('Relaunch workflow result:', result);
```

### Bulk Agent Relaunch

```javascript theme={null}
const relaunchMultipleAgents = async (agentIds) => {
  const results = [];
  
  for (const agentId of agentIds) {
    try {
      const result = await relaunchAgent(agentId);
      results.push({
        agentId,
        success: true,
        status: result.status,
        message: result.message
      });
      console.log(`✓ Relaunched agent ${agentId}`);
    } catch (error) {
      results.push({
        agentId,
        success: false,
        error: error.message
      });
      console.log(`✗ Failed to relaunch agent ${agentId}: ${error.message}`);
    }
  }

  return results;
};

// Usage
const agentIds = ['agent_123', 'agent_456', 'agent_789'];
const results = await relaunchMultipleAgents(agentIds);

const successful = results.filter(r => r.success).length;
const failed = results.filter(r => !r.success).length;

console.log(`Relaunch completed: ${successful} successful, ${failed} failed`);
```

### Agent Status Monitoring

```javascript theme={null}
const monitorAgentRelaunch = async (agentId) => {
  try {
    // Relaunch the agent
    await relaunchAgent(agentId);
    
    // Monitor status changes
    const checkStatus = async () => {
      const agent = await fetch(`https://api.kakiyo.com/v1/agents/${agentId}`, {
        headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
      }).then(r => r.json());
      
      return agent.status;
    };

    console.log('Monitoring agent status after relaunch...');
    
    let currentStatus = await checkStatus();
    console.log(`Initial status: ${currentStatus}`);

    // Check status every 30 seconds for up to 5 minutes
    const maxChecks = 10;
    let checks = 0;

    while (checks < maxChecks && currentStatus === 'setup_needed') {
      await new Promise(resolve => setTimeout(resolve, 30000)); // Wait 30 seconds
      currentStatus = await checkStatus();
      checks++;
      console.log(`Status check ${checks}: ${currentStatus}`);
    }

    return {
      finalStatus: currentStatus,
      checksPerformed: checks
    };

  } catch (error) {
    console.error('Monitoring failed:', error.message);
    throw error;
  }
};
```

## Best Practices

1. **Status Verification**: Always check agent status before relaunching
2. **Configuration Ready**: Have new configuration ready for immediate setup
3. **Error Handling**: Handle all possible error scenarios
4. **Monitoring**: Monitor agent status after relaunch
5. **Documentation**: Document why agents are being relaunched
6. **Rate Limiting**: Avoid relaunching too many agents simultaneously

## Next Steps After Relaunch

After successfully relaunching an agent:

1. **Setup Agent**: Use the `/agents/{id}/setup` endpoint to configure credentials
2. **Verify Configuration**: Check agent status and configuration
3. **Monitor Health**: Watch for any setup issues or alerts
4. **Test Functionality**: Verify the agent is working as expected

## Comparison: Relaunch vs Delete

| Aspect            | Relaunch            | Delete              |
| ----------------- | ------------------- | ------------------- |
| **Agent Entity**  | Preserved           | Permanently removed |
| **Agent ID**      | Remains same        | Lost forever        |
| **Usage History** | Preserved           | Permanently deleted |
| **Configuration** | Reset to defaults   | N/A                 |
| **Recovery**      | Can be reconfigured | Cannot be recovered |
| **Use Case**      | Temporary reset     | Permanent cleanup   |

<Info>
  Relaunch is ideal when you want to reconfigure an agent with different settings, while delete is for permanent removal when the agent is no longer needed.
</Info>
