task-router

TotalClaw 作者 totalclaw

OpenClaw 多代理系统的分布式任务队列和代理协调器。通过能力匹配将任务路由到专门代理、跟踪任务生命周期、处理异步切换、重新平衡负载以及管理死信。在以下情况下使用:(1) 以编程方式或通过检测信号创建任务,(2) 根据功能将工作路由到专门代理,(3) 监视任务状态和完成情况,(4) 协调代理之间的多步骤工作流,(5) 在不阻塞主会话的情况下处理异步代理工作。

安装 / 下载方式

TotalClaw CLI推荐
totalclaw install totalclaw:totalclaw~capt-marbles-task-router-skill
cURL直接下载,无需登录
curl -fsSL https://skills.taituai.com/api/skills/totalclaw%3Atotalclaw~capt-marbles-task-router-skill/file -o capt-marbles-task-router-skill.md
## 概述(中文)

OpenClaw 多代理系统的分布式任务队列和代理协调器。通过能力匹配将任务路由到专门代理、跟踪任务生命周期、处理异步切换、重新平衡负载以及管理死信。在以下情况下使用:(1) 以编程方式或通过检测信号创建任务,(2) 根据功能将工作路由到专门代理,(3) 监视任务状态和完成情况,(4) 协调代理之间的多步骤工作流,(5) 在不阻塞主会话的情况下处理异步代理工作。

## 原文

# Task Router

Distributed task queue for OpenClaw multi-agent systems. Central coordination, async handoffs, capability-based routing.

## Quick Start

```bash
# Install skill
clawhub install task-router

# Register an agent
task agent register watson --capabilities "research analysis" --max-concurrent 3

# Create a task
task create --type research --title "Competitor analysis" --priority high

# Router runs automatically via heartbeat
# Check task status
task list --status pending
task show task-abc123
```

## What This Does

**Core Functions:**
- **Enqueue**: Create tasks from any session (main or sub-agent)
- **Route**: Match tasks to agents by capabilities
- **Track**: Monitor task lifecycle (pending → active → complete/failed)
- **Async Coordination**: Hand off work, check back later
- **Dead Letter**: Handle timeouts and failures
- **Rebalance**: Move stuck tasks, retry with fallbacks

**Use Cases:**
- Heartbeat creates research task → auto-routes to research agent
- Main agent spawns work → goes async, checks later
- Multi-step workflows: Task A output → Task B input
- Agent failure → task reassigned to backup agent
- Load balancing across multiple agents with same capabilities

## Configuration

### File Layout
```
~/.openclaw/task-router/
├── config.yaml           # Router settings, timeouts
├── agents.yaml           # Agent registry + capabilities
├── queue/                # Task state
│   ├── pending/          # Waiting for assignment
│   ├── active/           # Assigned to agent
│   ├── completed/        # Finished successfully
│   └── failed/           # Failed, exhausted retries
└── logs/
    └── router.log        # Routing decisions
```

### config.yaml
```yaml
router:
  check_interval: 30           # Seconds between router runs
  default_ttl: 3600            # Default task timeout
  max_retries: 2
  
  strategies:
    default: least-loaded      # round-robin | least-loaded | priority
    by_type:
      research: least-loaded
      image_gen: round-robin
      urgent: priority

  health:
    agent_timeout: 300           # Mark agent unhealthy after seconds
    task_timeout:
      warning: 1800              # Alert at 30 min
      critical: 3600             # Fail at 1 hour

  notifications:
    on_complete: true
    on_fail: true
    channels: [main_session]   # Could add Discord, etc.
```

### agents.yaml (auto-maintained)
```yaml
agents:
  watson:
    id: watson
    emoji: 🔬
    capabilities: [research, analysis, web_search]
    max_concurrent: 3
    current_tasks: [task-abc123, task-def456]
    stats:
      completed: 47
      failed: 2
      avg_duration: 180
    health:
      last_ping: 2026-02-13T09:15:00Z
      status: healthy
    
  picasso:
    id: picasso
    emoji: 🎨
    capabilities: [image_gen, image_edit]
    max_concurrent: 2
    current_tasks: []
```

## Task Schema

```yaml
id: task-abc123
type: research               # Matches agent capability
title: Research Gameye competitors
description: Deep competitive analysis

payload:
  query: Gameye vs competitors
  sources: [web, apollo]
  output_format: markdown
  
created_by: main             # Session label that created it
assigned_to: watson          # null until routed
assigned_by: router          # router | manual | agent

created_at: 2026-02-13T09:00:00Z
assigned_at: 2026-02-13T09:05:00Z
started_at: 2026-02-13T09:06:00Z
completed_at: null
expires_at: 2026-02-13T10:00:00Z  # created_at + ttl

priority: high               # low | normal | high | urgent
ttl: 3600                    # Seconds
retries: 0
max_retries: 2

dependencies: []             # Block until these complete
blocked_by: []               # Populated by router

status: assigned             # pending | assigned | running | complete | failed
result: null                 # Path to result file
error: null                  # Error message if failed

metadata:
  source: heartbeat
  tags: [gameye, competitors]
```

## CLI Commands

### Task Management
```bash
# Create task
task create --type research \
  --title "Research Gameye competitors" \
  --data '{"query": "Gameye pricing"}' \
  --priority high \
  --ttl 3600

# Create with dependencies
task create --type analysis \
  --title "Analyze research results" \
  --depends-on task-abc123

# List tasks
task list                    # All non-completed
task list --status pending
task list --assigned-to watson
task list --type research --limit 10
task list --created-after 2026-02-13

# Show task
task show task-abc123        # Full details + result preview

# Manage tasks
task cancel task-abc123      # Cancel pending or active
task retry task-abc123       # Move failed back to pending
task reprioritize task-abc123 --priority urgent

# Results
task result task-abc123      # View result file
task export --status completed --since 2026-02-13 > ~/reports/tasks.ndjson
```

### Agent Management
```bash
# Register agent (required before routing)
task agent register watson \
  --capabilities "research analysis web_search" \
  --max-concurrent 3 \
  --emoji 🔬

# Update agent
task agent update watson --add-capability "competitive-analysis"
task agent update watson --max-concurrent 5

# Check agent health
task agent status watson     # Current tasks, health, stats
task agent ping watson       # Health check ping

# List agents
task agent list              # All agents
task agent list --capable-of research

# Unregister
task agent unregister watson --reassign-tasks
```

### Router Control
```bash
# Status
task router status           # Queue depth, agent health

# Control flow
task router pause            # Stop new assignments
task router resume           # Resume routing
task router rebalance        # Redistribute stuck tasks

# Maintenance  
task router cleanup          # Archive old completed tasks
task router drain            # Finish active, no new pending
```

## Programmatic API

```typescript
import * as Task from "~/.openclaw/task-router/sdk";

// === Creating Tasks ===

// Simple create
const task = await Task.create({
  type: "research",
  title: "Competitor analysis",
  payload: { query: "Gameye vs competitors" }
});

// With options
const task = await Task.create({
  type: "image_gen",
  title: "Generate hero image",
  payload: { prompt: "Futuristic game server...", size: "1024x1024" },
  priority: "high",
  ttl: 1800,
  max_retries: 1,
  dependencies: [previousTaskId],  // Waits for these first
  created_by: "main"
});

// === Querying ===

// Get status
const status = await Task.status(task.id);
// { id, status, assigned_to, created_at, expires_at }

// Wait for completion (blocking)
const result = await Task.wait(task.id, { timeout: 300, pollInterval: 5 });

// List with filters
const pending = await Task.query({
  status: "pending",
  type: "research",
  priority: "high",
  limit: 10
});

const myTasks = await Task.query({
  created_by: "main",
  status: ["assigned", "running"]
});

// === Agent Integration ===

// Agent picks up work (if auto-assign disabled)
await Task.claim({
  agentId: "watson",
  capableOf: "research",
  limit: 1
});

// Complete task
await Task.complete(task.id, {
  result_path: "~/agents/watson/memory/results/competitors.md",
  summary: "Found 5 competitors: GameLift, Multiplay, Hathora, Edgegap, Agones",
  metadata: { competitors_count: 5 }
});

// Fail task
await Task.fail(task.id, {
  reason: "API quota exceeded",
  retryable: true  // Will auto-retry
});

// === Multi-Step Workflows ===

// Chain tasks
const analysisTask = await Task.chain(researchTask.id, {
  type: "analysis",
  title: "Analyze research findings",
  payload: { input_task: researchTask.id }
});

// Parallel tasks
const tasks = await Task.parallel([
  { type: "research", title: "Research A", payload: {} },
  { type: "research", title: "Research B", payload: {} },