Task

Task

Structured task execution with status tracking and tool integration

Overview

Tasks provide a way to organize and execute complex operations with your agents. They support status tracking, tool usage, and can be composed into larger workflows. Each task can have dependencies, execute specific actions, and maintain its own state throughout execution.

Creating Tasks

Tasks are created through agents using a simple prompt-based approach:

import { Agent } from '@astreus-ai/astreus';

const agent = await Agent.create({
  name: 'TaskAgent',
  model: 'gpt-4o'
});

// Create a task
const task = await agent.createTask({
  prompt: 'Analyze the TypeScript code and suggest performance improvements'
});

// Execute the task
const result = await agent.executeTask(task.id);
console.log(result.response);

Task Attributes

Tasks can be configured with the following attributes:

interface TaskRequest {
  prompt: string;              // The task instruction or query
  useTools?: boolean;          // Enable/disable tool usage (default: true)
  mcpServers?: MCPServerDefinition[]; // Task-level MCP servers
  plugins?: Array<{            // Task-level plugins
    plugin: Plugin;
    config?: PluginConfig;
  }>;
  attachments?: Array<{        // Files to attach to the task
    type: 'image' | 'pdf' | 'text' | 'markdown' | 'code' | 'json' | 'file';
    path: string;              // File path
    name?: string;             // Display name
    language?: string;         // Programming language (for code files)
  }>;
  schedule?: string;           // Simple schedule string (e.g., 'daily@09:00')
  metadata?: MetadataObject;   // Custom metadata for tracking
  
  // Sub-agent delegation options
  useSubAgents?: boolean;                        // Enable sub-agent delegation for this task
  subAgentDelegation?: 'auto' | 'manual' | 'sequential'; // Delegation strategy
  subAgentCoordination?: 'parallel' | 'sequential';      // How sub-agents coordinate
  taskAssignment?: Record<number, string>;               // Manual task assignment (agentId -> task)
}

Attribute Details

  • prompt: The main instruction or query for the task. This is the only required field.
  • useTools: Controls whether the task can use tools/plugins. Defaults to true (inherits from agent if not specified).
  • mcpServers: Task-specific MCP (Model Context Protocol) servers to enable for this task.
  • plugins: Task-specific plugins to register for this task execution.
  • attachments: Array of files to attach to the task. Supports images, PDFs, text files, code files, and more.
  • schedule: Simple schedule string for time-based execution (e.g., 'daily@09:00', 'weekly@friday@17:00'). Optional field that enables automatic scheduling.
  • metadata: Custom key-value pairs for organizing and tracking tasks (e.g., category, priority, tags).

Sub-Agent Integration

  • useSubAgents: Enable sub-agent delegation for this specific task. When true, the main agent will intelligently delegate portions of the task to its registered sub-agents.
  • subAgentDelegation: Strategy for task delegation:
    • 'auto': AI-powered intelligent task distribution based on sub-agent capabilities
    • 'manual': Explicit task assignment using taskAssignment mapping
    • 'sequential': Sub-agents work in sequence, building on previous results
  • subAgentCoordination: Coordination pattern for sub-agent execution:
    • 'parallel': Sub-agents work simultaneously for maximum efficiency
    • 'sequential': Sub-agents work in order with context passing between them
  • taskAssignment: Manual task assignment mapping (only used with subAgentDelegation: 'manual'). Maps agent IDs to specific task instructions.

Task Lifecycle

Tasks go through several states during execution:

type TaskStatus = 'pending' | 'in_progress' | 'completed' | 'failed';

Pending

Task is created but not yet started. Waiting for execution or dependencies.

In Progress

Task is actively being executed by the agent. Tools may be used during this phase.

Completed

Task has finished successfully with results available.

Failed

Task encountered an error during execution. Error details are available.

Example with Attachments and Tools

Here's a complete example showing tasks with file attachments and tool integration:

import { Agent } from '@astreus-ai/astreus';

// Create an agent
const agent = await Agent.create({
  name: 'CodeReviewAssistant',
  model: 'gpt-4o',
  vision: true // Enable vision for screenshots
});

// Code review task with multiple file types
const codeReviewTask = await agent.createTask({
  prompt: `Please perform a comprehensive code review:
    1. Check for security vulnerabilities
    2. Identify performance issues
    3. Suggest improvements for code quality
    4. Review the UI mockup for usability issues`,
  attachments: [
    { 
      type: 'code', 
      path: '/src/auth/login.ts', 
      name: 'Login Controller',
      language: 'typescript' 
    },
    { 
      type: 'code', 
      path: '/src/middleware/security.js', 
      name: 'Security Middleware',
      language: 'javascript' 
    },
    { 
      type: 'json', 
      path: '/package.json', 
      name: 'Package Dependencies' 
    },
    { 
      type: 'image', 
      path: '/designs/login-mockup.png', 
      name: 'Login UI Mockup' 
    },
    { 
      type: 'markdown', 
      path: '/docs/security-requirements.md', 
      name: 'Security Requirements' 
    }
  ],
  metadata: {
    type: 'code-review',
    priority: 'high',
    reviewer: 'ai-assistant'
  }
});

// Execute task with streaming
const result = await agent.executeTask(codeReviewTask.id, {
  model: 'gpt-4o',  // Override model for this task
  stream: true      // Enable streaming response
});

console.log('Code review completed:', result.response);

// Documentation task with text files
const docTask = await agent.createTask({
  prompt: 'Update the API documentation based on the latest code changes',
  attachments: [
    { type: 'text', path: '/api/routes.txt', name: 'API Routes' },
    { type: 'markdown', path: '/README.md', name: 'Current Documentation' }
  ]
});

// List tasks with attachments
const tasksWithFiles = await agent.listTasks({
  orderBy: 'createdAt',
  order: 'desc'
});

tasksWithFiles.forEach(task => {
  console.log(`Task ${task.id}: ${task.status}`);
  if (task.metadata?.attachments) {
    console.log(`  - Has attachments`);
  }
  if (task.completedAt) {
    console.log(`  - Completed: ${task.completedAt.toISOString()}`);
  }
});

Sub-Agent Task Delegation

Tasks now support sub-agent delegation directly through task creation and execution:

import { Agent } from '@astreus-ai/astreus';

// Create specialized sub-agents
const researcher = await Agent.create({
  name: 'ResearchBot',
  systemPrompt: 'You are an expert researcher who gathers comprehensive information.'
});

const writer = await Agent.create({
  name: 'WriterBot', 
  systemPrompt: 'You create engaging, well-structured content.'
});

const mainAgent = await Agent.create({
  name: 'ContentCoordinator',
  subAgents: [researcher, writer]
});

// Create task with automatic sub-agent delegation
const autoTask = await mainAgent.createTask({
  prompt: 'Research renewable energy trends and write a comprehensive report',
  useSubAgents: true,
  subAgentDelegation: 'auto',
  subAgentCoordination: 'sequential',
  metadata: { type: 'research-report', priority: 'high' }
});

// Create task with manual sub-agent assignment
const manualTask = await mainAgent.createTask({
  prompt: 'Create market analysis presentation',
  useSubAgents: true,
  subAgentDelegation: 'manual',
  subAgentCoordination: 'parallel',
  taskAssignment: {
    [researcher.id]: 'Research market data and competitor analysis',
    [writer.id]: 'Create presentation slides and executive summary'
  },
  metadata: { type: 'presentation', deadline: '2024-12-01' }
});

// Execute tasks - sub-agent coordination happens automatically
const autoResult = await mainAgent.executeTask(autoTask.id);
const manualResult = await mainAgent.executeTask(manualTask.id);

console.log('Auto-delegated result:', autoResult.response);
console.log('Manually-assigned result:', manualResult.response);

Alternative: Agent Methods for Sub-Agent Execution

You can also leverage sub-agents through agent methods for immediate execution:

// Direct execution with sub-agent delegation via agent.ask()
const result = await mainAgent.ask('Research renewable energy trends and write report', {
  useSubAgents: true,
  delegation: 'auto',
  coordination: 'sequential'
});

// Manual delegation with specific task assignments
const manualResult = await mainAgent.ask('Create market analysis presentation', {
  useSubAgents: true,
  delegation: 'manual',
  coordination: 'parallel',
  taskAssignment: {
    [researcher.id]: 'Research market data and competitor analysis',
    [writer.id]: 'Create presentation slides and executive summary'
  }
});

Benefits of Task-Level Sub-Agent Delegation

  • Persistent Configuration: Sub-agent settings are stored with the task and persist across sessions
  • Reproducible Workflows: Task definitions can be reused with consistent sub-agent behavior
  • Flexible Execution: Tasks can be executed immediately or scheduled for later with same sub-agent coordination
  • Audit Trail: Task metadata includes sub-agent delegation history for tracking and debugging

Managing Tasks

Tasks can be managed and tracked throughout their lifecycle:

// Update task with additional metadata
await agent.updateTask(task.id, {
  metadata: {
    ...task.metadata,
    progress: 50,
    estimatedCompletion: new Date()
  }
});

// Delete a specific task
await agent.deleteTask(task.id);

// Clear all tasks for an agent
const deletedCount = await agent.clearTasks();
console.log(`Deleted ${deletedCount} tasks`);

// Search tasks with filters
const pendingTasks = await agent.listTasks({
  status: 'pending',
  limit: 5
});

const recentTasks = await agent.listTasks({
  orderBy: 'completedAt',
  order: 'desc',
  limit: 10
});

How is this guide?