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

# Declare Task Failed

> Define failure conditions to terminate workflows when errors occur

## What is Declare Task Failed?

Declare Task Failed is a specialized tool that allows your agent to immediately terminate workflow execution when specific failure conditions are met. This prevents the agent from continuing to attempt a task that cannot be completed, saving time and resources.

<Note>
  In your prompts, always refer to this tool as `declare_task_failed` (lowercase, with underscores).
</Note>

## Why This Tool Exists

Not all workflow failures are the same. Some errors are recoverable, while others indicate fundamental issues that make task completion impossible:

* **Authentication Failures**: Locked accounts or invalid credentials
* **Missing Prerequisites**: Required data or systems unavailable
* **Business Rule Violations**: Conditions that invalidate the entire process
* **Technical Limitations**: System errors that cannot be resolved
* **User-Defined Conditions**: Specific scenarios you define as failures

Without `declare_task_failed`, the agent might spend excessive time trying to work around insurmountable obstacles.

## How It Works

1. The agent encounters a condition you've defined as a failure
2. It calls `declare_task_failed` with a description of the failure
3. Workflow execution immediately terminates
4. The run is marked with status `task_failed` (shown in the dashboard as **Task Failed**)
5. No trajectory is saved (the run is not cached)
6. The failure reason is recorded for debugging

<Warning>
  **Important**: Once `declare_task_failed` is called, the workflow stops immediately. This tool is never cached because failed runs don't create trajectories.
</Warning>

<Info>
  Think of `task_failed` as a terminal run outcome, not an infrastructure crash. Cyberdesk still keeps the run's message history and failure reason, and you can retry that run later from the Runs UI or API. The part that is discarded is the pending trajectory cache for that failed path.
</Info>

<Note>
  `task_failed` is reserved for explicit `declare_task_failed` calls. Other failure paths (for example infrastructure or unexpected execution errors) continue using status `error`.\
  You can filter runs by this status using the Runs list `status=task_failed` filter.
</Note>

## When to Use Declare Task Failed

### 1. Authentication Errors

```text theme={null}
"If you see 'Account Locked' or 'Invalid Credentials' after attempting login, 
use declare_task_failed to terminate the workflow. Do not attempt 
password recovery or multiple login attempts."
```

### 2. Missing Critical Data

```text theme={null}
"Search for patient ID {patient_id}. If no results are found after searching, 
use declare_task_failed indicating 'Patient ID {patient_id} not found in system'. 
Do not proceed with empty data."
```

### 3. System Unavailability

```text theme={null}
"If the application shows 'System Maintenance in Progress' or fails to load 
after 30 seconds, use declare_task_failed stating 'Target system unavailable'."
```

### 4. Business Rule Violations

```text theme={null}
"Check the account balance before processing. If balance is less than {required_amount}, 
use declare_task_failed with message 'Insufficient funds: balance below required amount'."
```

## How to Prompt for Task Failure

### Best Practices

1. **Be Specific**: Clearly define what constitutes a failure
2. **Provide Context**: Explain why this is a failure condition
3. **Include Messages**: Specify what message to include when failing
4. **Set Boundaries**: Define how many attempts before failing
5. **Consider Timing**: Specify timeouts for time-sensitive operations

### Prompt Template

```text theme={null}
"If [specific condition occurs], use declare_task_failed with message 
'[descriptive failure reason]'. Do not [what not to do]."
```

## Real-World Examples

### Healthcare: Patient Safety

```text theme={null}
"When searching for the patient's medication list, if you see any alert about 
'Drug Interaction Warning - Contraindicated', immediately use declare_task_failed 
with message 'Critical drug interaction detected - manual review required'. 
Do not proceed with the prescription."
```

### Finance: Compliance Checks

```text theme={null}
"Before initiating the transfer, verify the recipient is not on the sanctions list. 
If the screen shows 'Compliance Alert - Restricted Entity', use declare_task_failed 
stating 'Transfer blocked - recipient on sanctions list'. Do not attempt workarounds."
```

### E-commerce: Inventory Management

```text theme={null}
"Check inventory for all items in order {order_id}. If any item shows 
'Out of Stock' or 'Discontinued', use declare_task_failed with message 
'Order cannot be fulfilled - {item_name} unavailable'. Do not process partial orders."
```

### IT Operations: Deployment Safety

```text theme={null}
"Before deploying, check the pre-deployment tests. If status shows 'FAILED' 
for any critical test, use declare_task_failed with 'Deployment aborted - 
critical test failures detected'. Do not override or skip failed tests."
```

## Common Failure Patterns

### Multiple Attempt Failures

```text theme={null}
"Attempt to connect to the database. If connection fails, retry up to 3 times 
with 10-second intervals. If still failing after 3 attempts, use declare_task_failed 
with 'Database connection failed after 3 attempts'."
```

### Timeout Conditions

```text theme={null}
"Click 'Generate Report' and wait for completion. If the progress bar doesn't 
finish within 5 minutes, use declare_task_failed stating 'Report generation 
timeout - exceeded 5 minute limit'."
```

### Validation Failures

```text theme={null}
"After filling the form, click Submit. If validation errors appear for required 
fields that cannot be populated from the provided data {input_data}, 
use declare_task_failed listing the missing required fields."
```

### Permission Denials

```text theme={null}
"Navigate to the admin panel. If you see 'Access Denied' or 'Insufficient Privileges', 
use declare_task_failed with 'User lacks required admin permissions'. 
Do not attempt to access via other routes."
```

## Failure vs. Recovery Strategies

### When to Fail vs. Retry

<Tabs>
  <Tab title="Use declare_task_failed">
    ```text theme={null}
    "If login fails with 'Account Locked', use declare_task_failed"
    "If the file is corrupted (shows 'Cannot read file'), use declare_task_failed"
    "If payment is declined with 'Card Reported Stolen', use declare_task_failed"
    ```
  </Tab>

  <Tab title="Retry/Recover">
    ```text theme={null}
    "If page doesn't load, refresh and try again"
    "If button click doesn't respond, wait 2 seconds and retry"
    "If search returns no results, try alternative search terms"
    ```
  </Tab>
</Tabs>

### Cascading Failures

```text theme={null}
"The workflow requires sequential approvals from 3 departments. If any department 
shows 'Request Denied' or 'Not Authorized', use declare_task_failed immediately 
with 'Approval chain broken at {department_name}'. Don't continue to other departments."
```

## Integration with Other Tools

### With Focused Action

```text theme={null}
"Use focused_action to check if an error message appears after submission. 
If the error contains 'Fatal', 'Critical', or 'Unrecoverable', 
use declare_task_failed with the full error message."
```

### With Terminal Commands

```text theme={null}
"Use execute_terminal_command to run 'Test-Path C:\RequiredFiles\config.xml'. 
If it returns False, use declare_task_failed with 'Required configuration file missing'."
```

### Conditional Workflow Paths

```text theme={null}
"Check the order status. If status is 'Cancelled' or 'Refunded', 
use declare_task_failed with 'Order {order_id} already {status} - no action needed'. 
Only proceed if status is 'Pending' or 'Processing'."
```

## Advanced Usage

### Complex Failure Conditions

```text theme={null}
"Monitor the batch processing progress. Use declare_task_failed if:
1. More than 10% of items fail processing
2. Any critical error (severity = 'CRITICAL') appears in logs
3. Processing time exceeds 30 minutes
4. System memory usage exceeds 90%
Include specific failure reason in the message."
```

### Partial Success Handling

```text theme={null}
"Process all invoices in the list. Keep track of successes and failures. 
If more than 50% fail, use declare_task_failed with 
'Batch processing failed - {failed_count} of {total_count} invoices failed'. 
Otherwise, complete successfully even with some failures."
```

### Pre-flight Checks

```text theme={null}
"Before starting the main workflow:
1. Verify all required applications are running
2. Check available disk space > 10GB
3. Confirm network connectivity to required services
If any check fails, use declare_task_failed with specific check that failed. 
This prevents wasting time on doomed workflows."
```

## Best Practices Summary

1. **Define clear, specific failure conditions**
2. **Fail fast when recovery is impossible**
3. **Include descriptive failure messages**
4. **Don't use for recoverable errors**
5. **Consider the business impact of failing vs. continuing**
6. **Set reasonable retry limits before failing**
7. **Document why each failure condition exists**
8. **Test failure scenarios to ensure proper handling**

## Common Mistakes to Avoid

<Warning>
  **Don't use declare\_task\_failed for:**

  * Temporary UI delays (use wait/retry instead)
  * Minor data variations (use focused\_action to adapt)
  * Recoverable errors (implement retry logic)
  * Success scenarios (even if no action needed)
</Warning>

### ❌ Incorrect Usage

```text theme={null}
"If the page takes more than 2 seconds to load, use declare_task_failed"  // Too aggressive
"If anything goes wrong, use declare_task_failed"                         // Too vague
"After completing successfully, use declare_task_failed"                   // Wrong tool
```

### ✅ Correct Usage

```text theme={null}
"If login fails with 'Account Suspended', use declare_task_failed"
"If required file is missing after checking 3 locations, use declare_task_failed"
"If the API returns 403 Forbidden, use declare_task_failed with 'API access denied'"
```
