Simple Orchestration
Overview
Route a task to the most qualified resource—whether human, AI agent, or LLM—using capability-first routing. HumanOS automatically finds, verifies, and assigns the best match based on skills, availability, and cost.
Why HumanOS Orchestration?
- Capability-First: Routes to resources that can do the work, not just the cheapest
- Human + AI: Seamlessly mix humans, agents, and LLMs in workflows
- Automatic Fallbacks: If the first choice fails, HumanOS tries the next best option
- Provenance: Every routing decision is logged and auditable
- Cost-Aware: Among capable resources, HumanOS optimizes for cost
- Safety: Built-in guardrails prevent unqualified resources from executing tasks
Think of it like: A smart dispatcher that routes 911 calls to the right responder—not just the closest, but the one with the right skills and equipment.
How Orchestration Works
HumanOS follows a four-step routing process:
1. ANALYZE TASK
├─ Extract required capabilities
├─ Determine complexity and risk
└─ Set minimum qualification thresholds
2. FIND CANDIDATES
├─ Query Capability Graph for matches
├─ Filter by minimum capability weight
└─ Check availability and constraints
3. VERIFY & RANK
├─ Cryptographically verify capabilities
├─ Rank by capability match quality
└─ Consider cost among equals
4. ASSIGN & MONITOR
├─ Assign to top-ranked resource
├─ Monitor execution with telemetry
└─ Auto-escalate on errors or low confidence
SDK Examples
typescript:TypeScript
```typescript
import { HumanOS } from '@human/sdk';
async function orchestrateTask(taskDescription: string) {
try {
// Define the task
const task = await HumanOS.createTask({
description: taskDescription,
requiredCapabilities: ['typescript', 'react'], // What skills are needed
minimumCapabilityWeight: 0.75, // 75% confidence required
priority: 'normal',
deadline: new Date(Date.now() + 24 * 60 * 60 * 1000), // 24 hours
});
console.log(`Task created: ${task.id}`);
// HumanOS automatically routes to the best resource
const assignment = await HumanOS.routeTask(task.id);
console.log(`✅ Task routed successfully!`);
console.log(` Assigned to: ${assignment.assignee.name} (${assignment.assignee.type})`);
console.log(` Capability match: ${assignment.capabilityScore.toFixed(2)}`);
console.log(` Estimated cost: $${assignment.estimatedCost}`);
console.log(` Estimated time: ${assignment.estimatedDuration} minutes`);
// Monitor task execution
const result = await HumanOS.waitForTaskCompletion(task.id, {
onProgress: (progress) => {
console.log(`Progress: ${progress.percentComplete}%`);
},
onEscalation: (escalation) => {
console.warn(`⚠️ Task escalated: ${escalation.reason}`);
},
});
console.log(`Task completed: ${result.status}`);
return result;
} catch (error) {
console.error("Orchestration failed:", error);
throw error;
}
}
// Example: Route a code review task
orchestrateTask("Review PR #123 for security vulnerabilities");
```
python:Python
```python
from human_sdk import HumanOS
from datetime import datetime, timedelta
async def orchestrate_task(task_description: str):
try:
# Define the task
task = await HumanOS.create_task(
description=task_description,
required_capabilities=['python', 'data_analysis'],
minimum_capability_weight=0.8, # 80% confidence required
priority='high',
deadline=datetime.now() + timedelta(hours=12)
)
print(f"Task created: {task.id}")
# HumanOS automatically routes to the best resource
assignment = await HumanOS.route_task(task.id)
print(f"✅ Task routed successfully!")
print(f" Assigned to: {assignment.assignee.name} ({assignment.assignee.type})")
print(f" Capability match: {assignment.capability_score:.2f}")
print(f" Estimated cost: ${assignment.estimated_cost}")
print(f" Estimated time: {assignment.estimated_duration} minutes")
# Monitor task execution
result = await HumanOS.wait_for_task_completion(
task.id,
on_progress=lambda p: print(f"Progress: {p.percent_complete}%"),
on_escalation=lambda e: print(f"⚠️ Task escalated: {e.reason}")
)
print(f"Task completed: {result.status}")
return result
except Exception as e:
print(f"Orchestration failed: {e}")
raise
# Example: Route a data analysis task
# await orchestrate_task("Analyze Q4 sales data and identify trends")
```
go:Go
```go
package main
import (
"fmt"
"time"
"github.com/human/sdk-go/humanos"
)
func orchestrateTask(taskDescription string) (*humanos.TaskResult, error) {
// Define the task
task, err := humanos.CreateTask(humanos.CreateTaskRequest{
Description: taskDescription,
RequiredCapabilities: []string{"golang", "microservices"},
MinimumCapabilityWeight: 0.8,
Priority: "normal",
Deadline: time.Now().Add(48 * time.Hour),
})
if err != nil {
return nil, fmt.Errorf("failed to create task: %w", err)
}
fmt.Printf("Task created: %s\n", task.ID)
// HumanOS automatically routes to the best resource
assignment, err := humanos.RouteTask(task.ID)
if err != nil {
return nil, fmt.Errorf("failed to route task: %w", err)
}
fmt.Printf("✅ Task routed successfully!\n")
fmt.Printf(" Assigned to: %s (%s)\n", assignment.Assignee.Name, assignment.Assignee.Type)
fmt.Printf(" Capability match: %.2f\n", assignment.CapabilityScore)
fmt.Printf(" Estimated cost: $%.2f\n", assignment.EstimatedCost)
fmt.Printf(" Estimated time: %d minutes\n", assignment.EstimatedDuration)
// Monitor task execution
result, err := humanos.WaitForTaskCompletion(task.ID, humanos.WaitOptions{
OnProgress: func(p humanos.Progress) {
fmt.Printf("Progress: %d%%\n", p.PercentComplete)
},
OnEscalation: func(e humanos.Escalation) {
fmt.Printf("⚠️ Task escalated: %s\n", e.Reason)
},
})
if err != nil {
return nil, fmt.Errorf("task execution failed: %w", err)
}
fmt.Printf("Task completed: %s\n", result.Status)
return result, nil
}
// Example usage
// orchestrateTask("Optimize database query performance for user API")
```
REST API Example
POST /v1/humanos/tasks
Content-Type: application/json
Authorization: Bearer <YOUR_API_KEY>
{
"description": "Translate user manual from English to Spanish",
"requiredCapabilities": ["translation:en-es", "technical_writing"],
"minimumCapabilityWeight": 0.85,
"priority": "normal",
"deadline": "2026-01-15T18:00:00Z",
"constraints": {
"maxCost": 100.00,
"preferredAssigneeType": "human"
}
}
Response (201 Created):
{
"task": {
"id": "task:human:a1b2c3d4e5f6...",
"description": "Translate user manual from English to Spanish",
"status": "routing",
"createdAt": "2026-01-10T14:00:00Z"
},
"routing": {
"status": "in_progress",
"candidatesFound": 3,
"estimatedRoutingTime": "< 2 seconds"
}
}
Get Routing Result:
GET /v1/humanos/tasks/task:human:a1b2c3d4e5f6.../assignment
Authorization: Bearer <YOUR_API_KEY>
Response (200 OK):
{
"taskId": "task:human:a1b2c3d4e5f6...",
"assignee": {
"passportDid": "did:human:maria-garcia",
"name": "Maria Garcia",
"type": "human",
"verifiedCapabilities": [
{
"name": "translation:en-es",
"weight": 0.95,
"evidence": "5+ years professional translation, 200+ completed projects"
},
{
"name": "technical_writing",
"weight": 0.88,
"evidence": "Technical writing certification + portfolio"
}
]
},
"routing": {
"capabilityScore": 0.92,
"costScore": 0.75,
"overallScore": 0.87,
"alternatives": 2,
"routingReason": "Highest capability match with acceptable cost"
},
"estimated": {
"cost": 85.00,
"duration": 180,
"completionDate": "2026-01-10T17:00:00Z"
},
"provenance": {
"routedBy": "humanos:v1.2.0",
"routedAt": "2026-01-10T14:00:02Z",
"ledgerProof": "0x7a3f9b2c..."
}
}
Routing Strategies
HumanOS supports different routing strategies depending on your needs:
1. Capability-First (Default)
Routes to the most qualified resource, regardless of cost.
const assignment = await HumanOS.routeTask(task.id, {
strategy: 'capability-first',
minimumCapabilityWeight: 0.8,
});
Best for: High-stakes tasks, quality-critical work, safety-critical operations
2. Cost-Optimized
Among capable resources, choose the cheapest.
const assignment = await HumanOS.routeTask(task.id, {
strategy: 'cost-optimized',
minimumCapabilityWeight: 0.7, // Still requires minimum capability
maxCost: 50.00, // Hard cost limit
});
Best for: High-volume tasks, budget-constrained projects, repetitive work
3. Speed-Optimized
Routes to the fastest available resource.
const assignment = await HumanOS.routeTask(task.id, {
strategy: 'speed-optimized',
minimumCapabilityWeight: 0.75,
maxWaitTime: 60, // Must start within 60 seconds
});
Best for: Time-sensitive tasks, urgent requests, SLA-bound work
4. Balanced
Balances capability, cost, and speed using a weighted score.
const assignment = await HumanOS.routeTask(task.id, {
strategy: 'balanced',
weights: {
capability: 0.5,
cost: 0.3,
speed: 0.2,
},
});
Best for: General-purpose tasks, balanced priorities
Automatic Fallbacks
If the first-choice resource fails or rejects a task, HumanOS automatically tries the next best option:
const assignment = await HumanOS.routeTask(task.id, {
fallbackStrategy: 'auto',
maxFallbackAttempts: 3, // Try up to 3 alternatives
escalateOnFailure: true, // Escalate to human if all fail
});
Fallback triggers:
- Resource is unavailable or offline
- Resource rejects the task
- Task execution fails with an error
- Confidence drops below threshold during execution
Monitoring & Telemetry
Track task execution in real-time:
// Subscribe to task events
const subscription = HumanOS.subscribeToTask(task.id, {
onProgress: (event) => {
console.log(`Progress: ${event.percentComplete}%`);
console.log(` Current step: ${event.currentStep}`);
console.log(` Confidence: ${event.confidence}`);
},
onConfidenceDrop: (event) => {
console.warn(`⚠️ Confidence dropped to ${event.confidence}`);
// Maybe escalate to human review
},
onEscalation: (event) => {
console.warn(`🚨 Task escalated: ${event.reason}`);
console.log(` Escalated to: ${event.escalatedTo}`);
},
onComplete: (event) => {
console.log(`✅ Task completed: ${event.status}`);
console.log(` Duration: ${event.duration} minutes`);
console.log(` Cost: $${event.actualCost}`);
},
});
Human-in-the-Loop Integration
HumanOS makes it easy to require human approval for critical decisions:
const assignment = await HumanOS.routeTask(task.id, {
humanApprovalRequired: true, // Require human to approve routing
approverRole: 'manager', // Who can approve
approvalTimeout: 600, // 10 minutes to approve
});
// Task will wait for approval before executing
See the Human-in-the-Loop pattern for more details.
building:Enterprise Workflows|Route internal tasks like code reviews, document approvals, and data analysis to qualified employees
bot:Multi-Agent Systems|Orchestrate complex workflows across multiple specialized AI agents
cloud:Hybrid Workforces|Seamlessly route between humans, agents, and LLMs based on task requirements
network:Distributed Teams|Route tasks to the right person regardless of location or timezone
do:Always verify capabilities before routing critical tasks
do:Log all routing decisions with provenance for audit trails
do:Set minimum capability thresholds appropriate for risk level
do:Implement automatic escalation for low-confidence execution
dont:Route high-stakes tasks purely on cost optimization
dont:Skip capability verification to save processing time
dont:Ignore escalation signals from agents or humans
dont:Allow tasks to run indefinitely without timeout safeguards
Next Steps
- Learn about Human-in-the-Loop for approval workflows
- Explore Multi-Agent Workflows for complex orchestration
- Understand Provenance Tracking for audit trails