Tasks
Tasks are units of work that agents execute. They provide structured job management with tracking, retries, dependencies, and deadlines.
Why Tasks?
While conversations are great for interactive dialogue, many agent workloads are better modeled as discrete jobs:
- Batch processing: Process 100 documents overnight
- Background work: Generate reports while users sleep
- Scheduled jobs: Daily data sync at 2 AM
- Dependent work: Task B waits for Task A to complete
Tasks give you:
- Progress tracking and status updates
- Automatic retries on failure
- Priority queuing
- Dependency management
- Deadline enforcement
Task Types
Manual Tasks
Created and triggered by users or API calls:
const task = await client.tasks.create({
name: 'Generate Q4 Report',
type: 'manual',
assignedAgentId: 'agent-123',
input: {
quarter: 'Q4',
year: 2024,
includeCharts: true
}
});
// Run it now
await client.tasks.run(task.id);
Scheduled Tasks
Run automatically on a schedule (see Schedules):
const task = await client.tasks.create({
name: 'Daily Data Sync',
type: 'scheduled',
assignedAgentId: 'agent-123',
schedule: '0 2 * * *', // 2 AM daily
timezone: 'America/New_York',
input: {
source: 'salesforce',
target: 'data-warehouse'
}
});
Triggered Tasks
Execute in response to webhooks (see Triggers):
const task = await client.tasks.create({
name: 'Process New Order',
type: 'triggered',
assignedAgentId: 'agent-123',
input: {
// Will be merged with trigger payload
notifyTeam: true
}
});
Task Lifecycle
┌─────────┐ ┌────────────┐ ┌───────────┐
│ pending │───▶│ in_progress│───▶│ completed │
└─────────┘ └────────────┘ └───────────┘
│ │
│ ▼
│ ┌────────┐
│ │ failed │──▶ (retry)
│ └────────┘
│ │
▼ ▼
┌───────────┐ ┌───────────┐
│ cancelled │ │ paused │
└───────────┘ └───────────┘
Status Values
| Status | Description |
|---|---|
pending | Waiting to be executed |
in_progress | Currently running |
completed | Successfully finished |
failed | Execution failed (may retry) |
cancelled | Manually cancelled |
paused | Temporarily paused |
Creating Tasks
Basic Task
const task = await client.tasks.create({
name: 'Analyze Customer Feedback',
description: 'Process and categorize recent customer feedback',
assignedAgentId: 'agent-123',
input: {
feedbackSource: 'zendesk',
dateRange: 'last-7-days'
}
});
Task with Priority
const task = await client.tasks.create({
name: 'Urgent Security Scan',
assignedAgentId: 'security-agent',
priority: 'urgent', // low, medium, high, urgent
input: {
target: 'production-servers',
scanType: 'full'
}
});
Task with Settings
const task = await client.tasks.create({
name: 'Long-Running Analysis',
assignedAgentId: 'data-agent',
settings: {
maxRetries: 3,
timeoutMs: 300000, // 5 minutes
retryDelayMs: 10000, // 10 seconds between retries
enableMemory: true // Agent remembers across retries
},
input: {
dataset: 'large-dataset-id'
}
});
Task with Deadline
const task = await client.tasks.create({
name: 'Compliance Report',
assignedAgentId: 'compliance-agent',
deadline: '2024-12-31T23:59:59Z',
priority: 'high',
input: {
reportType: 'annual-audit'
}
});
Note: Task deadlines require a Business plan or higher.
Task Dependencies
Tasks can depend on other tasks, creating execution chains:
// First task
const extractTask = await client.tasks.create({
name: 'Extract Data',
assignedAgentId: 'etl-agent',
input: { source: 'database' }
});
// Second task waits for first
const transformTask = await client.tasks.create({
name: 'Transform Data',
assignedAgentId: 'etl-agent',
dependencies: [extractTask.id],
input: { transformations: ['normalize', 'dedupe'] }
});
// Third task waits for second
const loadTask = await client.tasks.create({
name: 'Load Data',
assignedAgentId: 'etl-agent',
dependencies: [transformTask.id],
input: { destination: 'warehouse' }
});
// Run the first task - others will follow automatically
await client.tasks.run(extractTask.id);
Note: Task dependencies require a Business plan or higher.
Multi-Agent Tasks
Assign tasks to multiple agents for parallel processing:
const task = await client.tasks.create({
name: 'Multi-Region Analysis',
assignedAgents: [
'agent-us',
'agent-eu',
'agent-apac'
],
input: {
analysisType: 'market-trends'
}
});
Running Tasks
Execute Immediately
const run = await client.tasks.run('task-123');
console.log(run.id); // run-456
console.log(run.status); // 'in_progress'
Execute with Input Override
const run = await client.tasks.run('task-123', {
input: {
// Override or add to task's default input
urgent: true,
customParam: 'value'
}
});
Cancel Running Task
await client.tasks.cancel('task-123');
Retry Failed Task
await client.tasks.retry('task-123');
Monitoring Tasks
Get Task Status
const task = await client.tasks.get('task-123');
console.log({
status: task.status,
progress: task.progress,
lastRunAt: task.lastRunAt,
nextRunAt: task.nextRunAt
});
List Task Runs
const runs = await client.tasks.listRuns('task-123');
for (const run of runs.data) {
console.log({
runId: run.id,
status: run.status,
startedAt: run.startedAt,
completedAt: run.completedAt,
tokensUsed: run.tokensUsed,
cost: run.cost
});
}
Get Run Details
const run = await client.tasks.getRun('run-456');
console.log({
output: run.output,
error: run.error,
duration: run.durationMs,
checkpoints: run.checkpoints
});
Task API Reference
List Tasks
const tasks = await client.tasks.list({
appId: 'app-123', // Filter by app
teamId: 'team-456', // Filter by team
status: 'pending', // Filter by status
type: 'scheduled', // Filter by type
priority: 'high', // Filter by priority
assignedAgentId: 'agent-789', // Filter by agent
limit: 50,
offset: 0
});
Update Task
await client.tasks.update('task-123', {
name: 'Updated Task Name',
priority: 'urgent',
settings: {
maxRetries: 5
}
});
Delete Task
await client.tasks.delete('task-123');
Task Runs
Each execution of a task creates a "run" record:
interface TaskRun {
id: string;
taskId: string;
status: 'pending' | 'in_progress' | 'completed' | 'failed';
input: Record<string, any>;
output: Record<string, any>;
error?: string;
startedAt: string;
completedAt?: string;
durationMs?: number;
tokensUsed: number;
cost: number;
checkpoints: Checkpoint[];
}
Checkpoints
Long-running tasks can save checkpoints for resumability:
// Agent saves checkpoint during execution
await agent.saveCheckpoint({
processedItems: 500,
lastItemId: 'item-500',
intermediateResults: {...}
});
// If task fails and retries, it can resume from checkpoint
const checkpoint = await agent.getLatestCheckpoint();
const startFrom = checkpoint?.lastItemId || 'item-0';
Best Practices
1. Use Meaningful Names
// ✅ Good
name: 'Daily Sales Report - US Region'
name: 'Process Zendesk Tickets - Priority Queue'
// ❌ Bad
name: 'Task 1'
name: 'Do stuff'
2. Set Appropriate Timeouts
// Quick task - short timeout
settings: { timeoutMs: 30000 } // 30 seconds
// Long analysis - longer timeout
settings: { timeoutMs: 600000 } // 10 minutes
3. Configure Retries for Flaky Operations
settings: {
maxRetries: 3,
retryDelayMs: 5000 // Wait 5 seconds between retries
}
4. Use Dependencies for Pipelines
// ETL pipeline
const extract = await createTask('Extract');
const transform = await createTask('Transform', [extract.id]);
const load = await createTask('Load', [transform.id]);
5. Monitor with Webhooks
await client.webhooks.create({
url: 'https://your-app.com/webhooks',
events: ['task.completed', 'task.failed']
});
Pricing & Plans
| Feature | Starter | Pro | Business | Enterprise |
|---|---|---|---|---|
| Manual tasks | Yes | Yes | Yes | Yes |
| Scheduled tasks | - | Yes | Yes | Yes |
| Task dependencies | - | - | Yes | Yes |
| Task deadlines | - | - | Yes | Yes |
| Priority queuing | - | Yes | Yes | Yes |
Next: Learn about Schedules for automated task execution.