Astreus

Task

Structured task execution with status tracking and tool integration Learn the setup patterns, APIs, and practical examples needed to build reliable Astreus...

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
  graphId?: string;            // UUID - Graph this task belongs to
  graphNodeId?: string;        // UUID - Graph node creating this task
  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@07:00', 'weekly@monday@09:00')
  metadata?: MetadataObject;   // Custom metadata for tracking
  executionContext?: Record<string, unknown>; // Additional execution metadata
  useSubAgents?: boolean;                        // Enable sub-agent delegation for this task
  subAgentDelegation?: 'auto' | 'manual' | 'sequential'; // Delegation strategy
  subAgentCoordination?: 'parallel' | 'sequential';      // How sub-agents coordinate
  taskAssignment?: Record<string, string>;               // Manual task assignment (agentId UUID -> task)
}

Attribute Details

  • prompt: The main instruction or query for the task. This is the only required field.
  • graphId: UUID of the graph this task belongs to. Used when tasks are part of a graph workflow.
  • graphNodeId: UUID of the graph node that created this task. Used for tracking task origin in graph workflows.
  • 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@07:00', 'weekly@monday@09:00'). Optional field that enables automatic scheduling when used with graphs.
  • metadata: Custom key-value pairs for organizing and tracking tasks (e.g., category, priority, tags).
  • executionContext: Additional execution metadata as a record of key-value pairs. Useful for passing runtime context information.

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';
1

Pending

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

2

In Progress

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

3

Completed

Task has finished successfully with results available.

4

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
});

// Filter tasks by graph
const graphTasks = await agent.listTasks({
  graphId: 'graph-uuid-123',
  orderBy: 'createdAt',
  order: 'asc'
});

Response Types

Understanding task responses helps you handle execution results and track task lifecycle.

Task Object Response

Creating or retrieving a task returns a complete Task object:

const task = await agent.createTask({
  prompt: "Analyze this data",
  useTools: true,
  metadata: { priority: "high" }
});

// Response structure (Task interface):
{
  id: "550e8400-e29b-41d4-a716-446655440000",  // UUID string
  agentId: "agent-uuid-123",                    // UUID string
  graphId?: "graph-uuid-456",                   // UUID string if part of a graph
  graphNodeId?: "node-uuid-789",                // UUID string if created by graph node
  prompt: "Analyze this data",
  response?: "Analysis result...",              // Filled after execution
  status: "pending",                            // 'pending' | 'in_progress' | 'completed' | 'failed'
  metadata?: {
    priority: "high"
  },
  executionContext?: {},                        // Additional execution metadata
  createdAt: Date('2024-01-15T10:30:00Z'),
  updatedAt: Date('2024-01-15T10:30:00Z'),
  completedAt?: Date('2024-01-15T10:35:00Z')   // Filled after completion
}

Task Execution Response

Executing a task returns a TaskResponse with execution details:

const result = await agent.executeTask("task-uuid-123", {
  model: "gpt-4",
  stream: false
});

// Response structure (TaskResponse interface):
{
  task: {
    id: "task-uuid-123",
    agentId: "agent-uuid",
    graphId?: "graph-uuid",           // If part of a graph
    graphNodeId?: "node-uuid",        // If created by graph node
    prompt: "Analyze this data",
    response: "Analysis complete: The data shows a 15% increase...",
    status: "completed",
    metadata?: { priority: "high" },
    executionContext?: {},            // Additional execution metadata
    createdAt: Date('2024-01-15T10:30:00Z'),
    updatedAt: Date('2024-01-15T10:35:00Z'),
    completedAt: Date('2024-01-15T10:35:00Z')
  },
  response: "Analysis complete: The data shows a 15% increase in user engagement...",
  model?: "gpt-4",
  usage?: {
    promptTokens: 150,
    completionTokens: 300,
    totalTokens: 450
  }
}

Task List Response

Listing tasks returns an array of Task objects:

const tasks = await agent.listTasks({
  status: 'completed',
  orderBy: 'completedAt',
  order: 'desc',
  limit: 10,
  offset: 0,           // Pagination offset
  graphId: 'optional'  // Filter by graph ID (UUID)
});

// Response structure (Task[] array):
[
  {
    id: "task-uuid-1",
    agentId: "agent-uuid",
    graphId?: "graph-uuid",        // If part of a graph
    graphNodeId?: "node-uuid",     // If created by graph node
    prompt: "First task",
    response?: "First task completed",
    status: "completed",
    metadata?: {},
    executionContext?: {},
    createdAt: Date(...),
    updatedAt: Date(...),
    completedAt?: Date(...)
  },
  {
    id: "task-uuid-2",
    agentId: "agent-uuid",
    graphId?: "graph-uuid",
    graphNodeId?: "node-uuid",
    prompt: "Second task",
    response?: "Second task completed",
    status: "completed",
    metadata?: {},
    executionContext?: {},
    createdAt: Date(...),
    updatedAt: Date(...),
    completedAt?: Date(...)
  }
]

Update Task Response

Updating a task returns the updated Task object or null if not found:

const updated = await agent.updateTask("task-uuid", {
  metadata: { progress: 50, estimatedCompletion: new Date() }
});

// Response: Task object with updated fields or null
{
  id: "task-uuid",
  agentId: "agent-uuid",
  prompt: "Original prompt",
  status: "in_progress",
  metadata: {
    priority: "high",
    progress: 50,
    estimatedCompletion: Date('2024-01-15T12:00:00Z')
  },
  updatedAt: Date('2024-01-15T10:40:00Z'),
  ...
}

Get Task Response

Retrieving a specific task returns the Task object or null:

const task = await agent.getTask("task-uuid");

// Returns: Task object or null if not found

Delete Task Response

Deleting a task returns a boolean indicating success:

const deleted = await agent.deleteTask("task-uuid");
// Returns: true or false

Clear Tasks Response

Clearing all tasks returns the count of deleted tasks:

const deletedCount = await agent.clearTasks();
// Returns: 25 (number of tasks deleted)

Last updated: May 26, 2026