UFO Documentation

UFO³: Weaving the Digital Agent Galaxy

10,049 stars Python Python 101 files · ~388,656 tokens #agent#automation#copilot#gui#llm#windows
RAW Doc

Technical Documentation: microsoft/UFO

ℹ️ Provenance: Multi-Tier Ingestion · CodeWiki Reference

Overview (README.md)

**UFO³** : Weaving the Digital Agent Galaxy


🎯 Choose Your Path

| ### UFO³ Multi-Device Agent Galaxy
✨ NEW & RECOMMENDED

Perfect for:

  • 🔗 Cross-device collaboration workflows
  • 📊 Complex multi-step automation
  • 🎯 DAG-based task orchestration
  • 🌍 Heterogeneous platform integration

Key Features:

  • Constellation: Task decomposition into executable DAGs
  • Dynamic DAG editing for adaptive workflow evolution
  • Asynchronous execution with parallel task coordination
  • Unified AIP protocol for secure agent communication

📖 Galaxy Documentation →
📖 Galaxy Quick Start → ⭐ Online Docs | ### UFO² Desktop AgentOS
STABLE & BATTLE-TESTED

Perfect for:

  • 💻 Single Windows automation
  • ⚡ Quick task execution
  • 🎓 Learning agent basics
  • 🛠️ Simple workflows

Key Features:

  • Deep Windows OS integration
  • Hybrid GUI + API actions
  • Proven reliability
  • Easy setup
  • Can serve as Galaxy device agent

📖 UFO² Documentation → |
| --- | --- |


🎬 See UFO³ Galaxy in Action

Watch how UFO³ Galaxy orchestrates complex workflows across multiple devices:


🌟 What's New in UFO³?

Evolution Timeline

mermaid
%%{init: {'theme':'base', 'themeVariables': { 'primaryColor':'#E8F4F8','primaryTextColor':'#1A1A1A','primaryBorderColor':'#7CB9E8','lineColor':'#A8D5E2','secondaryColor':'#B8E6F0','tertiaryColor':'#D4F1F4','fontSize':'16px','fontFamily':'Segoe UI, Arial, sans-serif'}}}%%
graph LR
    A["<b>🎈 UFO</b><br/><span style='font-size:14px'>February 2024</span><br/><span style='font-size:13px; color:#666'><i>GUI Agent for Windows</i></span>"] 
    B["<b>🖥️ UFO²</b><br/><span style='font-size:14px'>April 2025</span><br/><span style='font-size:13px; color:#666'><i>Desktop AgentOS</i></span>"]
    C["<b>🌌 UFO³ Galaxy</b><br/><span style='font-size:14px'>November 2025</span><br/><span style='font-size:13px; color:#666'><i>Multi-Device Orchestration</i></span>"]
    
    A -->|Evolve| B
    B -->|Scale| C
    
    style A fill:#E8F4F8,stroke:#7CB9E8,stroke-width:2.5px,color:#1A1A1A,rx:15,ry:15
    style B fill:#C5E8F5,stroke:#5BA8D0,stroke-width:2.5px,color:#1A1A1A,rx:15,ry:15
    style C fill:#A4DBF0,stroke:#3D96BE,stroke-width:2.5px,color:#1A1A1A,rx:15,ry:15

🚀 UFO³ = **Galaxy** (Multi-Device Orchestration) + **UFO²** (Device Agent)

UFO³ introduces Galaxy, a revolutionary multi-device orchestration framework that coordinates intelligent agents across heterogeneous platforms. Built on five tightly integrated design principles:

  1. 🌟 Declarative Decomposition into Dynamic DAG - Requests decomposed into structured DAG with TaskStars and dependencies for automated scheduling and runtime rewriting

  2. 🔄 Continuous Result-Driven Graph Evolution - Living constellation that adapts to execution feedback through controlled rewrites and dynamic adjustments

  3. ⚡ Heterogeneous, Asynchronous & Safe Orchestration - Capability-based device matching with async execution, safe locking, and formally verified correctness

  4. 🔌 Unified Agent Interaction Protocol (AIP) - WebSocket-based secure coordination layer with fault tolerance and automatic reconnection

  5. 🛠️ Template-Driven MCP-Empowered Device Agents - Lightweight toolkit for rapid agent development with MCP integration for tool augmentation

Aspect UFO² UFO³ Galaxy
Architecture Single Windows Agent Multi-Device Orchestration
Task Model Sequential ReAct Loop DAG-based Constellation Workflows
Scope Single device, multi-app Multi-device, cross-platform
Coordination HostAgent + AppAgents ConstellationAgent + TaskOrchestrator
Device Support Windows Desktop Windows, Linux, Android (more coming)
Task Planning Application-level Device-level with dependencies
Execution Sequential Parallel DAG execution
Device Agent Role Standalone Can serve as Galaxy device agent
Complexity Simple to Moderate Simple to Very Complex
Learning Curve Low Moderate
Cross-Device Collaboration ❌ Not Supported ✅ Core Feature
Setup Difficulty ✅ Easy ⚠️ Moderate
Status ✅ LTS (Long-Term Support) ⚡ Active Development

🎓 Migration Path

For UFO² Users:

  1. ✅ Keep using UFO² – Fully supported, actively maintained
  2. 🔄 Gradual adoption – Galaxy can use UFO² as Windows device agent
  3. 📈 Scale up – Move to Galaxy when you need multi-device capabilities
  4. 📚 Learning resources – Migration Guide

✨ Capabilities at a Glance

🌌 Galaxy Framework – What's Different?

| #### 🌟 Constellation Planning

text
User Request
     ↓
ConstellationAgent
     ↓
  [Task DAG]
   /   |   \
Task1 Task2 Task3
(Win) (Linux)(Mac)

Benefits:

  • Cross-device dependency tracking
  • Parallel execution optimization
  • Cross-device dataflow management | #### 🎯 Device Assignment
text
Selection Criteria
  • Platform
  • Resource
  • Task requirements
  • Performance history
        ↓
  Auto-Assignment
        ↓
  Optimal Devices

Smart Matching:

  • Capability-based selection
  • Real-time resource monitoring
  • Dynamic reallocation | #### 📊 Orchestration
text
Task1 → Running  ✅
Task2 → Pending  ⏸️
Task3 → Running  🔄
        ↓
   Completion
        ↓
   Final Report

Orchestration:

  • Real-time status updates
  • Automatic error recovery
  • Progress tracking with feedback |
    | --- | --- | --- |

🪟 UFO² Desktop AgentOS – Core Strengths

UFO² serves dual roles: standalone Windows automation and Galaxy device agent for Windows platforms.

As Galaxy Device Agent:

  • Receives tasks from ConstellationAgent via Galaxy orchestration layer
  • Executes Windows-specific operations using proven UFO² capabilities
  • Reports status and results back to TaskOrchestrator
  • Participates in cross-device workflows seamlessly

🚀 Quick Start Guide

Choose your path and follow the detailed setup guide:

| ### 🌌 Galaxy Quick Start

For cross-device orchestration

powershell
# 1. Install
pip install -r requirements.txt

# 2. Configure ConstellationAgent
copy config\galaxy\agent.yaml.template config\galaxy\agent.yaml
# Edit and add your API keys

# 3. Configure devices
# Edit config\galaxy\devices.yaml to register your devices

# 4. Start device agents (with platform flags)
# Windows: Start server + client
# Linux: Start server + MCP servers + client  
# Mobile (Android): Start server + MCP servers + client
# See platform-specific guides for detailed setup

# 5. Launch Galaxy
python -m galaxy --interactive

📖 Complete Guide:

For Windows automation

powershell
# 1. Install
pip install -r requirements.txt

# 2. Configure
copy config\ufo\agents.yaml.template config\ufo\agents.yaml
# Edit and add your API keys

# 3. Run
python -m ufo --task <task_name>

📖 Complete Guide:

📋 Common Configuration

Both frameworks require LLM API configuration. Choose your provider:

OpenAI Configuration

For Galaxy (config/galaxy/agent.yaml):

yaml
CONSTELLATION_AGENT:
  REASONING_MODEL: false
  API_TYPE: "openai"
  API_BASE: "https://api.openai.com/v1/chat/completions"
  API_KEY: "sk-your-key-here"
  API_MODEL: "gpt-4o"

For UFO² (config/ufo/agents.yaml):

yaml
VISUAL_MODE: True
API_TYPE: "openai"
API_BASE: "https://api.openai.com/v1/chat/completions"
API_KEY: "sk-your-key-here"
API_MODEL: "gpt-4o"

Azure OpenAI Configuration

For Galaxy (config/galaxy/agent.yaml):

yaml
CONSTELLATION_AGENT:
  REASONING_MODEL: false
  API_TYPE: "aoai"
  API_BASE: "https://YOUR-RESOURCE.openai.azure.com"
  API_KEY: "your-azure-key"
  API_MODEL: "gpt-4o"
  API_DEPLOYMENT_ID: "your-deployment-id"

For UFO² (config/ufo/agents.yaml):

yaml
VISUAL_MODE: True
API_TYPE: "aoai"
API_BASE: "https://YOUR-RESOURCE.openai.azure.com"
API_KEY: "your-azure-key"
API_MODEL: "gpt-4o"
API_DEPLOYMENT_ID: "your-deployment-id"

💡 More LLM Options: See Model Configuration Guide for Qwen, Gemini, Claude, and more.


📚 Documentation Structure

| ### 🌌 Galaxy Documentation

📖 Technical Documentation:

📖 Online Docs:


📢 Latest Updates

2025-11 – UFO³ Galaxy Framework Released 🌌

Major Research Breakthrough: Multi-Device Orchestration System

  • 🌟 Declarative DAG Decomposition: TaskConstellation structure for workflow logic and dependencies
  • 🔄 Dynamic Graph Evolution: Living constellation that adapts through controlled rewrites
  • 🎯 Heterogeneous Orchestration: Safe, asynchronous execution with capability-based device matching
  • 🔌 Unified AIP Protocol: WebSocket-based secure agent coordination with fault tolerance
  • 🛠️ MCP-Empowered Agent Framework: Template-driven toolkit for rapid device agent development
  • 📄 Research Paper: UFO³: Weaving the Digital Agent Galaxy

Key Features:

  • First multi-device orchestration framework for GUI agents
  • Result-driven adaptive execution instead of rigid workflows
  • Model Context Protocol (MCP) integration for tool augmentation
  • Formally verified correctness and concurrency safety guarantees

2025-04 – UFO² v2.0.0

  • 📅 UFO² Desktop AgentOS released
  • 🏗️ Enhanced architecture with AgentOS concept
  • 📄 Technical Report published
  • ✅ Entered Long-Term Support (LTS) status

2024-02 – Original UFO

  • 🎈 First UFO release - UI-Focused agent for Windows
  • 📄 Original Paper
  • 🌍 Wide media coverage and adoption

📚 Citation

If you use UFO³ Galaxy or UFO² in your research, please cite the relevant papers:

UFO³ Galaxy Framework (2025)

bibtex
@article{zhang2025ufo3,
  title={UFO$^3$: Weaving the Digital Agent Galaxy}, 
  author = {Zhang, Chaoyun and Li, Liqun and Huang, He and Ni, Chiming and Qiao, Bo and Qin, Si and Kang, Yu and Ma, Minghua and Lin, Qingwei and Rajmohan, Saravan and Zhang, Dongmei},
  journal = {arXiv preprint arXiv:2511.11332},
  year    = {2025},
}

UFO² Desktop AgentOS (2025)

bibtex
@article{zhang2025ufo2,
  title   = {{UFO2: The Desktop AgentOS}},
  author  = {Zhang, Chaoyun and Huang, He and Ni, Chiming and Mu, Jian and Qin, Si and He, Shilin and Wang, Lu and Yang, Fangkai and Zhao, Pu and Du, Chao and Li, Liqun and Kang, Yu and Jiang, Zhao and Zheng, Suzhen and Wang, Rujia and Qian, Jiaxu and Ma, Minghua and Lou, Jian-Guang and Lin, Qingwei and Rajmohan, Saravan and Zhang, Dongmei},
  journal = {arXiv preprint arXiv:2504.14603},
  year    = {2025}
}

Original UFO (2024)

bibtex
@article{zhang2024ufo,
  title   = {{UFO: A UI-Focused Agent for Windows OS Interaction}},
  author  = {Zhang, Chaoyun and Li, Liqun and He, Shilin and Zhang, Xu and Qiao, Bo and Qin, Si and Ma, Minghua and Kang, Yu and Lin, Qingwei and Rajmohan, Saravan and Zhang, Dongmei and Zhang, Qi},
  journal = {arXiv preprint arXiv:2402.07939},
  year    = {2024}
}

🌐 Media & Community

Media Coverage:

Community:


Microsoft Research:

  • TaskWeaver – Code-first LLM agent framework for data analytics and task automation

GUI Agent Research:

Multi-Agent Systems:

  • UFO³ Galaxy represents a novel approach to multi-device orchestration, introducing the Constellation framework for coordinating heterogeneous agents across platforms
  • Builds on multi-agent coordination research while addressing unique challenges of cross-device GUI automation

Benchmarks:


💡 FAQ

🤔 Should I use Galaxy or UFO²?

Start with UFO² if:

  • You only need Windows automation
  • You want quick setup and learning
  • Tasks are relatively simple

Choose Galaxy if:

  • You need cross-device coordination
  • Tasks are complex and multi-step
  • You want advanced orchestration
  • You're comfortable with active development

Hybrid approach if:

  • You want best of both worlds
  • Some tasks are simple (UFO²), some complex (Galaxy)
  • You're gradually migrating

⚠️ Will UFO² be deprecated?

No! UFO² has entered Long-Term Support (LTS) status:

  • ✅ Actively maintained
  • ✅ Bug fixes and security updates
  • ✅ Performance improvements
  • ✅ Full community support
  • ✅ No plans for deprecation

UFO² is the stable, proven solution for Windows automation.

🔄 How do I migrate from UFO² to Galaxy?

Migration is gradual and optional:

  1. Phase 1: Learn – Understand Galaxy concepts
  2. Phase 2: Experiment – Try Galaxy with non-critical tasks
  3. Phase 3: Hybrid – Use both frameworks
  4. Phase 4: Migrate – Gradually move complex tasks to Galaxy

No forced migration! Continue using UFO² as long as it meets your needs.

See Migration Guide for details.

🎯 Can Galaxy do everything UFO² does?

Functionally: Yes. Galaxy can use UFO² as a Windows device agent.

Practically: It depends.

  • For simple Windows tasks: UFO² standalone is easier and more streamlined
  • For complex workflows: Galaxy orchestrates UFO² with other device agents

Recommendation: Use the right tool for the job. UFO² can work standalone or as Galaxy's Windows device agent.

📊 How mature is Galaxy?

Status: Active Development 🚧

Stable:

  • ✅ Core architecture
  • ✅ DAG orchestration
  • ✅ Basic multi-device support
  • ✅ Event system

In Development:

  • 🔨 Advanced device types
  • 🔨 Enhanced monitoring
  • 🔨 Performance optimization
  • 🔨 Extended documentation

Recommendation: Great for experimentation and non-critical workflows.

🔧 Can I extend or customize?

Both frameworks are highly extensible:

UFO²:

  • Custom actions and automators
  • Custom knowledge sources (RAG)
  • Custom control detectors
  • Custom evaluation metrics

Galaxy:

  • Custom agents
  • Custom device types
  • Custom orchestration strategies
  • Custom visualization components

See respective documentation for extension guides.

🤝 How can I contribute?

We welcome contributions to both UFO² and Galaxy!

Ways to contribute:

  • 🐛 Report bugs and issues
  • 💡 Suggest features and improvements
  • 📝 Improve documentation
  • 🧪 Add tests and examples
  • 🔧 Submit pull requests

See CONTRIBUTING.md for guidelines.


⚠️ Disclaimer & License

Disclaimer: By using this software, you acknowledge and agree to the terms in DISCLAIMER.md.

License: This project is licensed under the MIT License.

Trademarks: Use of Microsoft trademarks follows Microsoft's Trademark Guidelines.




Documents Docs Index (`documents/docs/index.md`)

Welcome to UFO³ Documentation





📖 About This Documentation

Welcome to the official documentation for UFO³, Microsoft's open-source framework for intelligent automation across devices and platforms. Whether you're looking to automate Windows applications or orchestrate complex workflows across multiple devices, this documentation will guide you through every step.

What you'll find here:


🎯 Choose Your Path

UFO³ consists of two complementary frameworks. Choose the one that best fits your needs, or use both together!

Framework Best For Key Strength Get Started
🌌 Galaxy ✨ NEW & RECOMMENDED Cross-device workflowsComplex automationParallel execution Multi-device orchestrationDAG-based planningReal-time monitoring Quick Start →
🪟 UFO² ⚡ STABLE & LTS Windows automationQuick tasksLearning basics Deep Windows integrationHybrid GUI + APIStable & reliable Quick Start →

🤔 Decision Guide

Question Galaxy UFO²
Need cross-device collaboration? ✅ ❌
Complex multi-step workflows? ✅ ⚠️ Limited
Windows-only automation? ✅ ✅ Optimized
Quick setup & learning? ⚠️ Moderate ✅ Easy
Stable & reliable? 🚧 Active Dev ✅ LTS

🌟 What's New in UFO³?

UFO³ is a scalable, universal cross-device agent framework that enables you to develop new device agents for different platforms and applications. Through the Agent Interaction Protocol (AIP), custom device agents can seamlessly integrate into UFO³ Galaxy for coordinated multi-device orchestration.

Evolution Timeline

mermaid
%%{init: {'theme':'base', 'themeVariables': { 'primaryColor':'#E8F4F8','primaryTextColor':'#1A1A1A','primaryBorderColor':'#7CB9E8','lineColor':'#A8D5E2','secondaryColor':'#B8E6F0','tertiaryColor':'#D4F1F4','fontSize':'16px','fontFamily':'Segoe UI, Arial, sans-serif'}}}%%
graph LR
    A["<b>🎈 UFO</b><br/><span style='font-size:14px'>February 2024</span><br/><span style='font-size:13px; color:#666'><i>GUI Agent for Windows</i></span>"] 
    B["<b>🖥️ UFO²</b><br/><span style='font-size:14px'>April 2025</span><br/><span style='font-size:13px; color:#666'><i>Desktop AgentOS</i></span>"]
    C["<b>🌌 UFO³ Galaxy</b><br/><span style='font-size:14px'>November 2025</span><br/><span style='font-size:13px; color:#666'><i>Multi-Device Orchestration</i></span>"]
    
    A -->|Evolve| B
    B -->|Scale| C
    
    style A fill:#E8F4F8,stroke:#7CB9E8,stroke-width:2.5px,color:#1A1A1A,rx:15,ry:15
    style B fill:#C5E8F5,stroke:#5BA8D0,stroke-width:2.5px,color:#1A1A1A,rx:15,ry:15
    style C fill:#A4DBF0,stroke:#3D96BE,stroke-width:2.5px,color:#1A1A1A,rx:15,ry:15

🚀 UFO³ = **Galaxy** (Multi-Device Orchestration) + **UFO²** (Device Agent)

UFO³ introduces Galaxy, a revolutionary multi-device orchestration framework that coordinates intelligent agents across heterogeneous platforms. Built on five tightly integrated design principles:

  1. 🌟 Declarative Decomposition into Dynamic DAG - Requests decomposed into structured DAG with TaskStars and dependencies for automated scheduling and runtime rewriting

  2. 🔄 Continuous Result-Driven Graph Evolution - Living constellation that adapts to execution feedback through controlled rewrites and dynamic adjustments

  3. ⚡ Heterogeneous, Asynchronous & Safe Orchestration - Capability-based device matching with async execution, safe locking, and formally verified correctness

  4. 🔌 Unified Agent Interaction Protocol (AIP) - WebSocket-based secure coordination layer with fault tolerance and automatic reconnection

  5. 🛠️ Template-Driven MCP-Empowered Device Agents - Lightweight toolkit for rapid agent development with MCP integration for tool augmentation

Aspect UFO² UFO³ Galaxy
Architecture Single Windows Agent Multi-Device Orchestration
Task Model Sequential ReAct Loop DAG-based Constellation Workflows
Scope Single device, multi-app Multi-device, cross-platform
Coordination HostAgent + AppAgents ConstellationAgent + TaskOrchestrator
Device Support Windows Desktop Windows, Linux, macOS, Android, Web
Task Planning Application-level Device-level with dependencies
Execution Sequential Parallel DAG execution
Device Agent Role Standalone Can serve as Galaxy device agent
Complexity Simple to Moderate Simple to Very Complex
Learning Curve Low Moderate
Cross-Device Collaboration ❌ Not Supported ✅ Core Feature
Setup Difficulty ✅ Easy ⚠️ Moderate
Status ✅ LTS (Long-Term Support) ⚡ Active Development

🎓 Migration Path

For UFO² Users:

  1. ✅ Keep using UFO² – Fully supported, actively maintained
  2. 🔄 Gradual adoption – Galaxy can use UFO² as Windows device agent
  3. 📈 Scale up – Move to Galaxy when you need multi-device capabilities
  4. 📚 Learning resources – Migration Guide

✨ Capabilities at a Glance

🌌 Galaxy Framework – What's Different?

🌟 Constellation Planning

text
User Request
     ↓
ConstellationAgent
     ↓
  [Task DAG]
   /   |   \
Task1 Task2 Task3
(Win) (Linux)(Mac)

Benefits:

  • Cross-device dependency tracking
  • Parallel execution optimization
  • Cross-device dataflow management

🎯 Device Assignment

text
Selection Criteria
  • Platform
  • Resource
  • Task requirements
  • Performance history
        ↓
  Auto-Assignment
        ↓
  Optimal Devices

Smart Matching:

  • Capability-based selection
  • Real-time resource monitoring
  • Dynamic reallocation

📊 Orchestration

text
Task1 → Running  ✅
Task2 → Pending  ⏸️
Task3 → Running  🔄
        ↓
   Completion
        ↓
   Final Report

Orchestration:

  • Real-time status updates
  • Automatic error recovery
  • Progress tracking with feedback

🪟 UFO² Desktop AgentOS – Core Strengths

UFO² serves dual roles: standalone Windows automation and Galaxy device agent for Windows platforms.

Feature Description Documentation
Deep OS Integration Windows UIA, Win32, WinCOM native control Learn More
Hybrid Actions GUI clicks + API calls for optimal performance Learn More
Speculative Multi-Action Batch predictions → 51% fewer LLM calls Learn More
Visual + UIA Detection Hybrid control detection for robustness Learn More
Knowledge Substrate RAG with docs, demos, execution traces Learn More
Device Agent Role Can serve as Windows executor in Galaxy orchestration Learn More

As Galaxy Device Agent:

  • Receives tasks from ConstellationAgent through Galaxy orchestration layer
  • Executes Windows-specific operations using proven UFO² capabilities
  • Reports status and results back to TaskOrchestrator
  • Seamlessly participates in cross-device workflows

🏗️ Architecture

UFO³ Galaxy – Multi-Device Orchestration

Component Role
ConstellationAgent Plans and decomposes tasks into DAG workflows
TaskConstellation DAG representation with TaskStar nodes and dependencies
Device Pool Manager Matches tasks to capable devices dynamically
TaskOrchestrator Coordinates parallel execution and handles data flow
Event System Real-time monitoring with observer pattern

📖 Learn More →

UFO² – Desktop AgentOS

Component Role
HostAgent Desktop orchestrator, application lifecycle management
AppAgents Per-application executors with hybrid GUI–API actions
Knowledge Substrate RAG-enhanced learning from docs & execution history
Speculative Executor Multi-action prediction for efficiency

📖 Learn More →


🚀 Quick Start

Ready to dive in? Follow these guides to get started with your chosen framework:

🌌 Galaxy Quick Start (Multi-Device Orchestration)

Perfect for complex workflows across multiple devices and platforms.

bash
# 1. Install dependencies
pip install -r requirements.txt

# 2. Configure agents (see detailed guide for API key setup)
copy config\galaxy\agent.yaml.template config\galaxy\agent.yaml
copy config\ufo\agents.yaml.template config\ufo\agents.yaml

# 3. Start device agents
python -m ufo.server.app --port 5000
python -m ufo.client.client --ws --ws-server ws://localhost:5000/ws --client-id device_1 --platform windows

# 4. Launch Galaxy
python -m galaxy --interactive

📖 Complete Galaxy Quick Start Guide →
⚙️ Galaxy Configuration Details →

🪟 UFO² Quick Start (Windows Automation)

Perfect for Windows-only automation tasks with quick setup.

bash
# 1. Install
pip install -r requirements.txt

# 2. Configure (add your API keys)
copy config\ufo\agents.yaml.template config\ufo\agents.yaml

# 3. Run
python -m ufo --task <task_name>

📖 Complete UFO² Quick Start Guide →
⚙️ UFO² Configuration Details →


📚 Documentation Navigation

🎯 Getting Started

Start here if you're new to UFO³:

Guide Description Framework
Galaxy Quick Start Set up multi-device orchestration in 10 minutes 🌌 Galaxy
UFO² Quick Start Start automating Windows in 5 minutes 🪟 UFO²
Linux Agent Quick Start Automate Linux systems 🐧 Linux
Mobile Agent Quick Start Automate Android devices via ADB 📱 Mobile
Choosing Your Path Decision guide for selecting the right framework Both

🏗️ Core Architecture

Understand how UFO³ works under the hood:

Topic Description Framework
Galaxy Overview Multi-device orchestration architecture 🌌 Galaxy
UFO² Overview Desktop AgentOS architecture and concepts 🪟 UFO²
Task Constellation DAG-based workflow representation 🌌 Galaxy
ConstellationAgent Intelligent task planner and decomposer 🌌 Galaxy
Task Orchestrator Execution engine and coordinator 🌌 Galaxy
AIP Protocol Agent communication protocol 🌌 Galaxy

⚙️ Configuration & Setup

Configure your agents, models, and environments:

Topic Description Framework
Agent Configuration LLM and agent settings Both
Galaxy Devices Device pool and capability management 🌌 Galaxy
Model Providers Supported LLMs (OpenAI, Azure, Qwen, etc.) Both

🎓 Tutorials & Examples

Learn through practical examples in the documentation:

Topic Description Framework
Creating App Agents Build custom application agents 🪟 UFO²
Multi-Action Prediction Efficient batch predictions 🪟 UFO²
Knowledge Substrate RAG-enhanced learning 🪟 UFO²

🔧 Advanced Topics

Deep dive into powerful features:

Topic Description Framework
Multi-Action Prediction Batch actions for 51% fewer LLM calls 🪟 UFO²
Hybrid Detection Visual + UIA control detection 🪟 UFO²
Knowledge Substrate RAG-enhanced learning 🪟 UFO²
Constellation Agent Task planning and decomposition 🌌 Galaxy
Task Orchestrator Execution coordination 🌌 Galaxy

🛠️ Development & Extension

Customize and extend UFO³:

Topic Description
Project Structure Understand the codebase layout
Creating Custom Device Agents Build device agents for new platforms (mobile, web, IoT, etc.)
Creating App Agents Build custom application agents
Contributing Guide How to contribute to UFO³

❓ Support & Troubleshooting

Get help when you need it:

Resource What You'll Find
FAQ Common questions and answers
GitHub Discussions Community Q&A
GitHub Issues Bug reports and feature requests

📊 Feature Matrix

Feature UFO² Desktop AgentOS UFO³ Galaxy Winner
Windows Automation ⭐⭐⭐⭐⭐ Optimized ⭐⭐⭐⭐ Supported UFO²
Cross-Device Tasks ❌ Not supported ⭐⭐⭐⭐⭐ Core feature Galaxy
Setup Complexity ⭐⭐⭐⭐⭐ Very easy ⭐⭐⭐ Moderate UFO²
Learning Curve ⭐⭐⭐⭐⭐ Gentle ⭐⭐⭐ Moderate UFO²
Task Complexity ⭐⭐⭐ Good ⭐⭐⭐⭐⭐ Excellent Galaxy
Parallel Execution ❌ Sequential ⭐⭐⭐⭐⭐ Native DAG Galaxy
Stability ⭐⭐⭐⭐⭐ Stable ⭐⭐⭐ Active dev UFO²
Monitoring Tools ⭐⭐⭐ Logs ⭐⭐⭐⭐⭐ Real-time viz Galaxy
API Flexibility ⭐⭐⭐ Good ⭐⭐⭐⭐⭐ Extensive Galaxy

🎯 Use Cases & Examples

Explore what you can build with UFO³:

🌌 Galaxy Use Cases (Cross-Device)

Perfect for complex, multi-device workflows:

  • Cross-Platform Data Pipelines: Extract from Windows Excel → Process on Linux → Visualize on Mac
  • Distributed Testing: Run tests on Windows → Deploy to Linux → Update mobile app
  • Multi-Device Monitoring: Collect logs from multiple devices → Aggregate centrally
  • Complex Automation: Orchestrate workflows across heterogeneous platforms

🪟 UFO² Use Cases (Windows)

Perfect for Windows automation and rapid task execution:

  • Office Automation: Excel/Word/PowerPoint report generation and data processing
  • Web Automation: Browser-based research, form filling, data extraction
  • File Management: Organize, rename, convert files based on rules
  • System Tasks: Windows configuration, software installation, backups

🌐 Community & Resources

📺 Media & Videos

Check out our official deep dive of UFO on YouTube.

Media Coverage:

💬 Get Help & Connect


📚 Research & Citation

UFO³ is built on cutting-edge research in multi-agent systems and GUI automation.

Papers

If you use UFO³ in your research, please cite:

UFO³ Galaxy Framework (2025)

bibtex
@article{zhang2025ufo3,
  title={UFO$^3$: Weaving the Digital Agent Galaxy}, 
  author = {Zhang, Chaoyun and Li, Liqun and Huang, He and Ni, Chiming and Qiao, Bo and Qin, Si and Kang, Yu and Ma, Minghua and Lin, Qingwei and Rajmohan, Saravan and Zhang, Dongmei},
  journal = {arXiv preprint arXiv:2511.11332},
  year    = {2025},
}

UFO² Desktop AgentOS (2025)

bibtex
@article{zhang2025ufo2,
  title   = {{UFO2: The Desktop AgentOS}},
  author  = {Zhang, Chaoyun and Huang, He and Ni, Chiming and Mu, Jian and Qin, Si and He, Shilin and Wang, Lu and Yang, Fangkai and Zhao, Pu and Du, Chao and Li, Liqun and Kang, Yu and Jiang, Zhao and Zheng, Suzhen and Wang, Rujia and Qian, Jiaxu and Ma, Minghua and Lou, Jian-Guang and Lin, Qingwei and Rajmohan, Saravan and Zhang, Dongmei},
  journal = {arXiv preprint arXiv:2504.14603},
  year    = {2025}
}

Original UFO (2024)

bibtex
@article{zhang2024ufo,
  title   = {{UFO: A UI-Focused Agent for Windows OS Interaction}},
  author  = {Zhang, Chaoyun and Li, Liqun and He, Shilin and Zhang, Xu and Qiao, Bo and Qin, Si and Ma, Minghua and Kang, Yu and Lin, Qingwei and Rajmohan, Saravan and Zhang, Dongmei and Zhang, Qi},
  journal = {arXiv preprint arXiv:2402.07939},
  year    = {2024}
}

📖 Read the Papers →


🗺️ Roadmap & Future

UFO² Desktop AgentOS (Stable/LTS)

  • ✅ Long-term support and maintenance
  • ✅ Windows device agent integration
  • 🔜 Enhanced device capabilities
  • 🔜 Picture-in-Picture mode

UFO³ Galaxy (Active Development)

  • ✅ Constellation Framework
  • ✅ Multi-device coordination
  • 🔄 Mobile, Web, IoT agents
  • 🔄 Interactive visualization
  • 🔜 Advanced fault tolerance

Legend: ✅ Done | 🔄 In Progress | 🔜 Planned



🚀 Ready to Start?

Choose your framework and begin your automation journey:

🌌 Start with Galaxy

For multi-device orchestration

🪟 Start with UFO²

For Windows automation

📖 Explore the Documentation

Core Concepts | Configuration | FAQ | GitHub




Documents Docs Aip Overview (`documents/docs/aip/overview.md`)

Agent Interaction Protocol (AIP)

The orchestration model requires a communication substrate that remains correct under continuous DAG evolution, dynamic agent participation, and fine-grained event propagation. Legacy HTTP-based coordination approaches (e.g., A2A, ACP) assume short-lived, stateless interactions, incurring handshake overhead, stale capability views, and fragile recovery when partial failures occur mid-task. These assumptions make them unsuitable for the continuously evolving workflows and long-running reasoning loops characteristic of UFO².

Design Overview

AIP serves as the nervous system of UFO², connecting the ConstellationClient, device agent services, and device clients under a unified, event-driven control plane. It is designed as a lightweight yet evolution-tolerant protocol to satisfy six goals:

Design Goals:

  • (G1) Maintain persistent bidirectional sessions to eliminate per-request overhead
  • (G2) Unify heterogeneous capability discovery via multi-source profiling
  • (G3) Ensure fine-grained reliability through heartbeats and timeout managers for disconnection and failure detection
  • (G4) Preserve deterministic command ordering within sessions
  • (G5) Support composable extensibility for new message types and resilience strategies
  • (G6) Provide transparent reconnection and task continuity under transient failures
Legacy HTTP Coordination AIP WebSocket-Based Design
❌ Short-lived requests ✅ Persistent sessions (G1)
❌ Stateless interactions ✅ Session-aware task management
❌ High latency overhead ✅ Low-latency event streaming
❌ Poor reconnection support ✅ Seamless recovery from disconnections (G6)
❌ Manual state synchronization ✅ Automatic DAG state propagation
❌ Fragile partial failures ✅ Fine-grained reliability (G3)

Five-Layer Architecture

To meet these requirements, AIP adopts a persistent, bidirectional WebSocket transport and decomposes the orchestration substrate into five logical strata, each responsible for a distinct aspect of reliability and adaptability. The architecture establishes a complete substrate where L1 defines semantic contracts, L2 provides transport flexibility, L3 implements protocol logic, L4 ensures operational resilience, and L5 delivers deployment-ready orchestration primitives.

Architecture Diagram:

The following diagram illustrates the five-layer architecture and the roles of each component:

Layer 1: Message Schema Layer

Defines strongly-typed, Pydantic-validated contracts (ClientMessage, ServerMessage) for message direction, purpose, and task transitions. All messages are validated at schema level, preventing malformed messages from entering the protocol pipeline, enabling early error detection and simplifying debugging.

Responsibility Implementation Supports
Message contracts Pydantic models with validation Human-readable + machine-verifiable
Structured metadata System info, capabilities Unified capability discovery (G2)
ID correlation Explicit request/response linking Deterministic ordering (G4)

Layer 2: Transport Abstraction Layer

Provides protocol-agnostic Transport interface with production-grade WebSocket implementation. The abstraction layer allows swapping transports without changing protocol logic, supporting future protocol evolution.

Feature Benefit Goals
Configurable pings/timeouts Connection health monitoring G3
Large payload support Handles complex task definitions G1
Decoupled transport logic Future extensibility (HTTP/3, gRPC) G5
Low-latency persistent sessions Eliminates per-request overhead G1

Layer 3: Protocol Orchestration Layer

Implements modular handlers for registration, task execution, heartbeat, and command dispatch. Each handler is independently testable and replaceable, supporting composable extensibility (G5) while maintaining ordered state transitions (G4).

Component Purpose Design
AIPProtocol base Common handler infrastructure Extensible base class
Handler modules Registration, tasks, heartbeat, commands Pluggable handlers
Middleware hooks Logging, metrics, authentication Composable extensions (G5)
State transitions Ordered message processing Deterministic ordering (G4)

Related Documentation:

Layer 4: Resilience and Health Management Layer

!!!warning "Fault Tolerance"
This layer guarantees fine-grained reliability (G3) and seamless task continuity under transient disconnections (G6), preventing cascade failures.

Encapsulates reliability mechanisms ensuring operational continuity under failures:

Component Mechanism Goals
HeartbeatManager Periodic keepalive signals G3
TimeoutManager Configurable timeout policies G3
ReconnectionStrategy Exponential backoff with jitter G6
Session recovery Automatic state restoration G6

→ Resilience implementation details

Layer 5: Endpoint Orchestration Layer

Provides role-specific facades integrating lower layers into deployable components. These endpoints unify connection lifecycle, task routing, and health monitoring across roles, reinforcing G1–G6 through consistent implementation of lower-layer capabilities.

Endpoint Role Responsibilities
ConstellationEndpoint Orchestrator Global agent registry, task assignment, DAG coordination
DeviceServerEndpoint Server WebSocket connection management, task dispatch, result aggregation
DeviceClientEndpoint Executor Local task execution, MCP tool invocation, telemetry reporting

Endpoint Integration Benefits:

  • ✅ Connection lifecycle management (G1, G6)
  • ✅ Role-specific protocol variants (G5)
  • ✅ Health monitoring integration (G3)
  • ✅ Task routing and session management (G4)

→ Endpoint setup guide

Architecture Benefits

Together, these layers form a vertically integrated stack that enables UFO² to maintain correctness and availability under challenging conditions:

Challenge How AIP Addresses It Layers Involved
DAG Evolution Deterministic ordering, extensible message types L1, L3, L4, L5 (G4, G5)
Agent Churn Heartbeats, reconnection, session recovery L4, L5 (G3, G6)
Heterogeneous Environments Persistent sessions, multi-source profiling L1, L2, L5 (G1, G2)
Transient Failures Timeout management, automatic recovery L4 (G3, G6)
Protocol Evolution Transport abstraction, middleware hooks L2, L3 (G5)

AIP transforms distributed workflow execution into a coherent, safe, and adaptive system where reasoning and execution converge seamlessly across diverse agents and environments.

Core Capabilities

Agent Registration & Profiling

Each agent is represented by an AgentProfile combining data from three sources for comprehensive capability discovery, supporting heterogeneous capability unification (G2):

Source Provider Information
User Config ConstellationClient Endpoint URLs, user preferences, device identity
Service Manifest Device Agent Service Supported tools, capabilities, operational metadata
Client Telemetry Device Agent Client OS, hardware specs, GPU status, runtime metrics

Benefits of Multi-Level Profiling:

  • ✅ Accurate task allocation based on real-time capabilities (G2)
  • ✅ Transparent adaptation to environmental changes (e.g., GPU availability)
  • ✅ No manual updates needed when device state changes
  • ✅ Informed scheduling decisions at scale

!!!tip "Dynamic Profile Updates"
Client telemetry continuously refreshes, so the orchestrator always sees current device state—critical for GPU-aware scheduling or cross-device load balancing (G2).

→ See detailed registration flow

Task Dispatch & Result Delivery

AIP uses long-lived WebSocket sessions that span multiple task executions, eliminating per-request connection overhead and preserving context (G1).

Task Execution Sequence:

The following sequence diagram shows the complete lifecycle of a task from assignment to completion, including intermediate execution steps and state updates:

mermaid
sequenceDiagram
    participant CC as ConstellationClient
    participant DAS as Device Service
    participant DAC as Device Client
    
    CC->>DAS: TASK message (TaskStar)
    DAS->>DAC: Stream task payload
    DAC->>DAC: Execute using MCP tools
    DAC->>DAS: Stream execution logs
    DAS->>CC: TASK_END (status, logs, results)
    CC->>CC: Update TaskConstellation
    CC->>CC: Notify ConstellationAgent

Each arrow represents a message exchange, with vertical lifelines showing the temporal ordering of events. Note how logs stream back during execution, enabling real-time monitoring.

Stage Message Type Content
Assignment TASK TaskStar definition, target device, commands
Execution (internal) MCP tool invocations, local computation
Reporting TASK_END Status, logs, evaluator outputs, results

!!!warning "Asynchronous Execution"
Tasks execute asynchronously. The orchestrator may assign multiple tasks to different devices simultaneously, with results arriving in non-deterministic order.

Related Documentation:

Command Execution

Within each task, AIP executes individual commands deterministically with preserved ordering, enabling precise control and error handling (G4).

Command Structure:

Field Purpose Example
tool_name Tool/action name "click_input"
parameters Typed arguments {"target": "Save Button", "button": "left"}
tool_type Category "action" or "data_collection"
call_id Unique identifier "cmd_001"

Execution Guarantees:

  • ✅ Sequential execution within a session (deterministic order) (G4)
  • ✅ Command batching supported (reduces network overhead)
  • ✅ Structured results with status codes and error details
  • ✅ Timeout propagation for precise recovery strategies (G3)

Command Batching Example:

json
{
  "actions": [
    {"tool_name": "click", "parameters": {"target": "File"}, "call_id": "1"},
    {"tool_name": "click", "parameters": {"target": "Save As"}, "call_id": "2"},
    {"tool_name": "type", "parameters": {"text": "document.pdf"}, "call_id": "3"}
  ]
}

All three commands sent in one message, executed sequentially.

→ See command execution protocol

Message Protocol Overview

All AIP messages use Pydantic models for automatic validation, serialization, and type safety.

Bidirectional Message Types

Direction Message Type Purpose
Client → Server REGISTER Initial capability advertisement
COMMAND_RESULTS Return command execution results
TASK_END Notify task completion
HEARTBEAT Keepalive signal
DEVICE_INFO_RESPONSE Device telemetry update
Server → Client TASK Task assignment
COMMAND Command execution request
DEVICE_INFO_REQUEST Request telemetry refresh
HEARTBEAT Keepalive acknowledgment
Bidirectional ERROR Error condition reporting

Message Correlation:

Every message includes:

  • timestamp: ISO 8601 formatted
  • request_id / response_id: Unique identifier
  • prev_response_id: Links responses to requests
  • session_id: Session context

→ Complete message reference

Resilient Connection Protocol

!!!warning "Network Instability Handling (G3, G6)"
AIP ensures continuous orchestration even under transient network failures or device disconnections through fine-grained reliability mechanisms and transparent reconnection.

Device Disconnection Flow

Connection State Transitions:

This state diagram illustrates how devices transition between connection states and the actions triggered at each transition:

mermaid
stateDiagram-v2
    [*] --> CONNECTED
    CONNECTED --> DISCONNECTED: Connection lost
    DISCONNECTED --> CONNECTED: Reconnection succeeds
    DISCONNECTED --> [*]: Timeout / Manual removal
    
    note right of DISCONNECTED
        • Excluded from scheduling
        • Tasks marked FAILED
        • Auto-reconnect triggered
    end note

The DISCONNECTED state acts as a quarantine zone where the device is temporarily removed from the scheduling pool while auto-reconnection attempts are made. If reconnection fails after timeout, the device is permanently removed.

Event Orchestrator Action Device Action
Device disconnects Mark as DISCONNECTEDExclude from schedulingTrigger auto-reconnect (G6) N/A
Reconnection succeeds Mark as CONNECTEDResume scheduling Session restored (G6)
Disconnect during task Mark tasks as FAILEDPropagate to ConstellationAgentTrigger DAG edit N/A

ConstellationClient Disconnection

!!!danger "Bidirectional Fault Handling"
When the ConstellationClient disconnects, all Device Agent Services:

text
1. Receive termination signal  
2. **Abort all ongoing tasks** tied to that client  
3. Prevent resource leakage and zombie processes  
4. Maintain end-to-end consistency

Guarantees:

  • ✅ No orphaned tasks
  • ✅ Synchronized state across client-server boundary
  • ✅ Rapid recovery when connection restored (G6)
  • ✅ Consistent TaskConstellation state (G4)

→ See resilience implementation

Extensibility Mechanisms

AIP provides multiple extension points for domain-specific needs without modifying the core protocol, supporting composable extensibility (G5).

1. Protocol Middleware

Add custom processing to message pipeline:

python
from aip.protocol.base import ProtocolMiddleware

class AuditMiddleware(ProtocolMiddleware):
    async def process_outgoing(self, msg):
        log_to_audit_trail(msg)
        return msg
    
    async def process_incoming(self, msg):
        log_to_audit_trail(msg)
        return msg

2. Custom Message Handlers

Register handlers for new message types:

python
protocol.register_handler("custom_type", handle_custom_message)

3. Transport Layer

Pluggable transport (default: WebSocket) (G5):

python
from aip.transport import CustomTransport
protocol.transport = CustomTransport(config)

→ See extensibility guide

Integration with UFO² Ecosystem

Component Integration Point Benefit
MCP Servers Command execution model aligns with MCP message formats Unified interface for system actions and LLM tool calls
TaskConstellation Real-time state synchronization via AIP messages Planning DAG always reflects distributed execution state
Configuration System Agent endpoints, capabilities managed via UFO² config Centralized management, type-safe validation
Logging & Monitoring Comprehensive logging at all protocol layers Debugging, performance monitoring, audit trails

AIP abstracts network/device heterogeneity, allowing the orchestrator to treat all agents as first-class citizens in a single event-driven control plane.

Related Documentation:

Summary

AIP transforms distributed workflow execution into a coherent, safe, and adaptive system where reasoning and execution converge seamlessly across diverse agents and environments.

Key Takeaways:

Aspect Impact Goals
Persistence Long-lived connections reduce overhead, maintain context G1
Low Latency WebSocket enables real-time event propagation G1
Capability Discovery Multi-source profiling unifies heterogeneous agents G2
Reliability Heartbeats, timeouts, auto-reconnection ensure graceful degradation G3, G6
Determinism Sequential command execution, explicit ID correlation G4
Extensibility Middleware hooks, pluggable transports, custom handlers G5
Developer UX Strongly-typed messages, clear errors reduce integration effort G5

By decomposing orchestration into five logical layers—each addressing specific reliability and adaptability concerns—AIP enables UFO² to maintain correctness and availability under DAG evolution (G4, G5), agent churn (G3, G6), and heterogeneous execution environments (G1, G2).


Documents Docs Client Overview (`documents/docs/client/overview.md`)

UFO Client Overview

The UFO Client runs on target devices and serves as the execution layer of UFO's distributed agent system. It manages MCP (Model Context Protocol) servers, executes commands deterministically, and communicates with the Agent Server through the Agent Interaction Protocol (AIP).

Quick Start: Jump to the Quick Start Guide to connect your device. Make sure the Agent Server is running first.


🎯 What is the UFO Client?

mermaid
graph LR
    subgraph "Agent Server (Brain)"
        Reasoning[High-Level Reasoning]
        Planning[Task Planning]
        Strategy[Strategy Selection]
    end
    
    subgraph "Agent Client (Hands)"
        Execution[Command Execution]
        Tools[Tool Management]
        Reporting[Status Reporting]
    end
    
    subgraph "Device Environment"
        Apps[Applications]
        Files[File System]
        UI[User Interface]
    end
    
    Reasoning -->|Directives| Execution
    Planning -->|Commands| Execution
    Strategy -->|Tasks| Execution
    
    Execution --> Tools
    Tools --> Apps
    Tools --> Files
    Tools --> UI
    
    Reporting -->|Results| Reasoning
    
    style Reasoning fill:#bbdefb
    style Execution fill:#c8e6c9
    style Tools fill:#fff9c4

The UFO Client is a stateless execution agent that:

Capability Description Benefit
🔧 Executes Commands Translates server directives into concrete actions Deterministic, reliable execution
🛠️ Manages MCP Servers Orchestrates local and remote tool interfaces Extensible tool ecosystem
📊 Reports Device Info Provides hardware and software profile to server Intelligent task assignment
📡 Communicates via AIP Maintains persistent WebSocket connection Real-time bidirectional communication
🚫 Remains Stateless Executes directives without high-level reasoning Independent updates, simple architecture

Stateless Design Philosophy: The client focuses purely on execution. All reasoning and decision-making happens on the server, allowing independent updates to server logic and client tools, simple client architecture, intelligent orchestration of multiple clients, and resource-efficient operation.

Architecture: The UFO Client is part of UFO's distributed server-client architecture, where it handles command execution and resource access while the Agent Server handles orchestration and decision-making. See Server-Client Architecture for the complete design rationale, communication protocols, and deployment patterns.


🏗️ Architecture

The client implements a layered architecture separating communication, execution, and tool management for maximum flexibility and maintainability.

mermaid
graph TB
    subgraph "Communication"
        WSC[WebSocket Client<br/>AIP Protocol]
    end
    
    subgraph "Orchestration"
        UFC[UFO Client]
        CM[Computer Manager]
    end
    
    subgraph "Execution"
        COMP[Computer]
        MCPM[MCP Manager]
    end
    
    subgraph "Tools"
        LOCAL[Local MCP Servers]
        REMOTE[Remote MCP Servers]
    end
    
    WSC --> UFC
    UFC --> CM
    CM --> COMP
    COMP --> MCPM
    MCPM --> LOCAL
    MCPM --> REMOTE
    
    style WSC fill:#bbdefb
    style UFC fill:#c8e6c9
    style COMP fill:#fff9c4
    style MCPM fill:#ffcdd2

Core Components

Component Responsibility Key Features Documentation
WebSocket Client AIP communication • Connection management• Registration• Heartbeat monitoring• Message routing Details →
UFO Client Execution orchestration • Command execution• Result aggregation• Error handling• Session management Details →
Computer Manager Multi-computer abstraction • Computer instance management• Namespace routing• Resource isolation Details →
Computer Tool management • MCP server registration• Tool registry• Execution isolation• Thread pool management Details →
MCP Server Manager MCP lifecycle • Server creation• Configuration loading• Connection pooling• Health monitoring MCP Documentation →
Device Info Provider System profiling • Hardware detection• Capability reporting• Platform identification• Feature enumeration Details →

For detailed component documentation:


🚀 Key Capabilities

1. Deterministic Command Execution

The client executes commands exactly as specified without interpretation or reasoning, ensuring predictable behavior.

mermaid
sequenceDiagram
    participant Server
    participant Client as UFO Client
    participant Computer
    participant Tool as MCP Tool
    
    Server->>Client: COMMAND (AIP)
    Client->>Computer: Execute Command
    Computer->>Computer: Lookup Tool
    Computer->>Tool: Execute with Timeout
    Tool-->>Computer: Result
    Computer-->>Client: Aggregated Result
    Client-->>Server: COMMAND_RESULTS (AIP)

Execution Flow:

Step Action Purpose
1️⃣ Receive Get structured command from server via AIP Ensure well-formed input
2️⃣ Route Dispatch to appropriate computer instance Support multi-namespace execution
3️⃣ Lookup Find tool in MCP registry Dynamic tool resolution
4️⃣ Execute Run tool in isolated thread pool Fault isolation and timeout protection
5️⃣ Aggregate Combine results from multiple tools Structured response format
6️⃣ Return Send results back to server via AIP Complete the execution loop

Execution Guarantees:

  • Isolation: Each tool runs in separate thread pool
  • Timeouts: Configurable timeout (default: 6000 seconds/100 minutes)
  • Fault Tolerance: One failed tool doesn't crash entire client
  • Thread Safety: Concurrent tool execution supported
  • Error Reporting: Structured errors returned to server

2. MCP Server Management

The client manages a collection of MCP (Model Context Protocol) servers to provide diverse tool access for automation tasks. The client is responsible for registering, managing, and executing these tools, while the Agent Server handles command orchestration. See Server-Client Architecture for how MCP integration fits into the overall architecture.

MCP Server Categories:

Data Collection Servers gather information from the device:

Server Type Tools Provided Use Cases
System Info CPU, memory, disk stats Resource monitoring
Application State Running apps, windows Context awareness
Screenshot Screen capture Visual verification
UI Element Detection Control trees, accessibility UI automation

Example Tools: get_system_info(), list_running_apps(), capture_screenshot(), get_ui_tree()

Action Servers perform actions on the device:

Server Type Tools Provided Use Cases
GUI Automation Keyboard, mouse, clicks UI interaction
Application Control Launch, close, focus App management
File System Read, write, delete File operations
Command Execution Shell commands System automation

Example Tools: click_button(label), type_text(text), open_application(name), execute_command(cmd)

Server Types:

Type Deployment Pros Cons
Local MCP Servers Run in same process via FastMCP Fast, no network overhead Limited to local capabilities
Remote MCP Servers Connect via HTTP/SSE Scalable, shared services Network latency, external dependency

Example MCP Server Configuration:

yaml
mcp_servers:
  data_collection:
    - name: "system_info"
      type: "local"
      class: "SystemInfoServer"
    - name: "ui_detector"
      type: "local"
      class: "UIDetectionServer"
  
  action:
    - name: "gui_automation"
      type: "local"
      class: "GUIAutomationServer"
    - name: "file_ops"
      type: "remote"
      url: "http://localhost:8080/mcp"

See MCP Integration for comprehensive MCP server documentation.

3. Device Profiling

The client automatically collects and reports device information to enable the server to make intelligent task routing decisions.

Device Profile Structure:

json
{
  "device_id": "device_windows_001",
  "platform": "windows",
  "platform_type": "computer",
  "os_version": "10.0.22631",
  "system_info": {
    "cpu_count": 8,
    "memory_total_gb": 16.0,
    "disk_total_gb": 512.0,
    "hostname": "DESKTOP-ABC123",
    "ip_address": "192.168.1.100"
  },
  "supported_features": [
    "gui_automation",
    "cli_execution",
    "browser_control",
    "office_integration",
    "windows_apps"
  ],
  "installed_applications": [
    "Chrome",
    "Excel",
    "PowerPoint",
    "VSCode"
  ],
  "screen_resolution": "1920x1080",
  "connected_at": "2025-11-05T10:30:00Z"
}

Profile Usage on Server:

mermaid
graph LR
    Client[Client Detects<br/>Device Info]
    Server[Server Stores<br/>Profile]
    Route[Server Routes<br/>Tasks]
    
    Client -->|Report Profile| Server
    Server -->|Match Requirements| Route
    Route -->|Dispatch Task| Client
    
    style Client fill:#bbdefb
    style Server fill:#c8e6c9
    style Route fill:#fff9c4

Server Uses Profile For:

Use Case Example Logic
Platform Matching Route Excel task to Windows device
Capability Filtering Only send browser tasks to devices with Chrome
Load Balancing Distribute tasks based on CPU/memory
Failure Recovery Reassign task if device disconnects

See Device Info Provider for detailed profiling documentation.

4. Resilient Communication

Robust, fault-tolerant communication with the server using strongly-typed AIP messages.

Connection Lifecycle:

mermaid
stateDiagram-v2
    [*] --> Disconnected
    Disconnected --> Connecting: Initiate Connection
    Connecting --> Registering: WebSocket Established
    Registering --> Connected: Registration Success
    Connecting --> Disconnected: Connection Failed
    Registering --> Disconnected: Registration Failed
    
    Connected --> Heartbeating: Start Heartbeat Loop
    Heartbeating --> Heartbeating: Send/Receive Heartbeat
    Heartbeating --> Disconnected: Heartbeat Timeout
    Heartbeating --> Disconnected: WebSocket Closed
    
    Disconnected --> Connecting: Retry (Exponential Backoff)
    
    note right of Connected
        • Receive commands
        • Execute tasks
        • Report results
    end note
    
    note right of Heartbeating
        Default interval: 30s
        Timeout: 60s
    end note

Connection Features:

Feature Description Configuration
Auto Registration Registers with server on connect Device ID, platform, capabilities
Exponential Backoff Smart retry on connection failure Max retries: 5 (default)
Heartbeat Monitoring Keep-alive mechanism Interval: 30s (configurable)
Graceful Reconnection Resume operation after disconnect Auto-reconnect on network recovery

Message Types:

Message Direction Purpose
REGISTRATION Client → Server Register device with capabilities
REGISTRATION_ACK Server → Client Confirm registration
HEARTBEAT Client ↔ Server Keep connection alive
COMMAND Server → Client Execute task command
COMMAND_RESULTS Client → Server Return execution results
ERROR Client → Server Report execution errors

See WebSocket Client and AIP Protocol for protocol details.


📋 Workflow Examples

Client Initialization & Registration

mermaid
sequenceDiagram
    participant Main as Client Main
    participant MCP as MCP Manager
    participant WSC as WebSocket Client
    participant Server
    
    Main->>MCP: Initialize MCP Servers
    MCP-->>Main: Server Registry Ready
    
    Main->>WSC: Create Client & Connect
    WSC->>Server: WebSocket Connect
    Server-->>WSC: Connection Established
    
    WSC->>WSC: Collect Device Info
    WSC->>Server: REGISTRATION
    Server-->>WSC: REGISTRATION_ACK
    
    WSC->>WSC: Start Heartbeat Loop
    
    loop Every 30 seconds
        WSC->>Server: HEARTBEAT
        Server-->>WSC: HEARTBEAT_ACK
    end
    
    Note over WSC,Server: Ready to Execute Commands

Initialization Steps:

Step Action Details
1️⃣ Parse Args Process command-line arguments --client-id, --ws-server, --platform
2️⃣ Load Config Load UFO configuration MCP servers, tools, settings
3️⃣ Init MCP Initialize MCP server manager Create local/remote servers
4️⃣ Create Managers Create computer manager Register MCP servers with computers
5️⃣ Connect Establish WebSocket connection Connect to server
6️⃣ Register Send device profile Platform, capabilities, system info
7️⃣ Heartbeat Start keep-alive loop Default: 30s interval
8️⃣ Listen Wait for commands Ready for task execution

Command Execution Flow

mermaid
sequenceDiagram
    participant Server
    participant Client as UFO Client
    participant Comp as Computer
    participant Tool as MCP Tool
    
    Server->>Client: COMMAND<br/>{type: "click_button", args: {...}}
    Client->>Comp: execute_command()
    Comp->>Comp: find_tool("click_button")
    
    alt Tool Found
        Comp->>Tool: execute(args)
        Note over Tool: Thread Pool Execution<br/>6000s timeout
        Tool-->>Comp: Success
        Comp-->>Client: Result
        Client-->>Server: COMMAND_RESULTS<br/>{status: "completed"}
    else Tool Not Found
        Comp-->>Client: Error
        Client-->>Server: ERROR<br/>{error: "Tool not found"}
    end

🖥️ Platform Support

The client supports multiple platforms with platform-specific tool implementations.

Platform Status Features Native Tools
Windows ✅ Full Support • UI Automation (UIAutomation API)• COM API integration• Office automation• Windows-specific apps PowerShell, Registry, WMI, Win32 API
Linux ✅ Full Support • Bash automation• X11/Wayland GUI tools• Package managers• Linux applications bash, apt/yum, systemd, xdotool
macOS 🚧 In Development • macOS applications• Automator integration• AppleScript support osascript, Automator, launchctl
Mobile 🔮 Planned • Touch interface• Mobile apps• Gesture control ADB (Android), XCTest (iOS)

Platform Detection:

  • Automatic: Detected via platform.system() on startup
  • Override: Use --platform flag to specify manually
  • Validation: Server validates platform matches task requirements

Platform-Specific Example:

Windows:

python
# Windows-specific tools
tools = [
    "open_windows_app(name='Excel')",
    "execute_powershell(script='Get-Process')",
    "read_registry(key='HKLM\\Software')"
]

Linux:

python
# Linux-specific tools
tools = [
    "execute_bash(command='ls -la')",
    "install_package(name='vim')",
    "control_systemd(service='nginx', action='restart')"
]

⚙️ Configuration

Command-Line Arguments

Start the UFO client with:

bash
python -m ufo.client.client [OPTIONS]

Available Options:

Option Type Default Description Example
--client-id str client_001 Unique client identifier --client-id device_win_001
--ws-server str ws://localhost:5000/ws WebSocket server URL --ws-server ws://192.168.1.10:5000/ws
--ws flag False Enable WebSocket mode (required) --ws
--max-retries int 5 Connection retry limit --max-retries 10
--platform str Auto-detect Platform override --platform windows
--log-level str WARNING Logging verbosity --log-level DEBUG

Quick Start Command:

bash
# Minimal command (default server)
python -m ufo.client.client --ws --client-id my_device

# Production command (custom server)
python -m ufo.client.client \
  --ws \
  --client-id device_production_01 \
  --ws-server ws://ufo-server.company.com:5000/ws \
  --max-retries 10 \
  --log-level INFO

UFO Configuration

The client inherits settings from config_dev.yaml:

Key Configuration Sections:

Section Purpose Example
MCP Servers Define data collection and action servers mcp_servers.data_collection, mcp_servers.action
Tool Settings Tool-specific parameters Timeouts, retries, API keys
Logging Log levels, formats, destinations File logging, console output
Platform Settings OS-specific configurations Windows UI automation settings

Sample Configuration:

yaml
client:
  heartbeat_interval: 30  # seconds
  command_timeout: 6000   # seconds (100 minutes)
  max_concurrent_tools: 10

mcp_servers:
  data_collection:
    - name: system_info
      type: local
      enabled: true
  action:
    - name: gui_automation
      type: local
      enabled: true
      settings:
        click_delay: 0.5
        typing_speed: 100  # chars per minute

logging:
  level: INFO
  format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
  file: "logs/client.log"

See Configuration Guide for comprehensive documentation.


⚠️ Error Handling

The client is designed to handle various failure scenarios gracefully without crashing.

Connection Failures

mermaid
stateDiagram-v2
    [*] --> Attempting
    Attempting --> Connected: Success
    Attempting --> Failed: Error
    
    Failed --> Waiting: Exponential Backoff
    Waiting --> Attempting: Retry (2^n seconds)
    
    Failed --> [*]: Max Retries Exceeded
    
    note right of Waiting
        Retry Delays:
        1st: 2s
        2nd: 4s
        3rd: 8s
        4th: 16s
        5th: 32s
    end note

Connection Error Handling:

Scenario Client Behavior Configuration
Initial Connection Failed Exponential backoff retry --max-retries (default: 5)
Connection Lost Attempt reconnection Automatic
Max Retries Exceeded Exit with error code Log error, exit
Server Unreachable Log error, retry Backoff between retries

Tool Execution Failures

Protection Mechanisms:

Mechanism Purpose Default Value
Thread Pool Isolation Prevent one tool from blocking others Enabled
Execution Timeout Kill hung tools 6000 seconds (100 minutes)
Exception Catching Graceful error handling All tools wrapped
Error Reporting Notify server of failures Structured error messages

Error Handling Example:

python
# Client automatically handles tool errors
try:
    result = tool.execute(args)
    return {"status": "success", "result": result}
except TimeoutError:
    return {"status": "error", "error": "Tool execution timeout"}
except Exception as e:
    return {"status": "error", "error": str(e)}

Server Disconnection

Graceful Shutdown Process:

  1. Detect Disconnection - WebSocket connection lost
  2. Stop Heartbeat - Terminate keep-alive loop
  3. Cancel Pending Tasks - Abort in-progress commands
  4. Attempt Reconnection - Use exponential backoff
  5. Clean Shutdown - If max retries exceeded

✅ Best Practices

Development Best Practices

1. Use Unique Client IDs

bash
# Bad: Generic ID
--client-id client_001

# Good: Descriptive ID
--client-id device_win_dev_john_laptop

2. Start with INFO Logging

bash
# Development: WARNING for normal operation (default)
--log-level WARNING

# Debugging: DEBUG for troubleshooting
--log-level DEBUG

3. Test MCP Connectivity First

python
# Verify MCP servers are accessible before running client
from ufo.client.mcp.mcp_server_manager import MCPServerManager

manager = MCPServerManager()
# Test server creation from configuration

Production Best Practices

1. Use Descriptive Client IDs

bash
# Include environment, location, purpose
--client-id device_windows_production_office_01
--client-id device_linux_staging_lab_02

2. Configure Automatic Restart

systemd (Linux):

ini
[Unit]
Description=UFO Agent Client
After=network.target
    
[Service]
Type=simple
User=ufo
WorkingDirectory=/opt/ufo
ExecStart=/usr/bin/python3 -m ufo.client.client \
  --ws \
  --client-id device_linux_prod_01 \
  --ws-server ws://ufo-server.internal:5000/ws \
  --log-level INFO
Restart=always
RestartSec=10
    
[Install]
WantedBy=multi-user.target

PM2 (Cross-platform):

json
{
  "apps": [{
    "name": "ufo-client",
    "script": "python",
    "args": [
      "-m", "ufo.client.client",
      "--ws",
      "--client-id", "device_win_prod_01",
      "--ws-server", "ws://ufo-server.internal:5000/ws",
      "--log-level", "INFO"
    ],
    "cwd": "C:\\ufo",
    "restart_delay": 5000,
    "max_restarts": 10
  }]
}

3. Monitor Connection Health

bash
# Check logs for connection status
tail -f logs/client.log | grep -E "Connected|Disconnected|ERROR"

Security Best Practices

!!! warning "Security Considerations"

text
| Practice | Description | Implementation |
|----------|-------------|----------------|
| **Use WSS** | Encrypt WebSocket communication | `wss://server:5000/ws` instead of `ws://` |
| **Validate Server** | Verify server certificate | Configure SSL/TLS verification |
| **Restrict Tools** | Limit MCP server access | Only enable necessary tools |
| **Least Privilege** | Run with minimum permissions | Create dedicated user account |
| **Network Isolation** | Use firewalls and VPNs | Restrict server access to internal network |

🎓 Documentation Map

Getting Started

Document Purpose When to Read
Quick Start Connect your device quickly First time setup
Server Quick Start Understand server-side setup Before running client

Component Details

Document Component Topics Covered
WebSocket Client Communication layer AIP protocol, connection management
UFO Client Orchestration Session tracking, command execution
Computer Manager Multi-computer abstraction Namespace management, routing
Computer Tool management MCP registry, execution
Device Info System profiling Hardware detection, capabilities
MCP Integration MCP servers Server types, configuration
Document Topic Relevance
Server Overview Server architecture Understand the other half
AIP Protocol Communication protocol Deep dive into messaging
Configuration UFO configuration Customize behavior

🔄 Client vs. Server

Understanding the clear division between client and server responsibilities is crucial for effective system design.

Responsibility Matrix:

Aspect Client (Execution) Server (Orchestration)
Primary Role Execute directives deterministically Reason about tasks, plan actions
State Management Stateless (no session memory) Stateful (maintains sessions)
Reasoning None (pure execution) Full (high-level decision-making)
Tools MCP servers (local/remote) Agent strategies, prompts, LLMs
Communication Device ↔ Server (AIP) Multi-client coordination
Updates Tool implementation changes Strategy and logic updates
Complexity Low (simple execution loop) High (complex orchestration)
Dependencies MCP servers, system APIs LLMs, databases, client registry

Workflow Comparison:

mermaid
graph TB
    subgraph "Server Workflow"
        S1[Receive User Request]
        S2[Reason About Task]
        S3[Plan Execution Steps]
        S4[Select Target Device]
        S5[Send Commands]
    end
    
    subgraph "Client Workflow"
        C1[Receive Command]
        C2[Lookup Tool]
        C3[Execute Tool]
        C4[Return Result]
    end
    
    S1 --> S2
    S2 --> S3
    S3 --> S4
    S4 --> S5
    S5 -.->|AIP| C1
    C1 --> C2
    C2 --> C3
    C3 --> C4
    C4 -.->|AIP| S5
    
    style S1 fill:#bbdefb
    style S2 fill:#bbdefb
    style S3 fill:#bbdefb
    style C1 fill:#c8e6c9
    style C2 fill:#c8e6c9
    style C3 fill:#c8e6c9

Decoupled Architecture Benefits:

  • Independent Updates: Modify server logic without touching clients
  • Flexible Deployment: Run clients on any platform
  • Scalability: Add more clients without server changes
  • Maintainability: Simpler client code, easier debugging
  • Testability: Test client and server independently

🚀 Next Steps

1. Run Your First Client

bash
# Follow the quick start guide
python -m ufo.client.client \
  --ws \
  --client-id my_first_device \
  --ws-server ws://localhost:5000/ws

👉 Quick Start Guide

2. Understand Registration Process

Learn how clients register with the server, device profile structure, and registration acknowledgment.

👉 Server Quick Start - Start server and connect clients

3. Explore MCP Integration

Learn about MCP servers, configure custom tools, and create your own MCP servers.

👉 MCP Integration

4. Configure for Your Environment

Customize MCP servers, adjust timeouts and retries, and configure platform-specific settings.

👉 Configuration Guide

5. Master the Protocol

Deep dive into AIP messages, understand message flow, and error handling patterns.

👉 AIP Protocol


Documents Docs Galaxy Overview (`documents/docs/galaxy/overview.md`)

UFO³ — Weaving the Digital Agent Galaxy


🚀 What is UFO³ Galaxy?

UFO³ Galaxy is a revolutionary cross-device orchestration framework that transforms isolated device agents into a unified digital ecosystem. It models complex user requests as Task Constellations (星座) — dynamic distributed DAGs where nodes represent executable subtasks and edges capture dependencies across heterogeneous devices.

🎯 The Vision

Building truly ubiquitous intelligent agents requires moving beyond single-device automation. UFO³ Galaxy addresses four fundamental challenges in cross-device agent orchestration:

🔄 Asynchronous Parallelism
Enabling concurrent task execution across multiple devices while maintaining correctness through event-driven coordination and safe concurrency control

⚡ Dynamic Adaptation
Real-time workflow evolution in response to intermediate results, transient failures, and runtime observations without workflow abortion

🌐 Distributed Coordination
Reliable, low-latency communication across heterogeneous devices via WebSocket-based Agent Interaction Protocol with fault tolerance

🛡️ Safety Guarantees
Formal invariants ensuring DAG consistency during concurrent modifications and parallel execution, verified through rigorous proofs


🏗️ Architecture

Layered Design

UFO³ Galaxy follows a hierarchical orchestration model that separates global coordination from local execution. This architecture enables scalable cross-device orchestration while maintaining consistent control and responsiveness across diverse operating systems and network environments.

🎛️ Hierarchical Control Plane

ConstellationClient serves as the global control plane, maintaining a live registry of all connected device agents with their:

  • Capability profiles and system specifications
  • Runtime health metrics and availability status
  • Current load and resource utilization

This registry enables intelligent task placement based on device capabilities, avoiding mismatches between task requirements and device capacity.

Each device hosts a device agent server that manages local orchestration through persistent WebSocket sessions with ConstellationClient. The server:

  • Maintains execution contexts on the host
  • Provides unified interface to underlying tools via MCP servers
  • Handles task execution, telemetry streaming, and resource monitoring

Clean separation: Global orchestration policies are decoupled from device-specific heterogeneity, providing consistent abstraction across endpoints with different OS, hardware, or network conditions.

🔄 Orchestration Flow

  1. DAG Synthesis: ConstellationClient invokes the Constellation Agent to construct a TaskConstellation—a dynamic DAG encoding task decomposition, dependencies, and device mappings
  2. Device Assignment: Each TaskStar (DAG node) is assigned to suitable device agents based on capability profiles and system load
  3. Asynchronous Execution: The Constellation Orchestrator executes the DAG in an event-driven manner:
    • Task completions trigger dependent nodes
    • Failures prompt retry, migration, or partial DAG rewrites
    • Workflows adapt to real-time system dynamics (device churn, network variability)

Result: Highly parallel and resilient execution that sustains workflow completion even as subsets of devices fail or reconnect.

🔌 Cross-Agent Communication

The Agent Interaction Protocol (AIP) handles all cross-agent interactions:

  • Agent registration and capability synchronization
  • Task dispatch and progress reporting
  • Result aggregation and telemetry streaming

Built on persistent WebSocket channels, AIP provides:

  • Lightweight: Minimal overhead for control messages
  • Bidirectional: Full-duplex communication between client and agents
  • Multiplexed: Concurrent message streams over single connection
  • Low-latency: Fast propagation of control signals and state updates
  • Resilient: Maintains global consistency despite intermittent connectivity

Together, these design elements form a cohesive foundation for orchestrating large-scale, heterogeneous, and adaptive workflows across a resilient multi-device execution fabric.


✨ Core Design Principles

UFO³ Galaxy realizes cross-device orchestration through five tightly integrated design principles:

1. 🌟 Declarative Decomposition into Dynamic DAG (Task Constellation)

Natural-language or programmatic requests are decomposed by the Constellation Agent into a structured DAG of TaskStars (nodes) and TaskStarLines (edges) that encode workflow logic, dependencies, and device assignments. This declarative structure is amenable to automated scheduling, introspection, and dynamic modification throughout execution.

Key Benefits:

  • 📋 Declarative structure for automated scheduling
  • 🔍 Runtime introspection for workflow visibility
  • ✏️ Dynamic rewriting throughout execution
  • 🔄 Automated orchestration across heterogeneous devices
mermaid
graph LR
    A[User Intent] --> B[Constellation Agent]
    B --> C[Task Constellation DAG]
    C --> D[TaskStar 1<br/>Windows]
    C --> E[TaskStar 2<br/>Linux GPU]
    C --> F[TaskStar 3<br/>Linux CPU]
    C --> G[TaskStar 4<br/>Mobile]
    E --> H[TaskStar 5]
    F --> H
    G --> H

Learn more →

2. 🔄 Continuous, Result-Driven Graph Evolution

The Task Constellation is a living data structure that evolves in response to execution feedback. Intermediate outputs, transient failures, and new observations trigger controlled rewrites—adding diagnostic TaskStars, creating fallbacks, rewiring dependencies, or pruning completed nodes—so the system adapts dynamically instead of aborting on errors.

Adaptation Mechanisms:

  • 🩺 Diagnostic TaskStars added for debugging
  • 🛡️ Fallback creation for error recovery
  • 🔗 Dependency rewiring for workflow optimization
  • ✂️ Node pruning after completion

The Constellation Agent operates in two modes:

  • Creation Mode: Synthesizes initial DAG from user request with device-aware task decomposition
  • Editing Mode: Incrementally refines constellation based on task completion events and runtime feedback

Learn more →

3. 🎯 Heterogeneous, Asynchronous, and Safe Orchestration

Each Task Star is matched to the most suitable device agent via rich Agent Profiles reflecting OS, hardware capabilities, and installed tools. The Constellation Orchestrator executes tasks asynchronously, allowing multiple TaskStars to progress in parallel.

Safety Guarantees:

  • 🔒 Safe assignment locking prevents race conditions
  • 📅 Event-driven scheduling monitors DAG readiness
  • ✅ DAG consistency checks maintain structural integrity
  • 🔄 Batched edits ensure atomicity
  • 📐 Formal verification reinforces correctness
  • ⏱️ Timeout protection prevents deadlocks

These mechanisms collectively ensure high efficiency without compromising reliability.

Learn more →

4. 🔌 Unified Agent Interaction Protocol (AIP)

Built atop persistent WebSocket channels, AIP provides a unified, secure, and fault-tolerant layer for the entire agent ecosystem.

Core Capabilities:

  • 📝 Agent registry with capability profiles
  • 🔐 Session management for secure communication
  • 📤 Task dispatch with intelligent routing
  • 🎯 Coordination primitives for distributed workflows
  • 💓 Heartbeat monitoring for health tracking
  • 🔌 Automatic reconnection under network fluctuations
  • 🔄 Retry mechanisms for reliability

Architecture Benefits:

  • 🪶 Lightweight interface for easy integration
  • 🧩 Extensible design supports new agent types
  • 🛡️ Fault tolerance ensures continuous operation

This protocol abstracts OS and network heterogeneity, enabling seamless collaboration among agents across desktops, servers, and edge devices, while allowing new agents to integrate seamlessly into the UFO³ ecosystem.

Learn more →

5. 🛠️ Template-Driven Framework for Device Agents

To democratize agent creation, UFO³ provides a lightweight development template and toolkit for rapidly building new device agents.

Development Framework:

  • 📄 Capability declaration defines agent profiles
  • 🔗 Environment binding connects to local systems
  • 🧩 MCP server integration for tool augmentation
  • 🔧 Modular design accelerates development

Model Context Protocol (MCP) Integration:

  • 🎁 Tool packages via MCP servers
  • 🔌 Plug-and-play capability extension
  • 🌐 Cross-platform tool standardization
  • 🚀 Rapid prototyping of new agents

This modular architecture maintains consistency across the constellation while enabling developers to extend UFO³ to new platforms (mobile, web, IoT, embedded systems, etc.) with minimal effort.

🔌 Extensibility: UFO³ is designed as a universal framework that supports developing new device agents for different platforms (mobile, web, IoT, embedded systems, etc.) and applications. Through the Agent Interaction Protocol (AIP), custom device agents can seamlessly integrate into UFO³ Galaxy for coordinated multi-device automation. Want to build your own device agent? See our Creating Custom Device Agents tutorial to learn how to extend UFO³ to new platforms.

Learn more → | MCP Integration →


🎯 Key Capabilities

🌐 Cross-Device Collaboration

Execute workflows that span Windows desktops, Linux servers, GPU clusters, mobile devices, and edge nodes—all from a single natural language request.

⚡ Asynchronous Parallelism

Automatically identify parallelizable subtasks and execute them concurrently across devices through:

  • Event-driven scheduling that continuously monitors DAG topology for ready tasks
  • Non-blocking execution with Python asyncio for maximum concurrency
  • Dynamic adaptation that integrates new tasks without interrupting running execution

Result: Dramatically reduced end-to-end latency compared to sequential execution.

🛡️ Safety & Consistency

  • Three formal invariants (I1-I3) enforced at runtime for DAG correctness
  • Safe assignment locking prevents race conditions during concurrent modifications
  • Acyclicity validation ensures no circular dependencies
  • State merging algorithm preserves execution progress during dynamic edits
  • Timeout protection prevents deadlocks from agent failures

🔄 Dynamic Workflow Evolution

  • Dual-mode operation: Separate creation and editing phases with controlled transitions
  • Feedback-driven adaptation: Task completion events trigger intelligent constellation refinement
  • LLM-powered reasoning: ReAct architecture for context-aware DAG modifications
  • Undo/redo support: ConstellationEditor with command pattern for safe interactive editing

👁️ Rich Observability

  • Real-time constellation visualization with DAG topology updates
  • Event bus with publish-subscribe pattern for monitoring task progress
  • Detailed execution logs with markdown trajectory support
  • Task status tracking (pending, running, completed, failed, cancelled)
  • Dependency graph inspection and validation tools

🎨 Use Cases

🖥️ Software Development & Deployment

"Clone the repo on my laptop, build the Docker image on the GPU server, deploy to staging, and run the test suite on the CI cluster."

Workflow DAG:

mermaid
graph LR
    A[Clone<br/>Windows] --> B[Build<br/>Linux GPU]
    B --> C[Deploy<br/>Linux Server]
    C --> D[Test<br/>Linux CI]

📊 Data Science Workflows

"Fetch the dataset from cloud storage, preprocess on the Linux workstation, train the model on the A100 node, and generate a visualization dashboard on my Windows machine."

Workflow DAG:

mermaid
graph LR
    A[Fetch<br/>Any] --> B[Preprocess<br/>Linux]
    B --> C[Train<br/>Linux GPU]
    C --> D[Visualize<br/>Windows]

📝 Cross-Platform Document Processing

"Extract data from Excel on Windows, process with Python scripts on Linux, generate PDF reports, and send summary emails."

Workflow DAG:

mermaid
graph LR
    A[Extract<br/>Windows] --> B[Process<br/>Linux]
    B --> C[Generate PDF<br/>Windows]
    B --> D[Send Email<br/>Windows]

🔬 Distributed System Monitoring

"Collect server logs from all Linux machines, analyze for errors, generate alerts, and create a consolidated report."

Workflow DAG:

mermaid
graph LR
    A[Collect Logs<br/>Linux 1] --> D[Analyze Errors<br/>Any]
    B[Collect Logs<br/>Linux 2] --> D
    C[Collect Logs<br/>Linux 3] --> D
    D --> E[Generate Report<br/>Windows]

🏢 Enterprise Automation

"Query the database on the server, process the results, update Excel spreadsheets on Windows, and generate PowerPoint presentations."

Workflow DAG:

mermaid
graph LR
    A[Query DB<br/>Linux] --> B[Process Data<br/>Any]
    B --> C[Update Excel<br/>Windows]
    B --> D[Create PPT<br/>Windows]

🗺️ Documentation Structure

🚀 [Quick Start](../getting_started/quick_start_galaxy.md)

Get UFO³ Galaxy up and running in minutes with our step-by-step guide

👥 [Galaxy Client](client/overview.md)

Device coordination, connection management, and ConstellationClient API

🧠 [Constellation Agent](constellation_agent/overview.md)

LLM-driven task decomposition, DAG creation, and dynamic workflow evolution

⚙️ [Constellation Orchestrator](constellation_orchestrator/overview.md)

Asynchronous execution engine, event-driven coordination, and safety guarantees

📊 [Task Constellation](constellation/overview.md)

DAG structure, TaskStar nodes, TaskStarLine edges, and constellation editor

🆔 [Agent Registration](agent_registration/overview.md)

Device registry, agent profiles, and registration flow

🌐 [Agent Interaction Protocol](../aip/overview.md)

WebSocket messaging, protocol specification, and communication patterns

⚙️ [Configuration](../configuration/system/galaxy_devices.md)

Device pools, capabilities, and orchestration policies


🚦 Getting Started

Ready to build your Digital Agent Galaxy? Follow these steps:

1. Install UFO³

bash
# Clone the repository
git clone https://github.com/microsoft/UFO.git
cd UFO

# Install dependencies
pip install -r requirements.txt

2. Configure Device Pool

Create configuration files in config/galaxy/:

config/galaxy/devices.yaml - Define your devices:

yaml
devices:
  - device_id: "windowsagent"
    server_url: "ws://localhost:5005/ws"
    os: "windows"
    capabilities:
      - "web_browsing"
      - "office_applications"
      - "file_management"
    metadata:
      location: "home_office"
      os: "windows"
      performance: "medium"
    max_retries: 5
    
  - device_id: "linux_agent_1"
    server_url: "ws://localhost:5001/ws"
    os: "linux"
    capabilities:
      - "server"
      - "python"
      - "docker"
    metadata:
      os: "linux"
      performance: "high"
      logs_file_path: "/root/log/log1.txt"
    auto_connect: true
    max_retries: 5
    
  - device_id: "mobile_agent_1"
    server_url: "ws://localhost:5002/ws"
    os: "android"
    capabilities:
      - "mobile"
      - "adb"
      - "ui_automation"
    metadata:
      os: "android"
      performance: "medium"
      device_type: "smartphone"
    auto_connect: true
    max_retries: 5

config/galaxy/constellation.yaml - Configure runtime settings:

yaml
# Constellation Runtime Settings
CONSTELLATION_ID: "my_constellation"
HEARTBEAT_INTERVAL: 30.0  # Heartbeat interval in seconds
RECONNECT_DELAY: 5.0  # Delay before reconnecting in seconds
MAX_CONCURRENT_TASKS: 6  # Maximum concurrent tasks
MAX_STEP: 15  # Maximum steps per session

# Device Configuration
DEVICE_INFO: "config/galaxy/devices.yaml"

# Logging Configuration
LOG_TO_MARKDOWN: true

See Galaxy Configuration for complete documentation.

3. Start Device Agents

On each device, launch the Agent Server. For detailed setup instructions, see the respective quick start guides:

On Windows:

See Windows Agent (UFO²) Quick Start →

On Linux:

See Linux Agent Quick Start →

On Mobile (Android):

See Mobile Agent Quick Start →

4. Launch Galaxy Client

Interactive Mode:

bash
python -m galaxy --interactive

Direct Request:

bash
python -m galaxy "Your cross-device task here"

Programmatic API:

python
from galaxy.galaxy_client import GalaxyClient

async def main():
    client = GalaxyClient(session_name="my_session")
    await client.initialize()
    result = await client.process_request("Your task request")
    await client.shutdown()

For detailed instructions, see the Quick Start Guide.


🔧 System Components

UFO³ Galaxy consists of several integrated components working together:

Core Components

Component Location Responsibility
GalaxyClient galaxy/galaxy_client.py Session management, user interaction, orchestration coordination
ConstellationClient galaxy/client/constellation_client.py Device management, connection lifecycle, task assignment
ConstellationAgent galaxy/agents/constellation_agent.py LLM-driven DAG synthesis and evolution, state machine control
TaskConstellationOrchestrator galaxy/constellation/orchestrator/ Asynchronous execution, event coordination, safety enforcement
TaskConstellation galaxy/constellation/task_constellation.py DAG data structure, validation, and modification APIs
DeviceManager galaxy/client/device_manager.py WebSocket connections, heartbeat monitoring, message routing

Supporting Infrastructure

Component Purpose
Event Bus Publish-subscribe system for constellation events
Observer Pattern Event listeners for visualization and synchronization
Device Registry Centralized device information and capability tracking
Agent Profile Device metadata and capability declarations
MCP Servers Tool augmentation via Model Context Protocol

For detailed component documentation, see the respective sections in Documentation Structure.

Technology Stack

Layer Technologies
Programming Python 3.10+, asyncio, dataclasses
Communication WebSockets, JSON-RPC
LLM Integration OpenAI API, Azure OpenAI, Gemini, Claude, Custom Models
Tool Augmentation Model Context Protocol (MCP)
Configuration YAML, Pydantic models
Logging Python logging, Rich console, Markdown trajectory
Testing pytest, mock agents

🌟 From Devices to Constellations to Galaxy

UFO³ represents a paradigm shift in intelligent automation:

  • Single Device → Isolated agents operating within one OS
  • Task Constellation → Coordinated multi-device workflows for one task
  • Digital Agent Galaxy → Interconnected constellations spanning your entire digital estate

Over time, multiple constellations can interconnect, weaving together agents, devices, and capabilities into a self-organizing Digital Agent Galaxy. This design elevates cross-device automation from a brittle engineering challenge to a unified orchestration paradigm, where multi-device workflows become naturally expressive, paving the way for large-scale, adaptive, and resilient intelligent ubiquitous computing systems.


📊 Performance Monitoring & Evaluation

UFO³ Galaxy provides comprehensive performance monitoring and evaluation tools to analyze multi-device workflow execution:

Automated Metrics Collection

Galaxy automatically collects detailed performance metrics during execution through an event-driven observer pattern:

  • Task Metrics: Execution times, success rates, bottleneck identification
  • Constellation Metrics: DAG statistics, parallelism analysis, critical path computation
  • Modification Metrics: Dynamic editing patterns and adaptation frequency
  • Device Metrics: Per-device performance and resource utilization

All metrics are captured in real-time without impacting execution performance and saved to structured JSON files for programmatic analysis.

Trajectory Report

Galaxy automatically generates a comprehensive Markdown trajectory report (output.md) documenting the complete execution lifecycle:

text
logs/galaxy/<task_name>/output.md

This human-readable report includes:

  • Step-by-step execution timeline with agent actions
  • Interactive DAG topology visualizations showing constellation evolution
  • Detailed task execution logs with results and errors
  • Device connection status and coordination events
  • Complete before/after constellation states at each step

The trajectory report provides visual debugging and workflow understanding, complementing the quantitative result.json metrics.

Result JSON Format

After each session, Galaxy also generates a comprehensive result.json file containing:

text
logs/galaxy/<task_name>/result.json

This file includes:

  • Complete session metadata and execution timeline
  • Task-by-task performance breakdown
  • Constellation statistics (parallelism ratio, critical path, max concurrency)
  • Modification history showing DAG evolution
  • Final results and outcomes

Example Key Metrics:

Metric Description Use Case
parallelism_ratio Efficiency of parallel execution (total_work / critical_path) Optimization target
critical_path_length Minimum possible execution time Theoretical performance limit
average_task_duration Mean task execution time Baseline performance
modification_count Number of dynamic DAG edits Adaptability analysis

Performance Analysis Tools

python
import json

# Load session results
with open("logs/galaxy/task_32/result.json", 'r') as f:
    result = json.load(f)

# Extract key metrics
metrics = result["session_results"]["metrics"]
task_stats = metrics["task_statistics"]
const_stats = result["session_results"]["final_constellation_stats"]

print(f"✅ Success Rate: {task_stats['success_rate'] * 100:.1f}%")
print(f"⏱️  Avg Task Duration: {task_stats['average_task_duration']:.2f}s")
print(f"🔀 Parallelism Ratio: {const_stats['parallelism_ratio']:.2f}")

Documentation:


📚 Learn More


🤝 Contributing

We welcome contributions! Whether you're building new device agents, improving orchestration algorithms, or enhancing the protocol, check out our Contributing Guide on GitHub.


📄 License

UFO³ Galaxy is released under the MIT License.



Documents Docs Linux Overview (`documents/docs/linux/overview.md`)

LinuxAgent: CLI Task Executor

LinuxAgent is a specialized lightweight agent designed for executing command-line instructions on Linux systems. It demonstrates how a standalone device agent can leverage the layered FSM architecture and server-client design to perform intelligent, iterative task execution in a CLI-based environment.

Quick Links:

Architecture Overview

LinuxAgent operates as a single-agent instance that interacts with Linux systems through command-line interface (CLI) commands. Unlike the two-tier architecture of UFO (HostAgent + AppAgent), LinuxAgent uses a simplified single-agent model optimized for shell-based automation.

Core Responsibilities

LinuxAgent provides the following capabilities for Linux CLI automation:

Command-Line Execution

LinuxAgent interprets user requests and translates them into appropriate shell commands for execution on Linux systems.

Example: User request "Check disk space and create a backup" becomes:

  1. Execute df -h to check disk space
  2. Execute tar -czf backup.tar.gz /data to create backup

System Information Collection

The agent can proactively gather system-level information to inform decision-making:

  • Memory usage (free -h)
  • Disk space (df -h)
  • Process status (ps aux)
  • Hardware configuration (lscpu, lshw)

Iterative Task Execution

LinuxAgent executes tasks iteratively, evaluating execution outcomes at each step and determining the next action based on results and LLM reasoning.

Error Handling and Recovery

The agent monitors command execution results (stdout, stderr, exit codes) and can adapt its strategy when errors occur.

Key Characteristics

  • Scope: Single Linux system (CLI-based automation)
  • Lifecycle: One instance per task session
  • Hierarchy: Standalone agent (no child agents)
  • Communication: Direct MCP server integration
  • Control: 3-state finite state machine with 3-phase processing pipeline

Execution Workflow

mermaid
sequenceDiagram
    participant User
    participant LinuxAgent
    participant LLM
    participant MCPServer
    participant Linux
    
    User->>LinuxAgent: "Check disk space and create backup"
    LinuxAgent->>LinuxAgent: State: CONTINUE
    LinuxAgent->>LLM: Send prompt with request & context
    LLM-->>LinuxAgent: Return command: df -h
    LinuxAgent->>MCPServer: execute_command: df -h
    MCPServer->>Linux: Execute command
    Linux-->>MCPServer: stdout + stderr
    MCPServer-->>LinuxAgent: Execution result
    LinuxAgent->>LinuxAgent: Update memory
    
    LinuxAgent->>LLM: Send prompt with previous result
    LLM-->>LinuxAgent: Return command: tar -czf ...
    LinuxAgent->>MCPServer: execute_command: tar -czf backup.tar.gz /data
    MCPServer->>Linux: Execute command
    Linux-->>MCPServer: stdout + stderr
    MCPServer-->>LinuxAgent: Execution result
    LinuxAgent->>LinuxAgent: State: FINISH
    LinuxAgent-->>User: Task completed

Comparison with UFO Agents

Aspect LinuxAgent HostAgent AppAgent
Platform Linux (CLI) Windows Desktop Windows Applications
States 3 (CONTINUE, FINISH, FAIL) 7 states 6 states
Architecture Single-agent Parent orchestrator Child executor
Interface Command-line Desktop GUI + Shell Application GUI + API
Processing Phases 3 phases 4 phases 4 phases
MCP Tools execute_command, get_system_info Desktop commands UI + API commands

Design Principles

LinuxAgent exemplifies a minimal viable design for single-agent systems with a small state set (only 3 states for deterministic control flow), modular strategies (clear separation between LLM interaction, action execution, and memory updates), well-defined commands (atomic CLI operations isolated in MCP server layer), proactive information gathering (on-demand system info collection), and traceable execution (complete logging of commands, results, and state transitions).

Deep Dive Topics

Explore the detailed architecture and implementation:

Use Cases

LinuxAgent is ideal for:

  • System Administration: Automated system maintenance and monitoring
  • DevOps Tasks: Deployment scripts, log analysis, configuration management
  • Data Processing: File operations, text processing, batch jobs
  • Monitoring & Alerts: System health checks and automated responses
  • Cross-Device Workflows: As a sub-agent in Galaxy multi-device orchestration

!!!tip "Galaxy Integration"
LinuxAgent can serve as a device agent in Galaxy's multi-device orchestration framework, executing Linux-specific tasks as part of cross-platform workflows alongside Windows and other devices.

text
See [Using Linux Agent as Galaxy Device](as_galaxy_device.md) for configuration details.

Implementation Location

The LinuxAgent implementation can be found in:

text
ufo/
├── agents/
│   ├── agent/
│   │   └── customized_agent.py          # LinuxAgent class definition
│   ├── states/
│   │   └── linux_agent_state.py         # State machine implementation
│   └── processors/
│       ├── customized/
│       │   └── customized_agent_processor.py  # LinuxAgentProcessor
│       └── strategies/
│           └── linux_agent_strategy.py  # Processing strategies

Next Steps

To understand LinuxAgent's complete architecture:

  1. State Machine - Learn about the 3-state FSM
  2. Processing Strategy - Understand the 3-phase pipeline
  3. MCP Commands - Explore CLI command execution

For deployment and configuration, see the Getting Started Guide.


Documents Docs Mcp Overview (`documents/docs/mcp/overview.md`)

MCP (Model Context Protocol) - Overview

What is MCP?

MCP (Model Context Protocol) is a standardized protocol that enables UFO² agents to interact with external tools and services in a unified way. It provides a tool execution framework where agents can:

  • Collect system state through data collection servers
  • Execute actions through action servers
  • Extend capabilities through custom MCP servers
mermaid
graph TB
    subgraph Agent["UFO² Agent"]
        HostAgent[HostAgent]
        AppAgent[AppAgent]
    end
    
    Computer["Computer<br/>(MCP Tool Manager)"]
    
    subgraph DataServers["Data Collection Servers"]
        UICollector["UICollector<br/>• Screenshots<br/>• Window Info"]
        HWInfo["Hardware Info<br/>• CPU/Memory<br/>• System State"]
    end
    
    subgraph ActionServers["Action Servers"]
        UIExecutor["UIExecutor<br/>• Click/Type<br/>• UI Automation"]
        CLIExecutor["CLI Executor<br/>• Shell Commands"]
        COMExecutor["COM Executor<br/>• API Calls"]
    end
    
    HostAgent --> Computer
    AppAgent --> Computer
    Computer --> DataServers
    Computer --> ActionServers
    
    style Agent fill:#e3f2fd,stroke:#1976d2,stroke-width:2px
    style Computer fill:#fff3e0,stroke:#f57c00,stroke-width:2px
    style DataServers fill:#e8f5e9,stroke:#388e3c,stroke-width:2px
    style ActionServers fill:#fce4ec,stroke:#c2185b,stroke-width:2px

MCP serves as the execution layer in UFO²'s architecture. While agents make decisions about what to do, MCP servers handle how to do it by providing concrete tool implementations.

Key Concepts

1. Two Server Types

MCP servers in UFO² are categorized into two types based on their purpose:

Type Purpose Examples Side Effects LLM Selectable?
Data Collection Retrieve system stateRead-only operations UI detection, Screenshot, System info ❌ None ❌ No - Auto-invoked
Action Modify system stateState-changing operations Click, Type text, Run command ✅ Yes ✅ Yes - LLM chooses

Server Selection Model:

  • Data Collection Servers: Automatically invoked by the framework to gather context and build observation prompts. Not selectable by LLM.
  • Action Servers: LLM agent actively selects which action tool to execute at each step based on the task. Only action tools are LLM-selectable.

How Action Tools Reach the LLM: Each action tool's Annotated type hints and docstring are automatically extracted and converted into structured instructions that appear in the LLM's prompt. The LLM uses these instructions to understand what each tool does, what parameters it requires, and when to use it. Therefore, developers should write clear, comprehensive docstrings and type annotations - they directly impact the LLM's ability to use the tool correctly.

2. Server Deployment Models

UFO² supports three deployment models for MCP servers:

Model Description Benefits Trade-offs
Local (In-Process) Server runs in same process as agent Fast (no IPC overhead), Simple setup Shares process resources
HTTP (Remote) Server runs as HTTP service (e.g., Port 8006) Process isolation, Language-agnostic Network overhead
Stdio (Process) Server runs as child process using stdin/stdout Process isolation, Bidirectional streaming Platform-specific

3. Namespace Isolation

Each MCP server has a namespace that groups related tools together:

yaml
# Example: HostAgent configuration
HostAgent:
  default:
    data_collection:
      - namespace: UICollector          # Namespace for UI detection tools
        type: local
    action:
      - namespace: HostUIExecutor       # Namespace for UI automation tools
        type: local
      - namespace: CommandLineExecutor  # Namespace for CLI tools
        type: local

Tool Key Format: {tool_type}::{tool_name}

  • Example: data_collection::screenshot - Screenshot tool in data_collection
  • Example: action::click - Click tool in action
  • Example: action::run_shell - Shell command in action

Key Features

1. GUI + API Dual-Mode Automation

UFO² supports both GUI automation and API-based automation simultaneously. Each agent can register multiple action servers, combining:

  • GUI Automation: Windows UI Automation (UIA) - clicking, typing, scrolling when visual interaction is needed
  • API Automation: Direct COM API calls, shell commands, REST APIs for efficient, reliable operations

The LLM agent dynamically chooses the best action at each step based on task requirements, reliability, speed, and availability.

Example: Word Document Automation

yaml
AppAgent:
  WINWORD.EXE:
    action:
      - namespace: WordCOMExecutor      # API: Fast, reliable
      - namespace: AppUIExecutor        # GUI: Visual navigation fallback  
      - namespace: CommandLineExecutor  # Shell: File operations

LLM's Dynamic Selection:

text
Task: "Create a report with a 3x2 table and bold the title"

Step 1: Insert table
  → LLM selects: WordCOMExecutor::insert_table(rows=3, cols=2)
  → Reason: API is fast, reliable, no GUI navigation needed

Step 2: Navigate to Design tab  
  → LLM selects: AppUIExecutor::click_input(id="5", name="Design")
  → Reason: Visual navigation, COM API doesn't expose tab selection

Step 3: Type table header
  → LLM selects: AppUIExecutor::set_edit_text(id="cell_1_1", text="Product")
  → Reason: GUI interaction needed for cell input

Step 4: Bold title text
  → LLM selects: WordCOMExecutor::select_text(text="Report Title")
  →            WordCOMExecutor::set_font(font_size=16)
  → Reason: API is more reliable than GUI button clicking

Step 5: Save as PDF
  → LLM selects: WordCOMExecutor::save_as(file_ext=".pdf")
  → Reason: One API call vs. multiple GUI clicks (File → Save As → Format → PDF)

Why Hybrid Automation Matters:

  • APIs: ~10x faster, deterministic, no visual dependency
  • GUI: Handles visual elements, fallback when API unavailable
  • LLM Decision: Chooses optimal approach per step, not locked into one mode

2. Multi-Server Per Agent

Each agent can register multiple action servers, each providing a different set of tools:

HostAgent Example:

yaml
HostAgent:
  default:
    data_collection:
      - UICollector           # Automatically invoked
    action:
      - HostUIExecutor        # LLM selects: Window selection
      - CommandLineExecutor   # LLM selects: Launch apps, shell commands

AppAgent Example (Word-specific):

yaml
AppAgent:
  WINWORD.EXE:
    data_collection:
      - UICollector           # Automatically invoked
    action:
      - WordCOMExecutor       # LLM selects: insert_table, select_text, save_as
      - AppUIExecutor         # LLM selects: click_input, set_edit_text
      - CommandLineExecutor   # LLM selects: run_shell

HardwareAgent Example (Cross-platform):

yaml
HardwareAgent:
  default:
    data_collection:
      - HardwareCollector     # Auto-invoked (HTTP remote)
    action:
      - HardwareExecutor      # LLM selects: touch_screen, swipe, press_key (HTTP remote)

At each step, the LLM sees all available action tools and selects the most appropriate one.

3. Process Isolation

MCP servers can run:

  • In-process (local): Fast, low overhead
  • HTTP (remote): Process isolation, cross-platform, distributed
  • Stdio (child process): Sandboxed execution, clean resource management

4. Namespace Isolation

Each MCP server has a unique namespace that groups related tools together, preventing naming conflicts and enabling modular organization. See Namespace Isolation section above for details.

Architecture

MCP Server Lifecycle

mermaid
graph TB
    Start([MCP Server Lifecycle])
    
    Config["1. Configuration Loading<br/>(mcp.yaml)"]
    Manager["2. MCPServerManager<br/>Creates BaseMCPServer"]
    ServerStart["3. Server.start()<br/>• Local: Get from registry<br/>• HTTP: Build URL<br/>• Stdio: Spawn process"]
    Register["4. Computer Registration<br/>• List tools from server<br/>• Register in tool registry"]
    Execute["5. Tool Execution<br/>• Agent sends Command<br/>• Computer routes to tool<br/>• MCP server executes"]
    Reset["6. Server.reset() (optional)<br/>Reset server state"]
    
    Start --> Config
    Config --> Manager
    Manager --> ServerStart
    ServerStart --> Register
    Register --> Execute
    Execute --> Reset
    
    style Start fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px
    style Config fill:#e1f5fe,stroke:#0277bd,stroke-width:2px
    style Manager fill:#fff9c4,stroke:#f57f17,stroke-width:2px
    style ServerStart fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px
    style Register fill:#fce4ec,stroke:#c2185b,stroke-width:2px
    style Execute fill:#e0f2f1,stroke:#00695c,stroke-width:2px
    style Reset fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px

Component Relationships

mermaid
graph TB
    subgraph Architecture["MCP Architecture"]
        Registry["MCPRegistry (Singleton)<br/>• Stores server factories<br/>• Lazy initialization"]
        
        Manager["MCPServerManager (Singleton)<br/>• Creates server instances<br/>• Maps server types to classes<br/>• Manages server lifecycle"]
        
        subgraph ServerTypes["MCP Server Types"]
            Local["Local MCP Server<br/>(In-Process)"]
            HTTP["HTTP MCP Server<br/>(Remote)"]
            Stdio["Stdio MCP Server<br/>(Child Process)"]
        end
        
        Computer["Computer (Per Agent)<br/>• Manages multiple MCP servers<br/>• Routes commands to tools<br/>• Maintains tool registry"]
        
        Registry --> Manager
        Manager --> ServerTypes
        Manager --> Computer
    end
    
    style Architecture fill:#fafafa,stroke:#424242,stroke-width:2px
    style Registry fill:#e1f5fe,stroke:#01579b,stroke-width:2px
    style Manager fill:#fff9c4,stroke:#f57f17,stroke-width:2px
    style ServerTypes fill:#e8f5e9,stroke:#1b5e20,stroke-width:2px
    style Local fill:#c8e6c9,stroke:#2e7d32,stroke-width:1px
    style HTTP fill:#c8e6c9,stroke:#2e7d32,stroke-width:1px
    style Stdio fill:#c8e6c9,stroke:#2e7d32,stroke-width:1px
    style Computer fill:#fce4ec,stroke:#880e4f,stroke-width:2px

Built-in MCP Servers

UFO² comes with several built-in MCP servers that cover common automation scenarios:

Data Collection Servers

Namespace Purpose Key Tools Platform
UICollector UI element detection get_control_info, take_screenshot, get_window_list Windows
HardwareCollector Hardware information get_cpu_info, get_memory_info Cross-platform
MobileDataCollector Android device observation capture_screenshot, get_ui_tree, get_device_info, get_mobile_app_target_info Android (ADB)

Action Servers

Namespace Purpose Key Tools Platform
HostUIExecutor UI automation (host-level) click, type_text, scroll Windows
AppUIExecutor UI automation (app-level) click, type_text, set_edit_text Windows
CommandLineExecutor CLI execution run_shell Cross-platform
WordCOMExecutor Word automation insert_table, select_text, format_text Windows
ExcelCOMExecutor Excel automation insert_cell, select_range, format_cell Windows
PowerPointCOMExecutor PowerPoint automation insert_slide, add_text, format_shape Windows
ConstellationEditor Multi-device coordination create_task, assign_device Cross-platform
BashExecutor Linux commands execute_bash Linux
MobileExecutor Android device control tap, swipe, type_text, launch_app, click_control Android (ADB)

!!!example "Tool Examples"
```python
# Data Collection: Take a screenshot
{
"tool_type": "data_collection",
"tool_name": "take_screenshot",
"parameters": {"region": "active_window"}
}

text
# Action: Click a button
{
    "tool_type": "action",
    "tool_name": "click",
    "parameters": {"control_label": "Submit"}
}

# Action: Run a shell command
{
    "tool_type": "action",
    "tool_name": "run_shell",
    "parameters": {"bash_command": "notepad.exe"}
}
```

Agent-Specific Configurations

Different agents can have different MCP configurations based on their roles:

yaml
# HostAgent: System-level operations
HostAgent:
  default:
    data_collection:
      - namespace: UICollector
        type: local
    action:
      - namespace: HostUIExecutor
        type: local
      - namespace: CommandLineExecutor
        type: local

# AppAgent: Application-specific operations
AppAgent:
  WINWORD.EXE:  # Word-specific configuration
    data_collection:
      - namespace: UICollector
        type: local
    action:
      - namespace: AppUIExecutor
        type: local
      - namespace: WordCOMExecutor  # Word COM API
        type: local
        reset: true  # Reset when switching documents

# HardwareAgent: Remote hardware monitoring
HardwareAgent:
  default:
    data_collection:
      - namespace: HardwareCollector
        type: http  # Remote server
        host: "localhost"
        port: 8006
        path: "/mcp"

# MobileAgent: Android device automation
MobileAgent:
  default:
    data_collection:
      - namespace: MobileDataCollector
        type: http  # Remote server
        host: "localhost"
        port: 8020
        path: "/mcp"
    action:
      - namespace: MobileExecutor
        type: http
        host: "localhost"
        port: 8021
        path: "/mcp"

Configuration Hierarchy:

Agent configurations follow this hierarchy:

  1. Agent Name (e.g., HostAgent, AppAgent)
  2. Sub-type (e.g., default, WINWORD.EXE)
  3. Tool Type (e.g., data_collection, action)
  4. Server List (array of server configurations)

Key Features

1. Process Isolation with Reset

Some MCP servers support state reset to ensure clean execution:

yaml
AppAgent:
  WINWORD.EXE:
    action:
      - namespace: WordCOMExecutor
        type: local
        reset: true

**When to use reset:**

- Server state is cleared when switching contexts
- Prevents state leakage between tasks
- Useful for stateful tools (e.g., COM APIs)

### 2. Thread Isolation

MCP tools execute in **isolated thread pools** to prevent blocking:

```python
# From Computer class
self._executor = ThreadPoolExecutor(max_workers=10)
self._tool_timeout = 6000  # 100 minutes

Benefits:

  • Prevents blocking the main event loop
  • Protects WebSocket connections from timeouts
  • Enables concurrent tool execution

Timeout Protection: If a tool takes longer than 6000 seconds, it will be cancelled and return a timeout error. Adjust _tool_timeout for long-running operations.

3. Dynamic Server Management

Add or remove MCP servers at runtime:

python
# Add a custom server
await computer.add_server(
    namespace="CustomTools",
    mcp_server=custom_server,
    tool_type="action"
)

# Remove a server
await computer.delete_server(
    namespace="CustomTools",
    tool_type="action"
)

4. Tool Introspection

Use meta tools to discover available tools:

python
# List all action tools
tool_call = MCPToolCall(
    tool_key="action::list_tools",
    tool_name="list_tools",
    parameters={"tool_type": "action"}
)

result = await computer.run_actions([tool_call])
# Returns: List of all available action tools

For more details on introspection capabilities, see Computer - Meta Tools.

Configuration Files

MCP configuration is located at:

text
config/ufo/mcp.yaml

For detailed configuration options, see:

Use Cases

1. UI Automation

yaml
# Agent that automates UI interactions
HostAgent:
  default:
    data_collection:
      - namespace: UICollector        # Detect UI elements
    action:
      - namespace: HostUIExecutor     # Click, type, scroll

2. Document Processing

yaml
# Agent specialized for Word documents
AppAgent:
  WINWORD.EXE:
    data_collection:
      - namespace: UICollector        # Read document structure
    action:
      - namespace: WordCOMExecutor    # Insert tables, format text

3. Multi-Device Coordination

yaml
# Agent that coordinates tasks across devices
ConstellationAgent:
  default:
    action:
      - namespace: ConstellationEditor  # Create and assign tasks

4. Remote Hardware Monitoring

yaml
# Agent that monitors remote hardware
HardwareAgent:
  default:
    data_collection:
      - namespace: HardwareCollector
        type: http
        host: "192.168.1.100"
        port: 8006

5. Android Device Automation

yaml
# Agent that automates Android devices via ADB
MobileAgent:
  default:
    data_collection:
      - namespace: MobileDataCollector
        type: http
        host: "localhost"  # Or remote Android automation server
        port: 8020
        path: "/mcp"
    action:
      - namespace: MobileExecutor
        type: http
        host: "localhost"
        port: 8021
        path: "/mcp"

Getting Started

To start using MCP in UFO²:

  1. Understand the two server types - Read about Data Collection and Action servers
  2. Configure your agents - See Configuration Guide for setup details
  3. Use built-in servers - Explore available Local Servers
  4. Create custom servers - Follow the Creating Custom MCP Servers Tutorial
  5. Deploy remotely - Learn about Remote Servers deployment

Design Philosophy:

MCP in UFO² follows the separation of concerns principle:

  • Agents decide what to do (high-level planning)
  • MCP servers implement how to do it (low-level execution)
  • Computer manages the routing between them (middleware)

This architecture enables flexibility, extensibility, and maintainability.


Documents Docs Mobile Overview (`documents/docs/mobile/overview.md`)

MobileAgent: Android Task Executor

MobileAgent is a specialized agent designed for executing tasks on Android mobile devices. It leverages the layered FSM architecture and server-client design to perform intelligent, iterative task execution in mobile environments through UI interaction and app control.

Quick Links:

Architecture Overview

MobileAgent operates as a single-agent instance that interacts with Android devices through UI controls and app management. Unlike the two-tier architecture of UFO (HostAgent + AppAgent), MobileAgent uses a simplified single-agent model optimized for mobile device automation, similar to LinuxAgent but with visual interface support.

Core Responsibilities

MobileAgent provides the following capabilities for Android device automation:

UI Interaction

MobileAgent interprets user requests and translates them into appropriate UI interactions on Android devices through screenshots analysis and control manipulation.

Example: User request "Search for restaurants on Maps" becomes:

  1. Take screenshot and identify app icons
  2. Launch Google Maps app
  3. Identify search field control
  4. Type "restaurants" into search field
  5. Tap search button

Visual Context Understanding

The agent captures and analyzes device screenshots to understand the current UI state:

  • Screenshot capture (clean and annotated)
  • Control identification and labeling
  • UI hierarchy parsing
  • App detection and recognition

App Management

MobileAgent can manage installed applications:

  • List installed apps (user apps and system apps)
  • Launch apps by package name or app name
  • Switch between apps
  • Monitor current app state

Iterative Task Execution

MobileAgent executes tasks iteratively, evaluating execution outcomes at each step and determining the next action based on results and LLM reasoning.

Error Handling and Recovery

The agent monitors action execution results and can adapt its strategy when errors occur, such as controls not found or apps not responding.

Key Characteristics

  • Scope: Single Android device (UI-based automation)
  • Lifecycle: One instance per task session
  • Hierarchy: Standalone agent (no child agents)
  • Communication: MCP server integration via ADB
  • Control: 3-state finite state machine with 4-phase processing pipeline
  • Visual: Screenshot-based UI understanding with control annotation

Execution Workflow

text
/* Detailed source-code truncated for AI context efficiency. */

Comparison with Other Agents

Aspect MobileAgent LinuxAgent AppAgent
Platform Android Mobile Linux (CLI) Windows Applications
States 3 (CONTINUE, FINISH, FAIL) 3 states 6 states
Architecture Single-agent Single-agent Child executor
Interface Mobile UI (touch-based) Command-line Desktop GUI
Processing Phases 4 phases (with DATA_COLLECTION) 3 phases 4 phases
Visual ✓ Screenshots + Annotations ✗ Text-only ✓ Screenshots + Annotations
MCP Tools UI controls + App management CLI commands UI controls + API
Input Method Touch (tap, swipe, type) Keyboard commands Mouse + Keyboard
Control Identification UI hierarchy + bounds N/A UI Automation API

Design Principles

MobileAgent exemplifies mobile-specific design considerations:

  • Visual Context: Screenshot-based UI understanding with control annotation for precise interaction
  • Control Caching: Efficient control information caching to reduce ADB overhead
  • Touch-based Interaction: Specialized actions for mobile gestures (tap, swipe, long-press)
  • App-centric Navigation: Focus on app launching and switching rather than window management
  • Minimal State Set: 3-state FSM for deterministic control flow
  • Modular Strategies: Clear separation between data collection, LLM interaction, action execution, and memory updates
  • Traceable Execution: Complete logging of screenshots, actions, and state transitions

Deep Dive Topics

Explore the detailed architecture and implementation:

Technology Stack

ADB (Android Debug Bridge)

MobileAgent relies on ADB for all device interactions:

  • Screenshot Capture: adb shell screencap for visual context
  • UI Hierarchy: adb shell uiautomator dump for control information
  • Touch Input: adb shell input tap/swipe for user interaction
  • Text Input: adb shell input text for typing
  • App Control: adb shell monkey for app launching
  • Device Info: adb shell getprop for device properties

MCP Server Architecture

Two separate MCP servers handle different responsibilities:

  1. Data Collection Server (Port 8020):

    • Screenshot capture
    • UI tree retrieval
    • App list collection
    • Control information gathering
    • Device information
  2. Action Server (Port 8021):

    • Touch actions (tap, swipe)
    • Text input
    • App launching
    • Key press events
    • Control clicking

Both servers share a singleton MobileServerState for efficient caching and coordination.

Use Cases

MobileAgent is ideal for:

  • Mobile App Testing: Automated UI testing across different apps
  • Cross-App Workflows: Tasks spanning multiple mobile applications
  • Data Entry: Automated form filling and text input
  • App Navigation: Exploring and interacting with mobile UIs
  • Mobile Productivity: Automating repetitive mobile tasks
  • Cross-Device Workflows: As a sub-agent in Galaxy multi-device orchestration

!!!tip "Galaxy Integration"
MobileAgent can serve as a device agent in Galaxy's multi-device orchestration framework, executing Android-specific tasks as part of cross-platform workflows alongside Windows and Linux devices.

text
See [Using Mobile Agent as Galaxy Device](as_galaxy_device.md) for configuration details.

Requirements

Hardware

  • Android device or emulator
  • USB connection (for physical devices) or network connection (for emulators)
  • USB debugging enabled on the device

Software

  • ADB (Android Debug Bridge) installed and accessible
  • Android device with API level 21+ (Android 5.0+)
  • Python 3.8+
  • Required Python packages (see requirements.txt)

Implementation Location

The MobileAgent implementation can be found in:

text
ufo/
├── agents/
│   ├── agent/
│   │   └── customized_agent.py          # MobileAgent class definition
│   ├── states/
│   │   └── mobile_agent_state.py        # State machine implementation
│   └── processors/
│       ├── customized/
│       │   └── customized_agent_processor.py  # MobileAgentProcessor
│       └── strategies/
│           └── mobile_agent_strategy.py # Processing strategies
├── prompter/
│   └── customized/
│       └── mobile_agent_prompter.py     # Prompt construction
├── module/
│   └── sessions/
│       └── mobile_session.py            # Session management
└── client/
    └── mcp/
        └── http_servers/
            └── mobile_mcp_server.py     # MCP server implementation

Next Steps

To understand MobileAgent's complete architecture:

  1. State Machine - Learn about the 3-state FSM
  2. Processing Strategy - Understand the 4-phase pipeline
  3. MCP Commands - Explore mobile UI interaction commands
  4. As Galaxy Device - Configure for multi-device workflows

For deployment and configuration, see the Quick Start Guide (coming soon).


Documents Docs Server Overview (`documents/docs/server/overview.md`)

Agent Server Overview

The Agent Server is the central orchestration engine that transforms UFO into a distributed multi-agent system, enabling seamless task coordination across heterogeneous devices through persistent WebSocket connections and robust state management.

New to the Agent Server? Start with the Quick Start Guide to get up and running in minutes.

What is the Agent Server?

The Agent Server is a FastAPI-based asynchronous WebSocket server that serves as the communication hub for UFO's distributed architecture. It bridges constellation orchestrators, device agents, and external systems through a unified protocol interface.

Core Responsibilities

Capability Description Key Benefit
🔌 Connection Management Tracks device & constellation client lifecycles Real-time device availability awareness
🎯 Task Orchestration Coordinates execution across distributed devices Centralized workflow control
💾 State Management Maintains session lifecycles & execution contexts Stateful multi-turn task execution
🌐 Dual API Interface WebSocket (AIP) + HTTP (REST) endpoints Flexible integration options
🛡️ Resilience Handles disconnections, timeouts, failures gracefully Production-grade reliability

Why Use the Agent Server?

  • Centralized Control: Single point of orchestration for multi-device workflows
  • Protocol Abstraction: Clients communicate via AIP, hiding network complexity
  • Async by Design: Non-blocking execution enables high concurrency
  • Platform Agnostic: Supports Windows, Linux, macOS (in development)

The Agent Server is part of UFO's distributed server-client architecture, where it handles orchestration and state management while Agent Clients handle command execution. See Server-Client Architecture for the complete design rationale and communication patterns.


Architecture

The server follows a clean separation of concerns with distinct layers for web service, connection management, and protocol handling.

Architectural Overview

Component Interaction Diagram:

mermaid
graph TB
    subgraph "Web Layer"
        FastAPI[FastAPI App]
        HTTP[HTTP API]
        WS[WebSocket /ws]
    end
    
    subgraph "Service Layer"
        WSM[Client Manager]
        SM[Session Manager]
        WSH[WebSocket Handler]
    end
    
    subgraph "Clients"
        DC[Device Clients]
        CC[Constellation Clients]
    end
    
    FastAPI --> HTTP
    FastAPI --> WS
    
    HTTP --> SM
    HTTP --> WSM
    WS --> WSH
    
    WSH --> WSM
    WSH --> SM
    
    DC -->|WebSocket| WS
    CC -->|WebSocket| WS
    
    style FastAPI fill:#e1f5ff
    style WSM fill:#fff4e1
    style SM fill:#f0ffe1
    style WSH fill:#ffe1f5

This layered design ensures each component has a single, well-defined responsibility. The managers maintain state while the handler implements protocol logic.

Core Components

Component Responsibility Key Operations
FastAPI Application Web service layer ✅ HTTP endpoint routing
✅ WebSocket connection acceptance
✅ Request/response handling
✅ CORS and middleware
Client Connection Manager Connection registry ✅ Client identity tracking
✅ Session ↔ client mapping
✅ Device info caching
✅ Connection lifecycle hooks
Session Manager Execution lifecycle ✅ Platform-specific session creation
✅ Background async task execution
✅ Result callback delivery
✅ Session cancellation
WebSocket Handler Protocol implementation ✅ AIP message parsing/routing
✅ Client registration
✅ Heartbeat monitoring
✅ Task/command dispatch

Component Documentation:


Key Capabilities

1. Multi-Client Coordination

The server supports two distinct client types with different roles in the distributed architecture.

Client Type Comparison:

Aspect Device Client Constellation Client
Role Task executor Task orchestrator
Connection Long-lived WebSocket Long-lived WebSocket
Registration ClientType.DEVICE ClientType.CONSTELLATION
Capabilities Local execution, telemetry Multi-device coordination
Target Field Not required Required for routing
Example Windows agent, Linux agent ConstellationClient orchestrator

Device Clients

  • Execute tasks locally on Windows/Linux machines
  • Report hardware specs and real-time status
  • Respond to commands via MCP tool servers
  • Stream execution logs back to server

See Agent Client Overview for detailed client architecture.

Constellation Clients

  • Orchestrate multi-device workflows from a central point
  • Dispatch tasks to specific target devices via target_id
  • Coordinate complex cross-device DAG execution
  • Aggregate results from multiple devices

Both client types connect to /ws and register using the REGISTER message. The server differentiates behavior based on client_type field. For the complete server-client architecture and design rationale, see Server-Client Architecture.

See Quick Start for registration examples.


2. Session Lifecycle Management

Unlike stateless HTTP servers, the Agent Server maintains session state throughout task execution, enabling multi-turn interactions and result callbacks.

Session Lifecycle State Machine:

mermaid
stateDiagram-v2
    [*] --> Created: create_session()
    Created --> Running: Start execution
    Running --> Completed: Success
    Running --> Failed: Error
    Running --> Cancelled: Disconnect
    Completed --> [*]
    Failed --> [*]
    Cancelled --> [*]
    
    note right of Running
        Async background execution
        Non-blocking server
    end note

Lifecycle Stages:

Stage Trigger Session Manager Action Server State
Created HTTP dispatch or AIP TASK Platform-specific session instantiation Session ID generated
Running Background task start Async execution without blocking Awaiting results
Completed TASK_END (success) Callback delivery to client Results cached
Failed TASK_END (error) Error callback delivery Error logged
Cancelled Client disconnect Cancel async task, cleanup Session removed

!!!warning "Platform-Specific Sessions"
The SessionManager creates different session types based on the target platform:
- Windows: WindowsSession with UI automation support
- Linux: LinuxSession with bash automation
- Auto-detected or overridden via --platform flag

Session Manager Responsibilities:

  • ✅ Platform abstraction: Hides Windows/Linux differences
  • ✅ Background execution: Non-blocking async task execution
  • ✅ Callback routing: Delivers results via WebSocket
  • ✅ Resource cleanup: Cancels tasks on disconnect
  • ✅ Result caching: Stores results for HTTP retrieval

3. Resilient Communication

The server implements the Agent Interaction Protocol (AIP), providing structured, type-safe communication with automatic failure handling.

Protocol Features:

Feature Implementation Benefit
Structured Messages Pydantic models with validation Type safety, automatic serialization
Connection Health Heartbeat every 20-30s Early failure detection
Error Recovery Exponential backoff reconnection Transient fault tolerance
State Tracking Session client mapping Proper cleanup on disconnect
Message Correlation request_id, prev_response_id chains Request-response tracing

Disconnection Handling Flow:

mermaid
sequenceDiagram
    participant Client
    participant Server
    participant SM as Session Manager
    
    Client-xServer: Connection lost
    Server->>SM: Cancel sessions
    SM->>SM: Cleanup resources
    Server->>Server: Remove from registry
    
    Note over Server: Client can reconnectwith same client_id

!!!danger "Important: Session Cancellation on Disconnect"
When a client disconnects (device or constellation), all associated sessions are immediately cancelled to prevent orphaned tasks and resource leaks.


4. Dual API Interface

The server provides two API styles to support different integration patterns: real-time WebSocket for agents and simple HTTP for external systems.

WebSocket API (AIP-based)

Purpose: Real-time bidirectional communication with agent clients

Message Type Direction Purpose
REGISTER Client Server Initial capability advertisement
TASK Server Client Task assignment with commands
COMMAND Server Client Individual command execution
COMMAND_RESULTS Client Server Execution results
TASK_END Bidirectional Task completion notification
HEARTBEAT Bidirectional Connection keepalive
DEVICE_INFO_REQUEST/RESPONSE Bidirectional Telemetry exchange
ERROR Bidirectional Error condition reporting

!!!example "WebSocket Connection"
```python
import websockets

text
async with websockets.connect("ws://localhost:5000/ws") as ws:
    # Register as device client
    await ws.send(json.dumps({
        "message_type": "REGISTER",
        "client_id": "windows_agent_001",
        "client_type": "device",
        "metadata": {"platform": "windows", "gpu": "NVIDIA RTX 3080"}
    }))
```

HTTP REST API

Purpose: Task dispatch and monitoring from external systems (HTTP clients, CI/CD, etc.)

Endpoint Method Purpose Authentication
/api/dispatch POST Dispatch task to device Optional (if configured)
/api/task_result/{task_name} GET Retrieve task results Optional
/api/clients GET List connected clients Optional
/api/health GET Server health check None

!!!example "HTTP Task Dispatch"
```bash
# Dispatch task to device
curl -X POST http://localhost:5000/api/dispatch
-H "Content-Type: application/json"
-d '{
"client_id": "my_windows_device",
"request": "Open Notepad and type Hello World",
"task_name": "test_task_001"
}'

text
# Response: {"status": "dispatched", "session_id": "session_abc123", "task_name": "test_task_001"}

# Retrieve results
curl http://localhost:5000/api/task_result/test_task_001
```

See HTTP API Reference for complete endpoint documentation.


Workflow Examples

Complete Task Dispatch Flow

End-to-End HTTP WebSocket Device Execution:

mermaid
sequenceDiagram
    participant EXT as External System
    participant HTTP as HTTP API
    participant SM as Session Manager
    participant WSH as WebSocket Handler
    participant DC as Device Client
    
    EXT->>HTTP: POST /api/dispatch{client_id, request, task_name}
    HTTP->>SM: create_session()
    SM->>SM: Create platform session
    SM-->>HTTP: session_id
    HTTP-->>EXT: 200 {session_id, task_name}
    
    SM->>WSH: send_task(session_id, task)
    WSH->>DC: TASK message (AIP)
    DC-->>WSH: ACK
    
    rect rgb(240, 255, 240)
        Note over DC: Background Execution
        DC->>DC: Execute via MCP tools
        DC->>DC: Generate results
    end
    
    DC->>WSH: COMMAND_RESULTS
    WSH->>SM: on_result_callback()
    SM->>SM: Cache results
    
    DC->>WSH: TASK_END (COMPLETED)
    WSH->>SM: on_task_end()
    
    EXT->>HTTP: GET /task_result/{session_id}
    HTTP->>SM: get_results()
    SM-->>HTTP: results
    HTTP-->>EXT: 200 {results}

The green box highlights async execution on the device side, which doesn't block the server.

Multi-Device Constellation Workflow

Constellation Client Coordinating Multiple Devices:

mermaid
sequenceDiagram
    participant CC as Constellation Client
    participant Server as Agent Server
    participant D1 as Device 1 (GPU)
    participant D2 as Device 2 (CPU)
    
    CC->>Server: REGISTER (constellation)
    Server-->>CC: HEARTBEAT (OK)
    
    Note over CC: Plan multi-device DAG
    
    CC->>Server: TASK (target: device_1)Subtask 1: Image processing
    Server->>D1: TASK (forward)
    
    CC->>Server: TASK (target: device_2)Subtask 2: Data extraction
    Server->>D2: TASK (forward)
    
    par Parallel Execution
        D1->>D1: Process image on GPU
        D2->>D2: Extract data from DB
    end
    
    D1->>Server: COMMAND_RESULTS
    Server->>CC: COMMAND_RESULTS (from device_1)
    
    D2->>Server: COMMAND_RESULTS
    Server->>CC: COMMAND_RESULTS (from device_2)
    
    Note over CC: Combine results,Update DAG
    
    D1->>Server: TASK_END
    D2->>Server: TASK_END
    Server->>CC: TASK_END (both tasks)

The server acts as a message router, forwarding tasks to target devices and routing results back to the constellation orchestrator. See Constellation Documentation for more details on multi-device orchestration.


Platform Support

The server automatically detects client platforms and creates appropriate session implementations.

Supported Platforms:

Platform Session Type Capabilities Status
Windows WindowsSession UI automation (UIA)
COM API integration
Native app control
Screenshot capture
Full support
Linux LinuxSession Bash automation
GUI tools (xdotool)
Package management
Process control
Full support
macOS (Planned) AppleScript
UI automation
Native app control
🚧 In development

Platform Auto-Detection:

The server automatically detects the client's platform during registration. You can override this globally with the --platform flag when needed for testing or specific deployment scenarios.

bash
python -m ufo.server.app --platform windows  # Force Windows sessions
python -m ufo.server.app --platform linux    # Force Linux sessions
python -m ufo.server.app                     # Auto-detect (default)

!!!warning "When to Use Platform Override"
Use --platform override when:
- Testing cross-platform sessions without actual devices
- Running server in container different from target platform
- Debugging platform-specific session behavior

For more details on platform-specific implementations, see Windows Agent and Linux Agent.


Configuration

The server runs out-of-the-box with sensible defaults. Advanced configuration inherits from UFO's central config system.

Command-Line Arguments

bash
python -m ufo.server.app [OPTIONS]

Available Options:

Option Type Default Description
--port int 5000 Server listening port
--host str 0.0.0.0 Bind address (use 127.0.0.1 for localhost only)
--platform str auto Force platform (windows, linux)
--log-level str INFO Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL, OFF)
--local flag False Restrict to local connections only

!!!example "Configuration Examples"
```bash
# Development: Local-only with debug logging
python -m ufo.server.app --local --log-level DEBUG --port 8000

text
# Production: External access, info logging
python -m ufo.server.app --host 0.0.0.0 --port 5000 --log-level INFO

# Testing: Force Linux sessions
python -m ufo.server.app --platform linux --port 9000
```

UFO Configuration Inheritance

The server uses UFO's central configuration from config_dev.yaml:

Config Section Inherited Settings
Agent Strategies HostAgent, AppAgent, EvaluationAgent configurations
LLM Models Model endpoints, API keys, temperature settings
Automators UI automation, COM API, web automation configs
Logging Log file paths, rotation, format
Prompts Agent system prompts, example templates

See Configuration Guide for comprehensive config documentation.


Monitoring & Operations

Health Monitoring

Monitor server status and performance using HTTP endpoints.

Health Check Endpoints:

bash
# Server health and uptime
curl http://localhost:5000/api/health

# Response:
# {
#   "status": "healthy",
#   "online_clients": [...]
# }

# Connected clients list
curl http://localhost:5000/api/clients

# Response:
# {
#   "online_clients": ["windows_001", "linux_002", ...]
# }

For comprehensive monitoring strategies including performance metrics collection, log aggregation patterns, alert configuration, and dashboard setup, see Monitoring Guide.

Error Handling

The server handles common failure scenarios gracefully to maintain system stability.

Disconnection Handling Matrix:

Scenario Server Detection Automatic Action Client Impact
Device Disconnect Heartbeat timeout / WebSocket close Cancel device sessions, notify constellation Task fails, constellation retries
Constellation Disconnect Heartbeat timeout / WebSocket close Continue device execution, skip callbacks Device completes but results not delivered
Task Execution Failure TASK_END with error status Log error, store in results Client receives error via callback/HTTP
Network Partition Heartbeat timeout Mark disconnected, enable reconnection Client reconnects with same ID
Server Crash N/A Clients detect via heartbeat Clients reconnect to new instance

!!!note "Reconnection Support"
Clients can reconnect with the same client_id. The server will re-register the client and restore heartbeat monitoring, but will not restore previous sessions (sessions are ephemeral).


Best Practices

Development Environment

Optimize your development workflow with these recommended practices.

Recommended Development Configuration:

bash
# Isolate to localhost, enable detailed logging
python -m ufo.server.app \
  --host 127.0.0.1 \
  --port 5000 \
  --local \
  --log-level DEBUG

Development Checklist:

  • Use --local flag to prevent external access
  • Enable DEBUG logging for detailed traces
  • Monitor logs in separate terminal: tail -f logs/ufo_server.log
  • Test with single device before adding multiple clients
  • Use HTTP API for quick task dispatch testing
  • Verify heartbeat monitoring with client disconnection

!!!example "Development Testing Pattern"
```bash
# Terminal 1: Start server with debug logging
python -m ufo.server.app --local --log-level DEBUG

text
# Terminal 2: Connect device client
python -m ufo.client.client --ws --ws-server ws://127.0.0.1:5000/ws

# Terminal 3: Dispatch test task
curl -X POST http://127.0.0.1:5000/api/dispatch \
  -H "Content-Type: application/json" \
  -d '{"client_id": "windowsagent", "request": "Open Notepad", "task_name": "test_001"}'
```

Production Deployment

The default configuration is not production-ready. Implement these security and reliability measures.

Production Architecture:

mermaid
graph LR
    Internet[Internet]
    LB[Load Balancernginx/HAProxy]
    SSL[SSL/TLSTermination]
    
    subgraph "UFO Server Cluster"
        S1[Server Instance 1:5000]
        S2[Server Instance 2:5001]
        S3[Server Instance 3:5002]
    end
    
    Monitor[MonitoringPrometheus/Grafana]
    PM[Process Managersystemd/PM2]
    
    Internet --> LB
    LB --> SSL
    SSL --> S1
    SSL --> S2
    SSL --> S3
    
    PM -.Manages.-> S1
    PM -.Manages.-> S2
    PM -.Manages.-> S3
    
    S1 -.Metrics.-> Monitor
    S2 -.Metrics.-> Monitor
    S3 -.Metrics.-> Monitor
    
    style LB fill:#ffe1f5
    style SSL fill:#fff4e1
    style Monitor fill:#f0ffe1

Production Checklist:

Category Recommendation Rationale
Reverse Proxy nginx, Apache, or cloud load balancer SSL termination, rate limiting, DDoS protection
SSL/TLS Enable WSS (WebSocket Secure) Encrypt client-server communication
Authentication Add auth middleware to FastAPI Prevent unauthorized access
Process Management systemd (Linux), PM2 (Node.js), Docker Auto-restart on crash, resource limits
Monitoring /api/health polling, metrics export Detect issues proactively
Logging Structured logging, log aggregation (ELK) Centralized debugging and audit trails
Resource Limits Set max connections, memory limits Prevent resource exhaustion

Example Nginx Configuration:

nginx
upstream ufo_server {
    server localhost:5000;
}

server {
    listen 443 ssl;
    server_name ufo-server.example.com;
    
    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;
    
    # WebSocket endpoint
    location /ws {
        proxy_pass http://ufo_server;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_read_timeout 3600s;
    }
    
    # HTTP API
    location /api/ {
        proxy_pass http://ufo_server;
        proxy_set_header Host $host;
    }
}

Scaling Strategies

The server can scale horizontally for high-load deployments, but requires careful session management.

Scaling Patterns:

Pattern Description Use Case Considerations
Vertical Increase CPU/RAM on single instance < 100 concurrent clients Simplest, no session distribution
Horizontal (Sticky Sessions) Multiple instances with session affinity 100-1000 clients Load balancer routes same client to same instance
Horizontal (Shared State) Multiple instances with Redis > 1000 clients Requires session state externalization

!!!warning "Current Limitation"
The current implementation stores session state in-memory. For horizontal scaling, use sticky sessions (client affinity) in your load balancer to route clients to consistent server instances. Future: Shared state backend (Redis) for true stateless horizontal scaling.


Troubleshooting

Common Issues

Issue: Clients Can't Connect

bash
# Symptom: Connection refused
Error: WebSocket connection to 'ws://localhost:5000/ws' failed

# Diagnosis:
1. Check server is running: curl http://localhost:5000/api/health
2. Verify port: netstat -an | grep 5000
3. Check firewall: sudo ufw status

# Solution:
# Start server with correct host binding
python -m ufo.server.app --host 0.0.0.0 --port 5000

Issue: Sessions Not Executing

bash
# Symptom: Task dispatched but no results

# Diagnosis:
1. Check server logs for errors
2. Verify client is connected: curl http://localhost:5000/api/clients
3. Check target_id matches client_id

# Solution:
# Ensure client_id in request matches registered client
curl -X POST http://localhost:5000/api/dispatch \
  -d '{"client_id": "correct_client_id", "request": "test", "task_name": "test_001"}'

Issue: Memory Leak / High Memory Usage

bash
# Symptom: Server memory grows over time

# Diagnosis:
1. Check session cleanup in logs
2. Monitor /api/health for session count
3. Profile with memory_profiler

# Solution:
# Ensure clients send TASK_END to complete sessions
# Restart server periodically (systemd handles this)
# Implement session timeout (future feature)

Debug Mode

!!!example "Enable Maximum Verbosity"
```bash
# Ultra-verbose debugging
python -m ufo.server.app
--log-level DEBUG
--local
--port 5000 2>&1 | tee debug.log

text
# Watch logs in real-time
tail -f debug.log | grep -E "(ERROR|WARNING|Session|WebSocket)"
```

Documentation Map

Explore related documentation to deepen your understanding of the Agent Server ecosystem.

Getting Started

Document Purpose
Quick Start Get server running in < 5 minutes
Client Registration How clients connect to server

Architecture & Components

Document Purpose
Session Manager Task execution lifecycle deep-dive
Client Connection Manager Connection registry internals
WebSocket Handler AIP protocol message handling
HTTP API REST endpoint specifications

Operations

Document Purpose
Monitoring Health checks, metrics, alerting
Document Purpose
AIP Protocol Communication protocol specification
Agent Architecture Agent design and FSM framework
Server-Client Architecture Distributed architecture rationale
Client Overview Device client architecture
MCP Integration Model Context Protocol tool servers

Next Steps

Follow this recommended sequence to master the Agent Server:

1. Run the Server (5 minutes)

2. Connect a Client (10 minutes)

  • Use Device Client
  • Verify registration in server logs
  • Check /api/clients endpoint

3. Dispatch Tasks (15 minutes)

  • Use HTTP API to send tasks
  • Retrieve results via /api/task_result
  • Observe WebSocket message flow in logs

4. Understand Architecture (30 minutes)

5. Deploy to Production (varies)

  • Set up reverse proxy (nginx)
  • Configure SSL/TLS
  • Implement monitoring
  • Test failover scenarios

Documents Docs Ufo2 Overview (`documents/docs/ufo2/overview.md`)

UFO² — Windows AgentOS

 
 
 
 
 

UFO² is a Windows AgentOS that reimagines desktop automation as a first-class operating system abstraction. Unlike traditional Computer-Using Agents (CUAs) that rely on screenshots and simulated inputs, UFO² deeply integrates with Windows OS through UI Automation APIs, application-specific introspection, and hybrid GUI–API execution—enabling robust, efficient, and non-disruptive automation across 20+ real-world applications.


What is UFO²?

UFO² addresses fundamental limitations of existing desktop automation solutions:

Traditional RPA (UiPath, Power Automate):
❌ Fragile scripts that break with UI changes
❌ Requires extensive manual maintenance
❌ Limited adaptability to dynamic environments

Current CUAs (Claude, Operator):
❌ Visual-only inputs with high cognitive overhead
❌ Miss native OS APIs and application internals
❌ Lock users out during automation (poor UX)

UFO² AgentOS:
✅ Deep OS Integration — Windows UIA, Win32, WinCOM APIs
✅ Hybrid GUI–API Actions — Native APIs + fallback GUI automation
✅ Continuous Knowledge Learning — RAG-enhanced from docs & execution history
✅ Picture-in-Picture Desktop — Parallel automation without user disruption
✅ 10%+ better success rate than state-of-the-art CUAs

Figure 1: Comparison between (a) traditional CUAs that rely on screenshots and simulated inputs, and (b) UFO² AgentOS that deeply integrates with OS APIs, application internals, and hybrid GUI–API execution.

Core Architecture

UFO² implements a hierarchical multi-agent system optimized for Windows desktop automation:

Figure 2: UFO² system architecture featuring the two-tier agent hierarchy (HostAgent + AppAgents), hybrid control detection pipeline, continuous knowledge substrate integration, and unified GUI–API action layer coordinated through MCP servers.

Two-Tier Agent Hierarchy

Agent Type Role Key Capabilities
HostAgent Desktop Orchestrator Task decomposition • Application selection • Cross-app coordination • AppAgent lifecycle management
AppAgent Application Executor UI element interaction • Hybrid GUI–API execution • Application-specific automation • Result reporting

Design Philosophy:

  • HostAgent handles WHAT (which application) and WHEN (task sequencing)
  • AppAgent handles HOW (UI/API interaction) and WHERE (control targeting)
  • Blackboard facilitates inter-agent communication without tight coupling
  • State Machines ensure deterministic execution flow and error recovery

!!!info "Learn More"
- HostAgent Documentation — 7-state FSM, desktop orchestration, AppAgent lifecycle
- AppAgent Documentation — 6-state FSM, UI automation, hybrid action execution
- Agent Architecture — Three-layer design principles


Key Innovations

1. Deep OS Integration 🔧

UFO² embeds directly into Windows OS infrastructure:

  • UI Automation (UIA): Introspects accessibility trees for standard controls
  • Win32 APIs: Low-level window management and process control
  • WinCOM: Interacts with Office applications (Excel, Word, Outlook)
  • Hybrid Detection: Fuses UIA metadata + visual grounding for non-standard UI elements

!!!tip "Hybrid Control Detection"
Combines Windows UIA APIs with vision models (OmniParser) to detect both standard and custom UI controls—bridging structured accessibility trees and pixel-level perception.

text
📖 [Control Detection Guide](core_features/control_detection/overview.md)

2. Unified GUI–API Action Layer ⚡

Traditional CUAs simulate mouse/keyboard only. UFO² chooses the best execution method:

GUI Actions (fallback):
click, type, select, scroll → Reliable for any application

Native APIs (preferred):

  • Excel: xlwings for direct cell/chart manipulation
  • Outlook: win32com for email operations
  • PowerPoint: python-pptx for slide editing
    → 51% fewer LLM calls via speculative multi-action execution

Model Context Protocol (MCP) Servers:
Extensible framework for adding application-specific APIs without modifying agent code.

!!!info "Learn More"
📖 Hybrid Actions Guide • MCP Integration

3. Continuous Knowledge Substrate 📚

UFO² learns from three knowledge sources without model retraining:

Source Content Integration Method
Help Documents Official app documentation, API references Vectorized retrieval (RAG)
Bing Search Real-time web knowledge for latest features Dynamic query expansion
Execution History Past successful/failed action sequences Experience replay & pattern mining

Result: Agents improve autonomously by retrieving relevant context at execution time.

!!!info "Knowledge Integration"
📖 Knowledge Substrate Overview
📖 Learning from Help Documents
📖 Experience Learning

4. Speculative Multi-Action Execution 🚀

Reduce LLM latency by predicting and validating action sequences:

Traditional Approach:
1 LLM call → 1 action → observe → repeat → High latency

UFO² Speculative Execution:
1 LLM call → predict N actions → validate with UI state → execute all → 51% fewer queries

Validation Mechanism:
Lightweight control-state checks ensure predicted actions remain valid before execution.

!!!example "Efficiency Gain"
Task: "Fill form fields A1–A10 with sequential numbers"

text
- **Traditional CUA:** 10 LLM calls (1 per field) → ~30 seconds  
- **UFO² Speculative:** 1 LLM call predicts all 10 actions → ~8 seconds

📖 [Multi-Action Execution Guide](core_features/multi_action.md)

5. Picture-in-Picture Desktop 🖼️

Problem: Existing CUAs lock users out during automation (poor UX).

UFO² Solution: Nested virtual desktop via Windows Remote Desktop loopback:

  • User Desktop: Continue working normally
  • Agent Desktop (PiP): Automation runs in parallel sandboxed environment
  • Zero Interference: User and agent don't compete for mouse/keyboard

Implementation:
Built on Windows native remote desktop infrastructure—secure, isolated, non-disruptive.

!!!success "User Experience"
Users can continue email, browsing, or coding while UFO² automates Excel reports in the background PiP desktop.


System Components

Processing Pipeline

Both HostAgent and AppAgent execute a 4-phase processing cycle:

Phase Purpose HostAgent Strategy AppAgent Strategy
1. Data Collection Gather environment state Desktop screenshot, app list App screenshot, UI tree, control annotations
2. LLM Interaction Decide next action Select application, plan subtask Select control, plan action sequence
3. Action Execution Execute commands Launch app, create AppAgent Execute GUI/API actions
4. Memory Update Record execution Save orchestration step Save interaction step, update blackboard

!!!info "Processing Details"
📖 Strategy Layer — Processing framework and dependency chain
📖 State Layer — FSM design principles

Command System

Commands are dispatched through MCP (Model Context Protocol) servers:

HostAgent Commands:

  • Desktop Capture: capture_desktop_screenshot
  • Window Management: get_desktop_app_info, get_app_window
  • Process Control: launch_application, close_application

AppAgent Commands:

  • Screenshot: capture_screenshot, annotate_screenshot
  • UI Inspection: get_control_info, get_ui_tree
  • UI Interaction: click, set_edit_text, wheel_mouse_input
  • Control Selection: select_control_by_index, select_control_by_name

!!!info "Command Architecture"
📖 Command Layer — MCP integration and command dispatch
📖 MCP Servers — Server architecture and custom server creation


Configuration

UFO² integrates with a centralized YAML-based configuration system:

yaml
# config/ufo/host_agent_config.yaml
host_agent:
  visual_mode: true                  # Enable screenshot-based reasoning
  max_subtasks: 10                   # Maximum subtasks per session
  llm_config:
    model: "gpt-4o"
    temperature: 0.0

# config/ufo/app_agent_config.yaml
app_agent:
  visual_mode: true                  # Enable UI screenshot analysis
  control_backend: "uia"             # UI Automation (uia) or Win32 (win32)
  max_steps: 20                      # Maximum steps per subtask

!!!tip "Complete Configuration Guide"
For detailed configuration options, model setup, and advanced customization:

text
📖 **[Configuration & Setup](../configuration/system/overview.md)** — Complete system configuration reference  
📖 **[Model Setup](../configuration/models/overview.md)** — LLM provider configuration (OpenAI, Azure, Gemini, Claude, etc.)  
📖 **[MCP Configuration](../configuration/system/mcp_reference.md)** — MCP server and extension configuration

Quick Start

Basic Usage

UFO² is designed to be run from the command line:

Interactive Mode:

powershell
# Start UFO² in interactive mode
python -m ufo --task <your_task_name>

Example:

powershell
python -m ufo --task excel_demo

This will prompt you to enter your request interactively:

text
Welcome to use UFO🛸, A UI-focused Agent for Windows OS Interaction.
Please enter your request to be completed🛸: Create a chart from Sheet1 data in Excel

Direct Request Mode:

powershell
# Execute with a specific request directly
python -m ufo --task <your_task_name> -r "<your_request>"

Example:

powershell
python -m ufo --task excel_demo -r "Open Excel and create a chart from Sheet1 data"

!!!tip "Complete Setup Guide"
For detailed installation, configuration, and advanced usage options, see the Quick Start Guide.

What Happens Under the Hood

  1. Session creates HostAgent with user request
  2. HostAgent captures desktop, selects "Microsoft Excel", launches app
  3. HostAgent creates AppAgent for Excel, delegates subtask
  4. AppAgent captures Excel UI, identifies chart insertion control
  5. AppAgent executes hybrid action (API if available, GUI fallback)
  6. AppAgent reports completion to HostAgent
  7. HostAgent verifies task, returns success to Session

!!!tip "Next Steps"
📖 Getting Started Guide
📖 Creating Your AppAgent


Documentation Navigation

Core Concepts

Advanced Features

System Architecture

Development

Benchmarking & Logs


Research Impact

UFO² demonstrates that system-level integration and architectural design matter more than model size alone:

!!!success "Key Findings"
- 10%+ improvement over Claude/Operator on WindowsAgentArena
- 51% fewer LLM calls via speculative multi-action execution
- Robust to UI changes through hybrid UIA + visual detection
- Continuous learning without model retraining via RAG
- Non-disruptive UX via Picture-in-Picture desktop

Research Paper:
📄 UFO²: A Grounded OS Agent for Windows


Get Started

Ready to explore UFO²? Choose your path:

!!!info "Learning Paths"
🚀 New Users: Start with Quick Start Guide
🔧 Developers: Read Creating AppAgent
🏗️ System Architects: Study Device Agent Architecture
📊 Researchers: Check Benchmark Results

Next: HostAgent Deep Dive → Understand desktop orchestration


🌐 Media Coverage

Check out our official deep dive of UFO on this Youtube Video.

UFO sightings have garnered attention from various media outlets, including:


📚 Citation

If you build on this work, please cite the AgentOS framework:

UFO² – The Desktop AgentOS (2025)
https://arxiv.org/abs/2504.14603

bibtex
@article{zhang2025ufo2,
  title   = {{UFO2: The Desktop AgentOS}},
  author  = {Zhang, Chaoyun and Huang, He and Ni, Chiming and Mu, Jian and Qin, Si and He, Shilin and Wang, Lu and Yang, Fangkai and Zhao, Pu and Du, Chao and Li, Liqun and Kang, Yu and Jiang, Zhao and Zheng, Suzhen and Wang, Rujia and Qian, Jiaxu and Ma, Minghua and Lou, Jian-Guang and Lin, Qingwei and Rajmohan, Saravan and Zhang, Dongmei},
  journal = {arXiv preprint arXiv:2504.14603},
  year    = {2025}
}

UFO – A UI‑Focused Agent for Windows OS Interaction (2024)
https://arxiv.org/abs/2402.07939

bibtex
@article{zhang2024ufo,
  title   = {{UFO: A UI-Focused Agent for Windows OS Interaction}},
  author  = {Zhang, Chaoyun and Li, Liqun and He, Shilin and Zhang, Xu and Qiao, Bo and Qin, Si and Ma, Minghua and Kang, Yu and Lin, Qingwei and Rajmohan, Saravan and Zhang, Dongmei and Zhang, Qi},
  journal = {arXiv preprint arXiv:2402.07939},
  year    = {2024}
}


❓Get Help

  • ❔GitHub Issues (preferred)
  • For other communications, please contact [email protected]

Documents Docs Configuration Models Overview (`documents/docs/configuration/models/overview.md`)

Supported Models

UFO supports a wide variety of LLM models and APIs. You can configure different models for HOST_AGENT, APP_AGENT, BACKUP_AGENT, and EVALUATION_AGENT in the config/ufo/agents.yaml file to optimize for performance, cost, or specific capabilities.

Available Model Integrations

Provider Documentation Visual Support Authentication
OpenAI OpenAI API ✅ API Key
Azure OpenAI (AOAI) Azure OpenAI API ✅ API Key / Azure AD
Google Gemini Gemini API ✅ API Key
Anthropic Claude Claude API ✅ API Key
Qwen (Alibaba) Qwen API ✅ API Key
DeepSeek DeepSeek API ❌ API Key
Ollama Ollama API ⚠️ Limited Local
OpenAI Operator Operator (CUA) ✅ Azure AD
Custom Models Custom API Depends Varies

Model Selection Guide

By Use Case

For Production Deployments:

  • Primary: OpenAI GPT-4o or Azure OpenAI (enterprise features)
  • Cost-optimized: GPT-4o-mini for APP_AGENT, GPT-4o for HOST_AGENT
  • Privacy-sensitive: Ollama (local models)

For Development & Testing:

  • Fast iteration: Gemini 2.0 Flash (high speed, low cost)
  • Local testing: Ollama with llama2 or similar
  • Budget-friendly: DeepSeek or Qwen models

For Specialized Tasks:

  • Computer control: OpenAI Operator (CUA model)
  • Code generation: DeepSeek-Coder or Claude
  • Long context: Gemini 1.5 Pro (large context window)

By Capability

Vision Support (Screenshot Understanding):

  • ✅ OpenAI GPT-4o, GPT-4-turbo
  • ✅ Azure OpenAI (vision-enabled deployments)
  • ✅ Google Gemini (all 1.5+ models)
  • ✅ Claude 3+ (all variants)
  • ✅ Qwen-VL models
  • ⚠️ Ollama (llava models only)
  • ❌ DeepSeek (text-only)

JSON Schema Support:

  • ✅ OpenAI / Azure OpenAI
  • ✅ Google Gemini
  • ⚠️ Limited: Claude, Qwen, Ollama

Configuration Architecture

Each model is implemented as a separate class in the ufo/llm directory, inheriting from the BaseService class in ufo/llm/base.py. All models implement the chat_completion method to maintain a consistent interface.

Key Configuration Files:

  • config/ufo/agents.yaml: Primary agent configuration (HOST, APP, BACKUP, EVALUATION, OPERATOR)
  • config/ufo/system.yaml: System-wide LLM parameters (MAX_TOKENS, TEMPERATURE, etc.)
  • config/ufo/prices.yaml: Cost tracking for different models

Multi-Provider Setup

You can mix and match providers for different agents to optimize cost and performance:

yaml
# Use OpenAI for planning
HOST_AGENT:
  API_TYPE: "openai"
  API_MODEL: "gpt-4o"

# Use Azure OpenAI for execution (cost control)
APP_AGENT:
  API_TYPE: "aoai"
  API_MODEL: "gpt-4o-mini"

# Use Claude for evaluation
EVALUATION_AGENT:
  API_TYPE: "claude"
  API_MODEL: "claude-3-5-sonnet-20241022"

Getting Started

  1. Choose your LLM provider from the table above
  2. Follow the provider-specific documentation to obtain API keys
  3. Configure config/ufo/agents.yaml with your credentials
  4. Refer to the Quick Start Guide to begin

For detailed configuration options:


Documents Docs Configuration System Overview (`documents/docs/configuration/system/overview.md`)

Configuration Architecture

UFO² features a modern, modular configuration system designed for flexibility, maintainability, and backward compatibility. This guide explains the overall architecture and design principles.

Design Philosophy

The configuration system follows professional software engineering best practices:

Separation of Concerns

Configuration files are organized by domain rather than monolithic structure:

  • Agent configurations (agents.yaml) - LLM settings for different agents → Agent Config Guide
  • System configurations (system.yaml) - Execution and runtime settings → System Config Guide
  • RAG configurations (rag.yaml) - Knowledge retrieval settings → RAG Config Guide
  • MCP configurations (mcp.yaml) - Model Context Protocol servers → MCP Config Guide
  • Pricing configurations (prices.yaml) - Cost tracking for different models → Pricing Config Guide
  • Third-party configurations (third_party.yaml) - External agent integration (LinuxAgent, HardwareAgent) → Third-Party Config Guide

Type Safety + Flexibility

Hybrid approach combining:

  • Fixed typed fields - IDE autocomplete, type checking, and IntelliSense
  • Dynamic YAML fields - Add new settings without code changes

Example:

python
# Type-safe access (recommended)
config = get_ufo_config()
max_step = config.system.max_step  # IDE autocomplete!
api_model = config.app_agent.api_model

# Dynamic access (for custom fields)
custom_value = config.CUSTOM_FEATURE_FLAG
new_setting = config["NEW_YAML_KEY"]

# Backward compatible (legacy code still works)
max_step_old = config["MAX_STEP"]

Backward Compatibility

Zero breaking changes - existing code continues to work:

  • Old configuration paths still supported (ufo/config/)
  • Old access patterns still work (config["MAX_STEP"])
  • Automatic migration warnings guide users to new structure

Your existing code will continue to work without any modifications. The system automatically falls back to legacy paths and access patterns. See the Migration Guide for details on upgrading to the new structure.

Auto-Discovery

No manual file registration needed:

  • All *.yaml files in config/ufo/ are automatically loaded
  • Files are merged intelligently with deep merging
  • Environment-specific overrides (*_dev.yaml, *_test.yaml) supported

Directory Structure

text
UFO/
├── config/                          ← New Configuration Root (Recommended)
│   ├── ufo/                        ← UFO² Configurations
│   │   ├── agents.yaml             # LLM agent settings
│   │   ├── agents.yaml.template    # Template for setup
│   │   ├── system.yaml             # System and runtime settings
│   │   ├── rag.yaml                # RAG knowledge settings
│   │   ├── mcp.yaml                # MCP server configurations
│   │   ├── prices.yaml             # Model pricing
│   │   └── third_party.yaml        # Third-party agents (optional)
│   │
│   ├── galaxy/                     ← Galaxy Configurations
│   │   ├── agent.yaml              # Constellation agent settings
│   │   ├── agent.yaml.template     # Template for setup
│   │   ├── constellation.yaml      # Constellation runtime settings
│   │   └── devices.yaml            # Device/client configurations
│   │
│   ├── config_loader.py            # Modern config loader
│   └── config_schemas.py           # Type definitions
│
└── ufo/config/                      ← Legacy Path (Still Supported)
    └── config.yaml                 # Old monolithic config

Galaxy Configuration Files

The Galaxy constellation system has its own set of configuration files in config/galaxy/:

File Purpose Template Documentation
constellation.yaml Constellation runtime settings (heartbeat, concurrency, step limits) No Galaxy Constellation Config
devices.yaml Device agent definitions (device_id, server_url, capabilities, metadata) No Galaxy Devices Config
agent.yaml Constellation agent LLM configuration (API settings, prompts) Yes (.template) Galaxy Agent Config

Galaxy Configuration Structure

text
/* Detailed source-code truncated for AI context efficiency. */

Galaxy Configuration Loading

python
# Load Galaxy configurations
from config.config_loader import get_galaxy_config

# Load Galaxy configuration (includes agent and constellation settings)
galaxy_config = get_galaxy_config()

# Access agent configuration (LLM settings)
agent_config = galaxy_config.agent.constellation_agent

# Access constellation runtime settings
constellation_settings = galaxy_config.constellation

# Or use raw dict access for backward compatibility
constellation_id = galaxy_config["CONSTELLATION_ID"]

Galaxy vs UFO Configuration:

  • UFO Configurations (config/ufo/) - Single-agent automation settings
  • Galaxy Configurations (config/galaxy/) - Multi-device constellation settings
  • Both systems can coexist in the same project

Configuration Loading Process

Priority Chain

The configuration system uses a clear priority chain (highest to lowest):

  1. New modular configs - config/{module}/*.yaml
  2. Legacy monolithic config - {module}/config/config.yaml
  3. Environment variables - Runtime overrides

When the same setting exists in multiple locations, the new modular config takes precedence over legacy configs. Values are merged with later sources overriding earlier ones.

Loading Algorithm

python
def load_config():
    # Step 1: Start with environment variables (lowest priority)
    config_data = dict(os.environ)
    
    # Step 2: Load legacy config if exists (middle priority)
    if exists("ufo/config/config.yaml"):
        legacy_data = load_yaml("ufo/config/config.yaml")
        merge(config_data, legacy_data)
    
    # Step 3: Load new modular configs (highest priority)
    for yaml_file in discover("config/ufo/*.yaml"):
        new_data = load_yaml(yaml_file)
        merge(config_data, new_data)
    
    # Step 4: Create typed config object
    return UFOConfig.from_dict(config_data)

Deep Merging

Configuration files are merged recursively, allowing you to split configurations across multiple files without duplication:

yaml
# config/ufo/agents.yaml
HOST_AGENT:
  API_TYPE: "openai"
  API_MODEL: "gpt-4o"

# config/ufo/custom.yaml (added later)
HOST_AGENT:
  TEMPERATURE: 0.5  # Added to HOST_AGENT

# Result: HOST_AGENT has all three fields

Fields from later files are added to (not replacing) earlier configurations.

File Organization Patterns

Split by Domain (Current Approach)

text
config/ufo/
├── agents.yaml      # All agent LLM configs
├── system.yaml      # All system settings
├── rag.yaml         # All RAG settings
├── mcp.yaml         # All MCP servers
└── prices.yaml      # Model pricing

Advantages: Easy to find related settings, clear separation of concerns, good for documentation.

Alternative: Split by Agent

text
config/ufo/
├── host_agent.yaml       # HOST_AGENT config
├── app_agent.yaml        # APP_AGENT config
├── system.yaml           # Shared system config
└── rag.yaml              # Shared RAG config

Advantages: Agent-specific settings isolated, easy to customize per agent, good for multi-agent scenarios.

Both patterns work! The loader auto-discovers and merges all YAML files.

Environment-Specific Overrides

Support for development, testing, and production environments:

bash
# Base configuration
config/ufo/agents.yaml          # All environments

# Environment-specific overrides
config/ufo/agents_dev.yaml      # Development only
config/ufo/agents_test.yaml     # Testing only
config/ufo/agents_prod.yaml     # Production only

Activation:

bash
# Set environment
export UFO_ENV=dev              # Linux/Mac
$env:UFO_ENV = "dev"            # Windows PowerShell

# Configuration loads:
# 1. agents.yaml (base)
# 2. agents_dev.yaml (overrides)

Type System

Provides IDE autocomplete and type safety:

python
@dataclass
class SystemConfig:
    max_step: int = 50
    max_retry: int = 20
    temperature: float = 0.0
    # ...

# Usage - IDE knows the types!
config.system.max_step        # int
config.system.temperature     # float

Dynamic Types (Flexible)

For custom or experimental settings. Learn more about adding custom fields in the Extending Configuration guide.

Example:

python
# In YAML
MY_CUSTOM_FEATURE: True
NEW_EXPERIMENTAL_SETTING: "value"

# In code - dynamic access
if config.MY_CUSTOM_FEATURE:
    setting = config.NEW_EXPERIMENTAL_SETTING

Hybrid Approach

Best of both worlds:

python
class SystemConfig:
    # Fixed fields
    max_step: int = 50
    
    # Dynamic extras
    _extras: Dict[str, Any]
    
    def __getattr__(self, name):
        # Try extras for unknown fields
        return self._extras.get(name)

Migration Warnings

The system provides clear warnings when using legacy paths:

text
⚠️  LEGACY CONFIG PATH DETECTED: UFO

Using legacy config: ufo/config/
Please migrate to:   config/ufo/

Quick migration:
  mkdir -p config/ufo
  cp ufo/config/*.yaml config/ufo/

Or use migration tool:
  python -m ufo.tools.migrate_config

These warnings appear once per session and guide you to migrate to the new structure.

Best Practices

Recommended Practices:

  • Use modular files - Split by domain or agent
  • Use typed access - config.system.max_step over config["MAX_STEP"]
  • Add templates - Provide .template files for sensitive data
  • Document custom fields - Add comments in YAML
  • Use environment overrides - For dev/test/prod differences

Anti-Patterns to Avoid:

  • Mix old and new - Migrate fully to new structure
  • Put secrets in YAML - Use environment variables instead
  • Duplicate settings - Leverage deep merging
  • Break backward compat - Keep config["OLD_KEY"] working
  • Hardcode paths - Use config system

Configuration Lifecycle

mermaid
graph LR
    A[Application Start] --> B[Load Environment Vars]
    B --> C[Check for Legacy Config]
    C --> D[Load New Modular Configs]
    D --> E[Deep Merge All Sources]
    E --> F[Apply Transformations]
    F --> G[Create Typed Config Object]
    G --> H[Cache for Reuse]
    H --> I[Application Running]

Next Steps

UFO Configuration Guides

Galaxy Configuration Guides

API Reference

For detailed API documentation of configuration classes and methods, see:

  • config.config_loader.ConfigLoader - Configuration loading and caching
  • config.config_schemas.UFOConfig - UFO configuration schema
  • config.config_schemas.GalaxyConfig - Galaxy configuration schema
  • config.config_loader.get_ufo_config() - Get UFO configuration instance
  • config.config_loader.get_galaxy_config() - Get Galaxy configuration instance

Documents Docs Galaxy Agent Registration Overview (`documents/docs/galaxy/agent_registration/overview.md`)

🌟 Agent Registration & Profiling - Overview

Agent Registration is the cornerstone of the AIP (Agent Interaction Protocol) initialization process. It enables dynamic discovery, capability advertisement, and intelligent task allocation across distributed constellation agents.


📋 Introduction

An overview of the Constellation Agent architecture showing the registration and profiling system.

At the core of AIP's initialization process is the ConstellationClient (implemented as ConstellationDeviceManager), which maintains a global registry of active agents. Any device agent service that exposes a WebSocket endpoint and implements the AIP task dispatch and result-return protocol can be seamlessly integrated into UFO, providing remarkable extensibility.

The multi-source profiling pipeline enables transparent capability discovery and safe adaptation to environmental drift without direct administrator intervention.

For a complete understanding of the constellation system, see:


🎯 Core Concepts

Agent Registry

The agent registry is a centralized store that tracks all active constellation agents. Each registered agent is represented by an AgentProfile that consolidates comprehensive information about the agent's capabilities, system resources, and operational status.

Component Responsibility Location
ConstellationDeviceManager Central coordinator for device management galaxy/client/device_manager.py
DeviceRegistry Device registration and information storage galaxy/client/components/device_registry.py
AgentProfile Multi-source agent metadata representation galaxy/client/components/types.py
ClientConnectionManager Server-side client connection tracking ufo/server/services/client_connection_manager.py

Multi-Source Profiling

Each AgentProfile consolidates information from three distinct sources, creating a comprehensive and dynamically updated view of each agent.

mermaid
graph TB
    subgraph Sources
        UC[User Configdevices.yaml]
        SM[AIP RegistrationService Manifest]
        CT[Device TelemetryDeviceInfoProvider]
    end
    
    UC -->|device_id, capabilitiesmetadata| AP[AgentProfile]
    SM -->|platform, client_typeregistration_time| AP
    CT -->|system_infosupported_features| AP
    
    AP --> CR[ConstellationDeviceManager]
    CR --> TA[Intelligent Task Routing]
    
    style UC fill:#e1f5ff
    style SM fill:#fff4e1
    style CT fill:#e8f5e9
    style AP fill:#f3e5f5

Source Details:

Source Provider Information Type Update Frequency
1. User Configuration Administrator (devices.yaml + constellation.yaml) Endpoint identity, user preferences, capabilities Static (config load)
2. Service Manifest Device Agent Service (AIP) Client type, platform, registration metadata On registration
3. Client Telemetry Device Client (DeviceInfoProvider) Hardware specs, OS info, network status On connection + periodic updates

Note: While constellation.yaml contains runtime settings like heartbeat intervals, the device-specific configuration is in devices.yaml.


🔄 Registration Flow

Agent registration flow: multi-source AgentProfile construction and registration.

Registration Process Overview

The registration process follows a well-defined sequence that ensures comprehensive profiling and validation:

mermaid
sequenceDiagram
    participant Admin as Administrator
    participant CDM as ConstellationDeviceManager
    participant Server as UFO Server
    participant DIP as DeviceInfoProvider
    
    Note over Admin,DIP: Phase 1: User Configuration
    Admin->>CDM: register_device(device_id, capabilities)
    CDM->>CDM: Create AgentProfile
    
    Note over Admin,DIP: Phase 2: WebSocket Connection
    CDM->>Server: connect_device()
    Server-->>CDM: Connection established
    
    Note over Admin,DIP: Phase 3: Service Registration
    CDM->>Server: REGISTER message
    Server-->>CDM: Registration confirmed
    
    Note over Admin,DIP: Phase 4: Telemetry Collection
    CDM->>Server: request_device_info()
    Server->>DIP: collect_system_info()
    DIP-->>Server: system_info
    Server-->>CDM: system_info
    CDM->>CDM: Merge into AgentProfile
    
    Note over Admin,DIP: Phase 5: Ready for Tasks
    CDM->>CDM: Set device to IDLE

Registration Phases:

Phase Description Components Involved Result
1. User Configuration Administrator registers device with endpoint and capabilities ConstellationDeviceManager, DeviceRegistry AgentProfile created with user-specified data
2. WebSocket Connection Establish persistent connection to device agent server WebSocketConnectionManager Active WebSocket channel
3. Service Registration AIP registration protocol exchange with capability advertisement RegistrationProtocol, UFOWebSocketHandler Client type and platform recorded
4. Telemetry Collection Retrieve runtime system information from device DeviceInfoProvider, DeviceInfoProtocol Hardware, OS, and feature data merged
5. Activation Set device to IDLE state, ready for task assignment DeviceRegistry Agent ready for constellation tasks

Devices can be registered with auto_connect=True to automatically establish connection, or auto_connect=False to require manual connection via connect_device().


📊 AgentProfile Structure

The AgentProfile is the primary data structure representing a registered constellation agent. For detailed information about the AgentProfile and its lifecycle operations, see Agent Profile Documentation.

Core Fields

The AgentProfile is the primary data structure representing a registered constellation agent:

python
@dataclass
class AgentProfile:
    """Device information and capabilities"""
    
    # Identity
    device_id: str                          # Unique device identifier
    server_url: str                         # WebSocket endpoint URL
    
    # Platform & Capabilities
    os: Optional[str] = None                # Operating system (windows, linux, darwin)
    capabilities: List[str]                 # Advertised capabilities/features
    metadata: Dict[str, Any]                # Additional metadata
    
    # Operational Status
    status: DeviceStatus                    # Current connection/operational status
    last_heartbeat: Optional[datetime]      # Last heartbeat timestamp
    
    # Connection Management
    connection_attempts: int = 0            # Connection retry counter
    max_retries: int = 5                    # Maximum retry attempts
    
    # Task Execution
    current_task_id: Optional[str] = None   # Currently executing task ID

Field Categories:

Category Fields Purpose
Identity device_id, server_url Unique identification and endpoint location
Platform os, capabilities, metadata System type and advertised features
Status status, last_heartbeat Real-time operational state tracking
Resilience connection_attempts, max_retries Connection retry management
Execution current_task_id Task assignment tracking

Metadata Structure

The metadata field is a flexible dictionary that aggregates information from all three sources:

python
metadata = {
    # From User Configuration (Source 1)
    "location": "home_office",
    "performance": "high",
    "description": "Primary development laptop",
    "operation_engineer_email": "[email protected]",
    
    # From Service Manifest (Source 2)
    "platform": "windows",
    "registration_time": "2025-11-06T10:30:00Z",
    
    # From Client Telemetry (Source 3)
    "system_info": {
        "platform": "windows",
        "os_version": "10.0.22631",
        "cpu_count": 16,
        "memory_total_gb": 32.0,
        "hostname": "DESKTOP-DEV01",
        "ip_address": "192.168.1.100",
        "platform_type": "computer",
        "schema_version": "1.0"
    },
    "custom_metadata": {
        "datacenter": "us-west-2",
        "tier": "production"
    }
}

For a complete example, see the Agent Profile Documentation.


🔄 Agent Lifecycle States

Lifecycle state transitions of the Constellation Agent.

The agent lifecycle is managed through a state machine that tracks connection, registration, and task execution states. For more details on agent behavior and state management, see Constellation Agent State Management.

State Definitions

python
class DeviceStatus(Enum):
    """Device connection status"""
    DISCONNECTED = "disconnected"   # Not connected to server
    CONNECTING = "connecting"       # Attempting to establish connection
    CONNECTED = "connected"         # Connected, initializing
    REGISTERING = "registering"     # Performing registration handshake
    IDLE = "idle"                   # Connected and ready for tasks
    BUSY = "busy"                   # Executing a task
    FAILED = "failed"               # Connection/execution failed

State Transition Diagram

mermaid
stateDiagram-v2
    [*] --> DISCONNECTED: Initial State
    
    DISCONNECTED --> CONNECTING: register_device() / connect_device()
    CONNECTING --> CONNECTED: WebSocket established
    CONNECTING --> FAILED: Connection error
    
    CONNECTED --> REGISTERING: Send REGISTER message
    REGISTERING --> IDLE: Registration confirmed + system info collected
    REGISTERING --> FAILED: Registration rejected
    
    IDLE --> BUSY: assign_task_to_device()
    BUSY --> IDLE: Task completed
    BUSY --> FAILED: Task failed / device disconnected
    
    FAILED --> CONNECTING: Automatic reconnection
    
    IDLE --> DISCONNECTED: disconnect_device() / connection lost
    BUSY --> DISCONNECTED: disconnect_device() / connection lost
    
    DISCONNECTED --> [*]: shutdown()

Transition Events:

From State To State Trigger Action
DISCONNECTED CONNECTING connect_device() Initiate WebSocket connection
CONNECTING CONNECTED WebSocket handshake complete Update status
CONNECTED REGISTERING Send REGISTER message AIP registration protocol
REGISTERING IDLE Registration confirmed Collect system info, ready for tasks
IDLE BUSY assign_task_to_device() Execute task
BUSY IDLE Task completes Clear current_task_id
Any DISCONNECTED Connection lost Cleanup, schedule reconnection
FAILED CONNECTING Retry timer Attempt reconnection (if under max_retries)

Important: When a device disconnects or enters FAILED state, the system automatically schedules reconnection attempts up to max_retries times with reconnect_delay interval.


🛠️ Key Components

1. ConstellationDeviceManager

File: galaxy/client/device_manager.py

The central coordinator for all device management operations in the constellation system.

Responsibilities:

  • Device registration and lifecycle management
  • Connection establishment and monitoring
  • Task assignment and execution coordination
  • Automatic reconnection handling

Key Methods:

python
class ConstellationDeviceManager:
    async def register_device(
        device_id: str,
        server_url: str,
        os: str,
        capabilities: List[str],
        metadata: Dict[str, Any],
        auto_connect: bool = True
    ) -> bool
    
    async def connect_device(device_id: str) -> bool
    
    async def assign_task_to_device(
        task_id: str,
        device_id: str,
        task_description: str,
        task_data: Dict[str, Any]
    ) -> ExecutionResult
    
    def get_device_info(device_id: str) -> Optional[AgentProfile]

See Device Registry Documentation for DeviceRegistry details.

2. DeviceRegistry

File: galaxy/client/components/device_registry.py

Manages device registration and information storage with a focus on data management.

Responsibilities:

  • Store and retrieve AgentProfile instances
  • Update device status and metadata
  • Track connection attempts and heartbeats
  • Merge multi-source information

Key Methods:

python
class DeviceRegistry:
    def register_device(...) -> AgentProfile
    def update_device_status(device_id: str, status: DeviceStatus)
    def update_device_system_info(device_id: str, system_info: Dict)
    def set_device_busy(device_id: str, task_id: str)
    def set_device_idle(device_id: str)

3. RegistrationProtocol (AIP)

File: aip/protocol/registration.py

Handles AIP registration message exchange for both device and constellation clients.

Responsibilities:

  • Device agent registration
  • Constellation client registration
  • Capability advertisement
  • Registration validation and confirmation

Key Methods:

python
class RegistrationProtocol(AIPProtocol):
    async def register_as_device(
        device_id: str,
        metadata: Dict[str, Any],
        platform: str
    ) -> bool
    
    async def register_as_constellation(
        constellation_id: str,
        target_device: str,
        metadata: Dict[str, Any]
    ) -> bool
    
    async def send_registration_confirmation()
    async def send_registration_error(error: str)

See AIP Protocol Documentation for protocol details.

4. DeviceInfoProvider

File: ufo/client/device_info_provider.py

Collects device system information (telemetry source).

Responsibilities:

  • Auto-detect platform, OS, and hardware
  • Collect CPU, memory, network information
  • Detect supported features based on platform
  • Provide DeviceSystemInfo structure

Key Methods:

python
class DeviceInfoProvider:
    @staticmethod
    def collect_system_info(
        client_id: str,
        custom_metadata: Optional[Dict]
    ) -> DeviceSystemInfo

See Device Info Provider Documentation for telemetry details.

5. ClientConnectionManager (Server)

File: ufo/server/services/client_connection_manager.py

Server-side client connection tracking and management. For detailed information about the server-side implementation, see Client Connection Manager Documentation.

Responsibilities:

  • Track connected clients (devices and constellations)
  • Store device system information received during registration
  • Manage session-to-client mappings
  • Merge server configuration with client telemetry

Key Methods:

python
class ClientConnectionManager:
    def add_client(
        client_id: str,
        platform: str,
        ws: WebSocket,
        client_type: ClientType,
        metadata: Dict
    )
    def get_device_system_info(device_id: str) -> Optional[Dict]

📝 Configuration

Agent registration uses two configuration files:

1. config/galaxy/devices.yaml - Device definitions:

  • Device endpoints and identities
  • User-specified capabilities and metadata
  • Connection parameters (max retries, auto-connect)

2. config/galaxy/constellation.yaml - Runtime settings:

  • Constellation identification and logging
  • Heartbeat interval and reconnection delay
  • Task concurrency and step limits

See Galaxy Devices Configuration and Galaxy Constellation Configuration for details.

Example Device Configuration (devices.yaml):

yaml
# Device Configuration - YAML Format
# Runtime settings are configured in constellation.yaml

devices:
  - device_id: "windowsagent"
    server_url: "ws://localhost:5005/ws"
    os: "windows"
    capabilities: ["web_browsing", "office_applications"]
    metadata:
      location: "office_desktop"
      performance: "high"
    max_retries: 5
    auto_connect: true

For complete configuration schema, examples, and best practices, see:

👉 Galaxy Devices Configuration Guide


🚀 Usage Example

Basic Registration

python
from galaxy.client.device_manager import ConstellationDeviceManager

# Initialize manager
manager = ConstellationDeviceManager(
    task_name="test_constellation",
    heartbeat_interval=30.0,
    reconnect_delay=5.0
)

# Register and connect device
success = await manager.register_device(
    device_id="windows_workstation",
    server_url="ws://localhost:5005/ws",
    os="windows",
    capabilities=["gui", "browser", "office"],
    metadata={
        "location": "home_office",
        "performance": "medium"
    },
    auto_connect=True  # Automatically connect after registration
)

if success:
    print("✅ Device registered and connected")
    
    # Get device profile
    profile = manager.get_device_info("windows_workstation")
    print(f"Device: {profile.device_id}")
    print(f"Status: {profile.status.value}")
    print(f"Capabilities: {profile.capabilities}")
    print(f"System Info: {profile.metadata.get('system_info')}")

Task Assignment

python
# Assign task to registered device
result = await manager.assign_task_to_device(
    task_id="task_001",
    device_id="windows_workstation",
    task_description="Open Excel and create a report",
    task_data={"file_path": "C:\\Reports\\monthly.xlsx"},
    timeout=300.0
)

print(f"Task Status: {result.status}")
print(f"Result: {result.result}")

For more details on task assignment and execution, see:


🔗 Cross-References

Topic Document Description
Device Info Collection Device Info Provider Client-side telemetry collection
AIP Protocol AIP Overview Agent Interaction Protocol fundamentals
AIP Messages AIP Messages Message structure and types
Agent Profile Agent Profile Detailed AgentProfile structure
Registration Flow Registration Flow Step-by-step registration process
Galaxy Devices Config Galaxy Devices Configuration YAML configuration reference
Device Registry Device Registry Registry component details
Constellation System Constellation Overview Multi-device coordination
Client Connection Manager Server Connection Manager Server-side connection tracking

Architecture Diagrams

  • Constellation Agent Overview: documents/docs/img/constellation_agent.png
  • Agent Registration Flow: documents/docs/img/agent_registry.png
  • Agent Lifecycle States: documents/docs/img/agent_state.png

💡 Key Benefits

The multi-source profiling approach provides several advantages:

1. Improved Task Allocation Accuracy

  • Administrators specify high-level capabilities
  • Service manifests advertise supported tools
  • Telemetry provides real-time hardware status

2. Transparent Capability Discovery

  • No manual system info entry required
  • Automatic feature detection based on platform
  • Dynamic updates without configuration changes

3. Safe Adaptation to Environmental Drift

  • System changes (upgrades, hardware additions) automatically reflected
  • No administrator intervention needed for routine updates
  • Consistent metadata across distributed agents

4. Reliable Scheduling Decisions

  • Fresh and accurate information for task routing
  • Hardware-aware task assignment (CPU/memory requirements)
  • Platform-specific capability matching

🎯 Next Steps

  1. Understand AgentProfile in Detail: Read Agent Profile Documentation
  2. Learn Registration Process: Follow Registration Flow
  3. Configure Your Devices: See Galaxy Devices Configuration
  4. Explore Device Registry: Check Device Registry
  5. Study AIP Protocol: Read AIP Documentation

📚 Additional Resources

  • Source Code: galaxy/client/device_manager.py
  • AIP Protocol: aip/protocol/registration.py
  • Device Info: ufo/client/device_info_provider.py
  • Configuration: config/galaxy/devices.yaml

Best Practice: Always configure devices with meaningful metadata and capabilities to enable intelligent task routing. The system will automatically enhance this information with telemetry data.


Documents Docs Galaxy Client Overview (`documents/docs/galaxy/client/overview.md`)

Galaxy Client Overview

Galaxy Client is the client-side layer responsible for multi-device coordination in the UFO³ framework. At its core is ConstellationClient, which manages device registration, connection, and task assignment. GalaxyClient provides a lightweight wrapper offering convenient session management interfaces.

The Complete Path: From User Request to Device Execution

To understand Galaxy Client, we first need to see the entire system workflow. When a user submits a task request, the system processes it through several layers:

1. User Interaction Layer (Optional)

Users can interact with the Galaxy system in two ways:

Interactive Mode: Users input natural language requests through a command-line interface (CLI), which are received and processed by GalaxyClient. This mode is primarily used for rapid prototyping and manual testing.

Programmatic Mode: Developers directly call the Python API of ConstellationClient or GalaxyClient, integrating Galaxy into their applications. This is the recommended approach for production environments.

2. Session Management Layer (GalaxyClient)

GalaxyClient's role is to manage the lifecycle of task sessions. It doesn't handle specific device operations but instead:

  • Initializes and holds a ConstellationClient instance
  • Creates a GalaxySession for each user request
  • Passes requests to ConstellationAgent for DAG planning (task decomposition)
  • Coordinates TaskConstellationOrchestrator to execute the DAG
  • Collects and aggregates execution results

GalaxyClient is optional. If your application doesn't need session management, you can use ConstellationClient directly.

3. Device Coordination Layer (ConstellationClient)

ConstellationClient is the heart of Galaxy Client. It is responsible for:

Device Management: Registering devices (each device has a unique ID, server URL, capability list, etc.), connecting to devices (via WebSocket), disconnecting devices, and monitoring device health status.

Task Assignment: Receiving task requests from upper layers (TaskConstellationOrchestrator), selecting appropriate devices based on capabilities, sending tasks to devices via the AIP protocol, and waiting for and collecting task execution results.

ConstellationClient doesn't concern itself with how tasks are decomposed (that's ConstellationAgent's responsibility) or how DAGs are executed (that's TaskConstellationOrchestrator's responsibility). It focuses on "device-level matters."

4. Connection Management Layer (DeviceManager)

DeviceManager is the core internal component of ConstellationClient, responsible for all low-level connection management:

WebSocket Connection Establishment: Establishes WebSocket connections with Agent Server, sends AIP REGISTER messages to register device identity, and requests device system information (DEVICE_INFO_REQUEST).

Connection Monitoring: Sends HEARTBEAT messages every 20-30 seconds to check if devices are online. If a timeout occurs with no response, it triggers disconnection handling and automatically attempts reconnection (up to max_retries times).

Message Routing: Starts a background message processing loop, receives messages returned by devices (TASK_END, COMMAND_RESULTS, etc.), and dispatches messages to appropriate handlers.

Task Queuing: If a device is busy executing another task, new tasks are queued and automatically dequeued when the device becomes idle.

5. Protocol Layer (AIP)

All communication with devices goes through the Agent Interaction Protocol (AIP). AIP is a WebSocket-based messaging protocol that defines standard message types and interaction flows. Main message types used by Galaxy Client include:

  • REGISTER: Register device identity with Agent Server
  • DEVICE_INFO_REQUEST/RESPONSE: Request and return device system information
  • TASK: Assign task to device
  • TASK_END: Device reports task completion
  • HEARTBEAT/HEARTBEAT_ACK: Heartbeat health check
  • COMMAND_RESULTS: Device reports intermediate execution results
  • ERROR: Error reporting

For detailed AIP explanation, see AIP Integration.

Component Responsibilities

Having understood the overall flow, let's examine the specific responsibilities of each component:

ConstellationClient: The Device Coordination Facade

ConstellationClient implements the Facade pattern. It provides simple device management APIs externally while delegating actual work to DeviceManager internally.

What it does:

python
# Register device
await client.register_device(
    device_id="windows_pc",
    server_url="ws://192.168.1.100:5000/ws",
    os="windows",
    capabilities=["office", "web", "email"]
)

# Connect device
success = await client.connect_device("windows_pc")

# Assign task
result = await client.assign_task_to_device(
    device_id="windows_pc",
    task_request=TaskRequest(...)
)

# Query status
status = client.get_device_status("windows_pc")

What it doesn't do:

  • DAG planning (handled by ConstellationAgent)
  • DAG execution (handled by TaskConstellationOrchestrator)
  • Session management (handled by GalaxySession)

See ConstellationClient documentation for detailed API reference.

DeviceManager: The Connection Management Engine

DeviceManager is the "engine" of ConstellationClient. It uses 5 modular components to accomplish connection management:

DeviceRegistry: Stores AgentProfiles for all registered devices (including device ID, URL, status, capabilities, metadata, etc.). This component maintains the single source of truth for device state. When a device connects, disconnects, or changes status, DeviceRegistry is updated. Other components query DeviceRegistry to make decisions.

WebSocketConnectionManager: Manages WebSocket connection lifecycle (connect, disconnect, send messages). This component handles the low-level WebSocket operations, including establishing connections, handling connection errors, and sending AIP messages. It maintains a mapping from device_id to WebSocket objects.

HeartbeatManager: Background heartbeat loop that periodically sends HEARTBEAT to check device health. This runs as an independent asyncio task for each connected device. If a device fails to respond within the timeout period (2 × heartbeat_interval), HeartbeatManager triggers the disconnection handler, allowing the system to detect and respond to connection failures quickly.

MessageProcessor: Background message processing loop that receives and routes AIP messages. This component runs a continuous loop for each device, receiving messages from the WebSocket and dispatching them to appropriate handlers. For example, TASK_END messages are used to complete task futures, COMMAND_RESULTS are logged for progress tracking, and ERROR messages trigger error handling.

TaskQueueManager: Manages task queue for each device, queuing tasks when device is busy. When a task is assigned to a busy device, it's placed in that device's queue. When the device completes its current task and becomes IDLE, TaskQueueManager automatically dequeues the next task and executes it. This ensures tasks are never lost even when devices are overloaded.

This modular design ensures each component has a single responsibility, making testing and maintenance easier. See DeviceManager documentation for details.

GalaxyClient: Session Management Wrapper

GalaxyClient provides a higher-level abstraction on top of ConstellationClient:

python
client = GalaxyClient()
await client.initialize()  # Initialize ConstellationClient and connect devices

# Process user request (internally creates GalaxySession, calls ConstellationAgent for DAG planning)
result = await client.process_request("Open Excel and create a sales chart")

await client.shutdown()  # Cleanup resources

GalaxyClient's main value lies in:

  • Simplifying initialization flow (automatically loads device info from config)
  • Providing session management (creates independent GalaxySession for each request)
  • Integrating display components (Rich console output, progress bars, etc.)
  • Supporting interactive mode (command-line interface)

If your application already has its own session management logic, you can skip GalaxyClient and use ConstellationClient directly. See GalaxyClient documentation for detailed API.

Typical Workflow Example

Let's walk through a complete example, from user request to device execution:

Scenario: Processing a Multi-Device Task

Suppose a user submits: "Download sales.xlsx from email, analyze it in Excel on Windows, then generate a report PDF on Linux".

Step 1: Initialize GalaxyClient

python
client = GalaxyClient()
await client.initialize()

What happens inside initialize():

  1. GalaxyClient loads device information from config file (device_info.yaml)
  2. Creates ConstellationClient instance and passes configuration
  3. ConstellationClient calls device_manager.register_device() to register each device
  4. If auto_connect: true is configured, automatically calls device_manager.connect_device()
  5. DeviceManager executes connection flow for each device (detailed below)

Step 2: Device Connection Flow (Inside DeviceManager)

For each device (e.g., "windows_pc" and "linux_server"), DeviceManager executes:

mermaid
sequenceDiagram
    participant DM as DeviceManager
    participant WS as WebSocketConnectionManager
    participant Server as Agent Server
    participant Device as Device Agent
    
    Note over DM,Device: 1. Establish WebSocket Connection
    DM->>WS: connect_to_device(device_info)
    WS->>Server: WebSocket handshake
    Server-->>WS: Connection established
    
    Note over DM,Device: 2. Register Device Identity (AIP REGISTER)
    WS->>Server: REGISTER message
    Server->>Device: Forward registration
    Device-->>Server: Service manifest (available MCP servers)
    Server-->>WS: REGISTER_CONFIRMATION
    
    Note over DM,Device: 3. Request Device System Info
    WS->>Server: DEVICE_INFO_REQUEST
    Server->>Device: Request system info
    Device-->>Server: System info (CPU, memory, OS, etc.)
    Server-->>WS: DEVICE_INFO_RESPONSE
    WS->>DM: Update AgentProfile
    
    Note over DM,Device: 4. Start Background Services
    DM->>DM: Start MessageProcessor (message handling loop)
    DM->>DM: Start HeartbeatManager (heartbeat loop)
    DM->>DM: Set device status to IDLE

This sequence diagram shows the connection establishment process. First, a WebSocket connection is established with the Agent Server. Then, the device registers its identity through the AIP REGISTER message, allowing the server to know which device is connecting and what capabilities it offers. Next, the client requests detailed system information from the device to populate the AgentProfile with actual hardware and software details. Finally, background services are started to maintain the connection and handle incoming messages.

Step 3: User Request Processing

python
result = await client.process_request("Download sales.xlsx...")

Inside process_request():

  1. GalaxyClient creates a GalaxySession
  2. GalaxySession calls ConstellationAgent for task planning
  3. ConstellationAgent (LLM-powered) decomposes task into DAG:
    • Task 1: Download sales.xlsx from email (requires "email" capability)
    • Task 2: Analyze in Excel (requires "office" capability, depends on Task 1)
    • Task 3: Generate PDF on Linux (requires "pdf_generation" capability, depends on Task 2)
  4. TaskConstellationOrchestrator executes DAG:
    • Based on capability matching, Task 1 assigned to device with "email" capability
    • Task 2 assigned to "windows_pc" (has "office" capability)
    • Task 3 assigned to "linux_server" (has "pdf_generation" capability)

The DAG structure ensures tasks execute in the correct order respecting dependencies, while allowing independent tasks to run in parallel across different devices.

Step 4: Task Assignment and Execution (ConstellationClient/DeviceManager)

For each task, ConstellationClient calls:

python
result = await client.assign_task_to_device(
    device_id="windows_pc",
    task_request=TaskRequest(
        task_id="task_2",
        request="Analyze sales.xlsx in Excel",
        ...
    )
)

Inside assign_task_to_device():

  1. DeviceManager checks device status (via DeviceRegistry)
  2. If device is IDLE, execute task immediately
  3. If device is BUSY, task enters queue (TaskQueueManager)
  4. WebSocketConnectionManager sends TASK message to device via AIP
  5. MessageProcessor waits in background for device to return COMMAND_RESULTS and TASK_END
  6. When task completes, DeviceManager changes device status back to IDLE
  7. If there are queued tasks, automatically dequeue and execute next task

The queuing mechanism ensures no tasks are lost when devices are busy, and tasks are executed in order as devices become available.

Step 5: Connection Monitoring (Continuous Background Process)

Throughout task execution, HeartbeatManager continuously monitors each device:

  • Sends HEARTBEAT message every 20-30 seconds
  • If device responds, updates last_heartbeat timestamp
  • If timeout with no response (2 × heartbeat_interval), triggers disconnection handling:
    • Stops MessageProcessor and HeartbeatManager
    • Sets device status to DISCONNECTED
    • If device was executing a task, marks task as failed
    • Attempts automatic reconnection (up to max_retries times)

This continuous monitoring ensures the system quickly detects and responds to connection failures, maintaining reliable communication with devices.

Step 6: Result Collection and Return

After all tasks complete:

  1. TaskConstellationOrchestrator aggregates all task results
  2. GalaxySession generates session results (including execution time, rounds, DAG statistics)
  3. GalaxyClient returns results to user
  4. Results are automatically saved to log directory

The complete execution trace is preserved in logs for debugging and analysis.

Relationships with Other System Components

Galaxy Client is not an isolated system—it closely collaborates with other UFO³ components:

Depends on Agent Server for Message Routing

Galaxy Client doesn't connect directly to devices but routes through Agent Server. Agent Server's role is to:

Maintain Device Registry: Tracks which devices are online and their connection details. When a device connects, Agent Server registers it in the central registry.

Route Messages: Forwards TASK messages from Galaxy Client to the correct device based on device_id. The server acts as a message broker, decoupling clients from devices.

Broadcast Device Status: Notifies clients when devices come online or go offline, enabling clients to maintain accurate device availability information.

Load Balancing: If multiple clients connect to the same device, Agent Server can distribute load and prevent conflicts.

Used by ConstellationAgent for Task Planning

When GalaxyClient receives a user request, it calls ConstellationAgent to decompose the request into a DAG (Directed Acyclic Graph). ConstellationAgent is LLM-powered and can:

Understand Natural Language: Parses user requests to identify subtasks and their relationships. For example, "Download file and then analyze it" is recognized as two sequential tasks.

Identify Task Dependencies: Determines which tasks must complete before others can start, constructing a proper dependency graph.

Suggest Device Assignments: Based on device capabilities, recommends which device should execute each task. If a task requires "office" capability, it's assigned to devices that advertise this capability.

Dynamically Adjust DAG: If issues arise during execution (e.g., a device fails), ConstellationAgent can replan and modify the DAG to adapt to the new situation.

For more details, see ConstellationAgent Documentation.

Coordinates with TaskConstellationOrchestrator for DAG Execution

Once ConstellationAgent creates the DAG, TaskConstellationOrchestrator executes it across devices. The orchestrator:

  • Respects Dependencies: Ensures tasks execute in the correct order based on the DAG structure
  • Selects Devices: Chooses appropriate devices based on capability matching
  • Parallel Execution: Runs independent tasks concurrently across different devices
  • Handles Failures: Manages task failures and triggers replanning if needed

For more details, see TaskConstellationOrchestrator Documentation.

Collaborates with Device Agents for Task Execution

The actual task execution happens on Device Agents running on each device (such as UFO² Desktop Agent, Linux Agent, etc.). Device Agents are responsible for:

Receiving Tasks: Accepts tasks from Agent Server and parses task requirements. Each task specifies what action to perform and what parameters to use.

Invoking MCP Servers: Calls local MCP servers to perform specific operations (such as opening Excel, running commands, etc.). MCP servers provide the actual execution capabilities.

Reporting Progress: Sends intermediate execution results through COMMAND_RESULTS messages, allowing clients to track progress in real-time.

Handling Errors: Deals with local errors and exceptions, reporting them back to the client through ERROR messages for proper error handling.

Unified Communication through AIP Protocol

All cross-component communication follows the AIP protocol. AIP provides:

Standardized Message Formats: Uses Pydantic models to define message structure, ensuring type safety and validation at both ends of communication.

Type-Safe Message Validation: Automatically validates message fields using Pydantic, catching errors early before they propagate through the system.

Request-Response Correlation: Uses request_id/response_id fields to match requests with their responses, enabling proper async handling.

Error Handling Mechanism: Defines standard ERROR message types for reporting and handling failures consistently across all components.

Configuration and Deployment

Device Configuration

Device information is defined through configuration files. See Galaxy Configuration for complete configuration options.

A typical configuration example:

yaml
# config/galaxy/constellation.yaml
task_name: "production_constellation"
heartbeat_interval: 30.0  # Heartbeat interval (seconds)
reconnect_delay: 5.0      # Reconnection delay (seconds)
max_concurrent_tasks: 5   # Max concurrent tasks per device

devices:
  - device_id: "windows_pc"
    server_url: "ws://192.168.1.100:5000/ws"
    os: "windows"
    capabilities: ["office", "email", "web"]
    auto_connect: true
    max_retries: 5  # Maximum reconnection attempts
    
  - device_id: "linux_server"
    server_url: "ws://192.168.1.101:5000/ws"
    os: "linux"
    capabilities: ["database", "api", "pdf_generation"]
    auto_connect: true
    max_retries: 10

Configuration fields explained:

  • task_name: Unique identifier for this constellation, used in logs and debugging
  • heartbeat_interval: How often to check device health (recommended: 20-30 seconds)
  • reconnect_delay: Wait time between reconnection attempts (recommended: 3-5 seconds)
  • max_concurrent_tasks: Maximum tasks a device can execute simultaneously
  • capabilities: List of capabilities each device provides, used for task assignment
  • auto_connect: Whether to automatically connect when client initializes
  • max_retries: Maximum reconnection attempts before giving up

Development vs Production Environment

Development Recommendations:

  • Use interactive mode for quick testing: python -m galaxy --interactive
  • Enable DEBUG log level for detailed information
  • Single-device configuration to simplify debugging
  • Use local Agent Server (ws://127.0.0.1:5000/ws)
  • Lower heartbeat_interval (e.g., 10 seconds) for faster failure detection

Production Recommendations:

  • Use WSS (secure WebSocket) instead of WS for encrypted communication
  • Configure reasonable heartbeat_interval (20-30 seconds) to balance responsiveness and network overhead
  • Set appropriate max_retries (5-10 attempts) based on network reliability
  • Enable automatic reconnection (auto_connect: true) for resilience
  • Monitor device health status via get_device_status() API and set up alerts
  • Configure log rotation and archiving to prevent disk space issues
  • Use connection pooling if connecting to many devices
  • Implement circuit breaker pattern for failing devices

Detailed Component Documentation

Summary

Galaxy Client provides the core multi-device coordination capabilities in UFO³. Through layered design, it simplifies complex distributed system management into clear APIs:

  • ConstellationClient is the core of device management, handling device registration, connection, and task assignment
  • DeviceManager is the underlying engine, processing WebSocket, heartbeat, message routing, and task queuing
  • GalaxyClient is an optional session wrapper, providing more convenient high-level APIs

If you're new to Galaxy Client, we recommend reading the documentation in this order:

  1. This Overview (understand overall architecture and workflow)
  2. ConstellationClient (learn core API)
  3. Components (understand modular components)
  4. DeviceManager (dive deep into connection management)
  5. AIP Integration (master communication protocol)

If you need to get started quickly, jump directly to GalaxyClient example code.


Documents Docs Galaxy Constellation Overview (`documents/docs/galaxy/constellation/overview.md`)

Task Constellation — Overview

Task Constellation DAG Structure

Example of a Task Constellation illustrating both sequential and parallel dependencies


🌌 Introduction

The Task Constellation is the central abstraction in Galaxy that captures the concurrent and asynchronous structure of distributed task execution. It provides a formal, directed acyclic graph (DAG) representation of complex workflows, enabling consistent scheduling, fault-tolerant orchestration, and runtime dynamism across heterogeneous devices.

At its core, a Task Constellation decomposes complex user requests into interdependent subtasks connected through explicit dependency edges. This formalism not only enables correct distributed execution but also supports runtime adaptation—allowing new tasks or dependencies to be introduced as the workflow evolves.

For information on how Task Constellations are orchestrated and scheduled, see the Constellation Orchestrator documentation. To understand how agents interact with constellations, refer to the Constellation Agent guide.


🎯 Core Components

The Task Constellation framework consists of four primary components:

Component Purpose Key Features
TaskStar Atomic execution unit Self-contained task with description, device assignment, execution state, dependencies
TaskStarLine Dependency relationship Directed edge with conditional logic, success-only, completion-only, or unconditional execution
TaskConstellation DAG orchestrator Complete workflow graph with validation, scheduling, and dynamic modification
ConstellationEditor Interactive editor Command pattern-based interface with undo/redo for safe constellation manipulation

📐 Formal Model

Mathematical Foundation

A Task Constellation $\mathcal{C}$ is formally defined as a directed acyclic graph (DAG):

$$
\mathcal{C} = (\mathcal{T}, \mathcal{E})
$$

where:

  • $\mathcal{T}$ is the set of all TaskStars (task nodes)
  • $\mathcal{E}$ is the set of TaskStarLines (dependency edges)

TaskStar Representation

Each TaskStar $t_i \in \mathcal{T}$ encapsulates a complete task specification:

$$
t_i = (\text{name}_ i, \text{description}_ i, \text{target_device_id}_ i, \text{tips}_ i, \text{status}_ i, \text{dependencies}_ i)
$$

Components:

  • name: Short name for the task
  • description: Natural-language specification sent to the device agent
  • target_device_id: ID of the device agent responsible for execution
  • tips: List of guidance hints to help the device agent complete the task
  • status: Current execution state (pending, running, completed, failed, cancelled, waiting_dependency)
  • dependencies: Set of prerequisite task IDs that must complete first

TaskStarLine Representation

Each TaskStarLine $e_{i \rightarrow j} \in \mathcal{E}$ represents a dependency from task $t_i$ to task $t_j$.

Dependency Types:

Type Behavior
Unconditional $t_j$ always waits for $t_i$ to complete
Success-only $t_j$ proceeds only if $t_i$ succeeds
Completion-only $t_j$ proceeds when $t_i$ completes (regardless of success/failure)
Conditional $t_j$ proceeds based on a user-defined or runtime condition

✨ Key Advantages

1. Explicit Task Ordering

Task dependencies are explicitly captured in the DAG structure, ensuring correctness across distributed execution without ambiguity.

2. Natural Parallelism

The DAG topology naturally exposes parallelizable tasks, enabling efficient concurrent execution across heterogeneous devices.

3. Runtime Dynamism

Unlike static DAG schedulers, Task Constellations are mutable objects. Tasks and dependency edges can be:

  • Added: Introduce new subtasks or diagnostic tasks
  • Removed: Prune completed or redundant nodes
  • Modified: Rewire dependencies, update conditions, change device assignments

This enables adaptive execution without restarting the entire workflow.

4. Formal Guarantees

The DAG representation provides formal properties:

  • Acyclicity: No circular dependencies
  • Causal consistency: Execution respects logical ordering
  • Safe concurrency: Parallel execution without race conditions

🔄 Lifecycle States

The Task Constellation progresses through several states during its lifecycle:

mermaid
stateDiagram-v2
    [*] --> CREATED: Initialize
    CREATED --> READY: Add tasks & dependencies
    READY --> EXECUTING: Start execution
    EXECUTING --> EXECUTING: Tasks running
    EXECUTING --> COMPLETED: All tasks succeed
    EXECUTING --> FAILED: All tasks fail
    EXECUTING --> PARTIALLY_FAILED: Some succeed, some fail
    COMPLETED --> [*]
    FAILED --> [*]
    PARTIALLY_FAILED --> [*]
State Description
CREATED Constellation initialized, no tasks added
READY Tasks and dependencies configured, ready to execute
EXECUTING At least one task is running or completed
COMPLETED All tasks completed successfully
FAILED All tasks failed
PARTIALLY_FAILED Some tasks succeeded, some failed

📊 DAG Metrics

Parallelism Analysis

The Task Constellation provides several metrics to analyze workflow parallelism:

Critical Path Length ($L$)

The longest serial dependency chain in the constellation:

$$
L = \max_{p \in \text{paths}} |p|
$$

where $|p|$ is the length of path $p$ from any root to any leaf node.

Total Work ($W$)

Sum of all task execution durations:

$$
W = \sum_{t_i \in \mathcal{T}} \text{duration}(t_i)
$$

Parallelism Ratio ($P$)

Measure of achievable parallelism:

$$
P = \frac{W}{L}
$$

  • $P = 1$: Completely serial execution
  • $P > 1$: Parallel execution possible
  • Higher $P$ indicates more parallelism

Maximum Width

Maximum number of tasks that can execute concurrently:

$$
\text{MaxWidth} = \max_{\text{level}} |\text{tasks at level}|
$$

!!!info "Calculation Modes"
The constellation supports two calculation modes:

text
- **Node Count Mode**: Uses task counts when execution is incomplete
- **Actual Time Mode**: Uses real execution durations when all tasks are terminal

🛠️ Core Operations

DAG Construction

python
from galaxy.constellation import TaskConstellation, TaskStar, TaskStarLine

# Create constellation
constellation = TaskConstellation(name="my_workflow")

# Add tasks
task_a = TaskStar(name="task_a", description="Checkout code on laptop")
task_b = TaskStar(name="task_b", description="Build on GPU server")
task_c = TaskStar(name="task_c", description="Deploy to staging")

constellation.add_task(task_a)
constellation.add_task(task_b)
constellation.add_task(task_c)

# Add dependencies
dep_ab = TaskStarLine.create_success_only(
    from_task_id=task_a.task_id,
    to_task_id=task_b.task_id,
    description="Build depends on successful checkout"
)

dep_bc = TaskStarLine.create_unconditional(
    from_task_id=task_b.task_id,
    to_task_id=task_c.task_id,
    description="Deploy after build"
)

constellation.add_dependency(dep_ab)
constellation.add_dependency(dep_bc)

DAG Validation

python
# Validate structure
is_valid, errors = constellation.validate_dag()
if not is_valid:
    print(f"Validation errors: {errors}")

# Check for cycles
has_cycles = constellation.has_cycle()

# Get topological order
order = constellation.get_topological_order()
print(f"Execution order: {order}")

Parallelism Analysis

python
# Get parallelism metrics
metrics = constellation.get_parallelism_metrics()

print(f"Critical Path Length: {metrics['critical_path_length']}")
print(f"Total Work: {metrics['total_work']}")
print(f"Parallelism Ratio: {metrics['parallelism_ratio']}")
print(f"Critical Path: {metrics['critical_path_tasks']}")

# Get maximum width
max_width = constellation.get_max_width()
print(f"Maximum concurrent tasks: {max_width}")

🔧 Dynamic Modification

Safe Editing with ConstellationEditor

python
from galaxy.constellation.editor import ConstellationEditor

# Create editor with undo/redo support
editor = ConstellationEditor(constellation)

# Add a new diagnostic task
diagnostic_task = editor.create_and_add_task(
    task_id="diag_1",
    description="Check server health",
    name="Server Health Check"
)

# Add conditional dependency
editor.create_and_add_dependency(
    from_task_id=task_b.task_id,
    to_task_id=diagnostic_task.task_id,
    dependency_type="CONDITIONAL",
    condition_description="Run diagnostic if build fails"
)

# Undo if needed
if something_wrong:
    editor.undo()

# Get modifiable components
modifiable_tasks = constellation.get_modifiable_tasks()
modifiable_deps = constellation.get_modifiable_dependencies()

!!!warning "Modification Safety"
Tasks and dependencies can only be modified if they are in PENDING or WAITING_DEPENDENCY status. Running or completed tasks cannot be modified to ensure execution consistency.


📈 Example Workflows

Sequential Workflow

mermaid
graph LR
    A[Task A] --> B[Task B]
    B --> C[Task C]
  • Parallelism Ratio: 1.0 (completely serial)
  • Maximum Width: 1

Parallel Workflow

mermaid
graph LR
    A[Task A] --> B[Task B]
    A --> C[Task C]
    B --> D[Task D]
    C --> D
  • Parallelism Ratio: 2.0 (B and C can run in parallel)
  • Maximum Width: 2

Complex Workflow

mermaid
graph LR
    A[Task A] --> B[Task B]
    A --> C[Task C]
    B --> D[Task D]
    C --> E[Task E]
    D --> F[Task F]
    E --> F
  • Parallelism Ratio: ~1.67
  • Maximum Width: 3 (B, C, E can run concurrently after A completes)

🎨 Visualization

The Task Constellation provides multiple visualization modes for monitoring and debugging:

Overview Mode

High-level constellation structure with task counts and state

Topology Mode

DAG graph showing task relationships and dependencies

Details Mode

Detailed task information including execution times and status

Execution Mode

Real-time execution flow with progress tracking

python
# Display constellation
constellation.display_dag(mode="overview")  # or "topology", "details", "execution"

For interactive web-based visualization, check out the Galaxy WebUI.


📚 Component Documentation

Explore detailed documentation for each component:

  • TaskStar — Atomic execution units representing individual tasks in the constellation
  • TaskStarLine — Dependency relationships connecting tasks with conditional logic
  • TaskConstellation — Complete DAG orchestrator managing workflow execution and coordination
  • ConstellationEditor — Interactive editor with command pattern and undo/redo capabilities

🔬 Research Background

The Task Constellation model is grounded in formal DAG theory and distributed systems research. Key properties include:

  • Acyclicity guarantees through Kahn's algorithm for topological sorting
  • Topological ordering for consistent execution
  • Critical path analysis for performance optimization
  • Dynamic graph evolution without compromising consistency

For more on Galaxy's architecture and design principles, see the Galaxy Overview.


💡 Best Practices

!!!tip "Designing Effective Constellations"
1. Keep tasks atomic: Each TaskStar should represent a single, well-defined operation
2. Minimize dependencies: Reduce unnecessary dependencies to maximize parallelism
3. Use appropriate dependency types: Choose conditional dependencies for error handling
4. Validate early: Run validate_dag() before execution
5. Monitor metrics: Track parallelism ratio to optimize workflow design

Common Patterns:

  • Fan-out: One task spawns multiple independent parallel tasks
  • Fan-in: Multiple parallel tasks converge to a single task
  • Pipeline: Sequential stages with parallel tasks within each stage
  • Conditional branching: Use conditional dependencies for error handling paths

🚀 Next Steps


Documents Docs Galaxy Constellation Agent Overview (`documents/docs/galaxy/constellation_agent/overview.md`)

Constellation Agent — The Centralized Constellation Weaver

The Constellation Agent serves as the central intelligence of UFO³ Galaxy, acting as both a planner and replanner. It interprets user intent, constructs executable Task Constellations, and dynamically steers their evolution across heterogeneous devices. By bridging high-level natural-language goals and concrete multi-agent execution, the Constellation Agent provides unified orchestration through a feedback-driven control loop.

For an overview of the Galaxy system architecture, see Galaxy Overview.

🌟 Introduction

Figure: An overview of the Constellation Agent showing the dual-mode control cycle between creation and editing phases.

The Constellation Agent extends the abstract Task Constellation model into runtime execution. Residing within the ConstellationClient (see Galaxy Client), it transforms user requests into structured DAG workflows and continuously refines them as distributed agents provide feedback.

Unlike traditional static DAG schedulers, the Constellation Agent operates as a dynamic orchestrator powered by an LLM-driven architecture and governed by a finite-state machine (FSM). This design enables it to alternate between two complementary operating modes:

  • Creation Mode: Synthesizes initial Task Constellations from user instructions
  • Editing Mode: Incrementally refines constellations based on runtime feedback

This feedback-driven control loop achieves tight coupling between symbolic reasoning and distributed execution, maintaining global consistency while adapting to changing device conditions.

🎯 Core Responsibilities

The Constellation Agent orchestrates distributed workflows through structured feedback loops, alternating between creation and editing phases with explicit operational boundaries. For details on task execution, see Constellation Orchestrator.

Primary Functions

Function Description Mode
Request Interpretation Parse user goals and context into actionable requirements Creation
DAG Synthesis Decompose requests into structured Task Constellations with dependencies Creation
Device Assignment Map tasks to appropriate devices based on AgentProfile capabilities Creation
Runtime Monitoring Track task completion events and constellation state Editing
Dynamic Adaptation Add, remove, or modify tasks/dependencies based on feedback Editing
Consistency Maintenance Ensure DAG validity and execution correctness throughout lifecycle Both

🏗️ Architecture

Dual-Mode Control System

The Constellation Agent implements a dual-mode control pattern that separates planning from replanning:

mermaid
graph LR
    A[User Request] --> B[Creation Mode]
    B --> C[Initial Constellation]
    C --> D[Orchestrator]
    D --> E[Task Execution]
    E --> F{Event Queue}
    F -->|Task Completed| G[Editing Mode]
    G --> H[Updated Constellation]
    H --> D
    F -->|All Complete| I[Finish]
    
    style B fill:#e1f5ff
    style G fill:#fff4e1
    style I fill:#e8f5e9

Component Integration

mermaid
graph TB
    subgraph "Constellation Agent"
        FSM[Finite State Machine]
        Prompter[Prompter]
        Processor[Agent Processor]
    end
    
    subgraph "MCP Layer"
        Dispatcher[Command Dispatcher]
        MCP[MCP Server Manager]
        Editor[Constellation Editor MCP]
    end
    
    subgraph "Execution Layer"
        Orchestrator[Task Orchestrator]
        EventBus[Event Bus]
    end
    
    FSM --> Prompter
    Prompter --> Processor
    Processor --> Dispatcher
    Dispatcher --> MCP
    MCP --> Editor
    Editor --> Orchestrator
    Orchestrator --> EventBus
    EventBus -->|Task Events| FSM
    
    style FSM fill:#e1f5ff
    style MCP fill:#fff4e1
    style Orchestrator fill:#e8f5e9

🔄 Creation Mode

In creation mode, the Constellation Agent receives a user request and generates the initial Task Constellation.

Inputs

Input Type Description
User Request str Natural language goal or structured command
AgentProfile Registry Dict[str, AgentProfile] Available device agents with capabilities and metadata
Demonstration Examples List[Example] In-context learning examples for task decomposition

Processing Flow

mermaid
sequenceDiagram
    participant User
    participant Agent as Constellation Agent
    participant Prompter
    participant LLM
    participant Dispatcher as Command Dispatcher
    participant MCP as MCP Server Manager
    participant Editor as Constellation Editor MCP
    participant Orchestrator
    
    User->>Agent: Submit Request
    Agent->>Prompter: Format Creation Prompt
    Prompter->>LLM: Send Prompt + Examples
    LLM->>Agent: Return Constellation JSON
    Agent->>Dispatcher: Execute build_constellation
    Dispatcher->>MCP: Route Command
    MCP->>Editor: Call build_constellation
    Editor->>MCP: Return Built Constellation
    MCP->>Dispatcher: Return Result
    Dispatcher->>Agent: Constellation Ready
    Agent->>Orchestrator: Start Execution
    Orchestrator-->>Agent: Constellation Started
    Agent->>User: Display Initial Plan

Outputs

Output Type Description
Task Constellation TaskConstellation Structured DAG with tasks and dependencies
Observation str Analysis of input context and device profiles
Thought str Reasoning trace explaining decomposition logic
State ConstellationAgentStatus Next FSM state (typically CONTINUE)
Result Any Summary for user or error message

Example: Creation Mode Response

User Request: "Download dataset on laptop, preprocess on server, train model on GPU"

Generated Constellation:

  • Task 1: fetch_data → Device: laptop
  • Task 2: preprocess → Device: linux_server (depends on Task 1)
  • Task 3: train_model → Device: gpu_server (depends on Task 2)

Thought: "Decomposed into 3 sequential tasks based on computational requirements. Laptop handles download, server preprocesses data, GPU server trains model."

✏️ Editing Mode

During execution, the Constellation Agent enters editing mode to process task completion events and adapt the constellation.

Inputs

Input Type Description
Original Request str The initial user request for context
AgentProfile Registry Dict[str, AgentProfile] Current device availability
Current Constellation TaskConstellation Serialized constellation snapshot
Task Events List[TaskEvent] Completion/failure events from orchestrator
Demonstration Examples List[Example] In-context learning examples for editing

Processing Flow

mermaid
sequenceDiagram
    participant Orchestrator
    participant EventBus
    participant Agent as Constellation Agent
    participant Prompter
    participant LLM
    participant Dispatcher as Command Dispatcher
    participant MCP as MCP Server Manager
    participant Editor as Constellation Editor MCP
    
    Orchestrator->>EventBus: Task Completed Event
    EventBus->>Agent: Queue Event
    Agent->>Agent: Collect Pending Events
    Agent->>Dispatcher: Sync Constellation State
    Dispatcher->>MCP: build_constellation (sync)
    MCP->>Editor: Update State
    Agent->>Prompter: Format Editing Prompt
    Prompter->>LLM: Send Current State + Events
    LLM->>Agent: Return Modification Actions
    Agent->>Dispatcher: Execute Modification Commands
    Dispatcher->>MCP: Route Commands
    MCP->>Editor: Apply Modifications
    Editor->>MCP: Return Updated Constellation
    MCP->>Dispatcher: Return Results
    Dispatcher->>Agent: Constellation Updated
    Agent->>EventBus: Publish Modified Event
    Agent->>Orchestrator: Continue Execution

Editing Operations

The agent can perform the following modifications through the MCP-based Constellation Editor:

Operation Use Case Example
Add Task Introduce follow-up or diagnostic tasks Add health check after training fails
Remove Task Prune redundant or obsolete tasks Remove preprocessing if data is pre-processed
Update Task Modify description, device, or tips Switch training to different GPU
Add Dependency Establish new task relationships Make validation depend on training
Remove Dependency Decouple independent tasks Remove unnecessary sequential constraint
Update Dependency Change conditional logic Update success criteria for task trigger

Note: Only tasks in PENDING or WAITING_DEPENDENCY status can be modified. Running or completed tasks are read-only to ensure execution consistency.

Outputs

Output Type Description
Updated Constellation TaskConstellation Modified DAG with new tasks/dependencies
Thought str Reasoning explaining modifications or no-op
State ConstellationAgentStatus Next FSM state (CONTINUE, FINISH, or FAIL)
Result Any Summary of changes or completion status

🔁 Finite-State Machine Lifecycle

Figure: Lifecycle state transitions of the Constellation Agent FSM.

The Constellation Agent's behavior is governed by a 4-state finite-state machine:

State Description Triggers
START Initialize constellation, begin orchestration Agent instantiation, restart after completion
CONTINUE Monitor events, process feedback, update constellation Task completion/failure events
FINISH Successful termination, aggregate results All tasks completed successfully
FAIL Terminal error state, abort execution Irrecoverable errors, validation failures

State Transition Rules

mermaid
stateDiagram-v2
    [*] --> START: Initialize Agent
    START --> CONTINUE: Constellation Created
    START --> FAIL: Creation Failed
    
    CONTINUE --> CONTINUE: Process Events
    CONTINUE --> FINISH: All Tasks Complete
    CONTINUE --> FAIL: Critical Error
    CONTINUE --> START: New Constellation Needed
    
    FINISH --> [*]
    FAIL --> [*]
    
    note right of START
        Creation Mode:
        - Generate initial constellation
        - Validate DAG structure
        - Start orchestration
    end note
    
    note right of CONTINUE
        Editing Mode:
        - Wait for task events
        - Process completion feedback
        - Apply modifications
    end note

For detailed state machine documentation, see State Machine Details.

🛠️ MCP-Based Constellation Editor

The Constellation Agent interacts with the Constellation Editor through the Model Context Protocol (MCP) layer. The architecture uses:

  • MCP Server Manager: Routes commands to appropriate MCP servers
  • Command Dispatcher: Provides a unified interface for executing MCP commands
  • Constellation Editor MCP Server: Implements the actual constellation manipulation operations

This MCP-based architecture provides:

  • Protocol Standardization: Consistent interface across all agent types
  • Loose Coupling: Agent logic decoupled from editor implementation
  • Extensibility: Easy to add new operations or alternative editors
  • Tool Discovery: Dynamic tool listing via list_tools command

Core MCP Operations

The Constellation Editor MCP Server exposes the following operations:

Operation Purpose Inputs Output
build_constellation Batch-create constellation from config Configuration dict, clear flag Built constellation
add_task Add atomic task node Task ID, name, description, device, tips Updated constellation
remove_task Remove task and dependencies Task ID Updated constellation
update_task Modify task fields Task ID + updated fields Updated constellation
add_dependency Create dependency edge From/to task IDs, type, condition Updated constellation
remove_dependency Delete dependency Dependency ID Updated constellation
update_dependency Update dependency logic Dependency ID, condition Updated constellation

All operations are:

  • Idempotent: Safe to retry without side effects
  • Atomic: Single operation per command
  • Validated: Ensures DAG consistency after each modification
  • Auditable: All changes are logged and traceable

For complete MCP command specifications and examples, see Command Reference. For details on the underlying Task Constellation structure, see Task Constellation Overview.

📋 Processing Pipeline

The Constellation Agent follows a 4-phase processing pipeline for both creation and editing modes:

Phase 1: Context Provision

python
# Load available MCP tools from Constellation Editor
await agent.context_provision(context=context)
# Queries MCP server for available operations via list_tools
# Formats tools into LLM-compatible prompt

Phase 2: LLM Interaction

python
# Construct prompt based on mode
prompt = agent.message_constructor(
    request=user_request,
    device_info=agent_profiles,
    constellation=current_constellation
)

# Get LLM response
response = await llm.query(prompt)
# Returns: ConstellationAgentResponse with thought, status, actions

Phase 3: Action Execution

python
# Execute MCP commands via Command Dispatcher
for command in response.actions:
    result = await context.command_dispatcher.execute_commands([command])
    
# Validate constellation
is_valid, errors = constellation.validate_dag()

Phase 4: Memory Update

python
# Update global context
context.set(ContextNames.CONSTELLATION, updated_constellation)
context.set(ContextNames.ROUND_RESULT, results)

# Log to memory
memory.add_round_log(
    step=step,
    weaving_mode=mode,
    request=request,
    constellation=constellation,
    response=response
)

🎭 Prompter Architecture

The Constellation Agent uses the Factory Pattern to create appropriate prompters for different weaving modes (creation and editing).

Prompter Hierarchy

mermaid
classDiagram
    class BaseConstellationPrompter {
        <<abstract>>
        +format_agent_profile()
        +format_constellation()
        +user_content_construction()
        +system_prompt_construction()
    }
    
    class ConstellationCreationPrompter {
        +user_prompt_construction()
        +examples_prompt_helper()
    }
    
    class ConstellationEditingPrompter {
        +user_prompt_construction()
        +examples_prompt_helper()
    }
    
    class ConstellationPrompterFactory {
        +create_prompter(mode)
        +get_supported_modes()
    }
    
    BaseConstellationPrompter <|-- ConstellationCreationPrompter
    BaseConstellationPrompter <|-- ConstellationEditingPrompter
    ConstellationPrompterFactory --> BaseConstellationPrompter

Factory Pattern Benefits

Benefit Description
Mode Isolation Creation and editing prompts remain independent
Extensibility New modes can be added without modifying existing code
Type Safety Compile-time checking for prompter selection
Testability Each prompter can be unit tested independently

For complete prompter architecture documentation, see Prompter Details.

💡 Key Design Benefits

1. Unified Reasoning and Control

High-level task synthesis and low-level execution coordination are decoupled yet tightly synchronized through the Task Constellation abstraction. The agent focuses on semantic reasoning while the orchestrator handles distributed execution.

2. Dynamic Adaptability

The editable constellation enables:

  • Failure Recovery: Add diagnostic tasks after failures
  • Resource Reallocation: Switch tasks to available devices
  • Opportunistic Execution: Insert new tasks as conditions permit

3. End-to-End Observability

Complete lineage tracking of:

  • State Transitions: FSM state changes logged with timestamps
  • Modifications: All edits tracked with before/after snapshots
  • Events: Task completion events queued and processed
  • Reasoning Traces: LLM thought processes captured in memory

4. Safe Modification Guarantees

The FSM + MCP Server architecture ensures:

  • Acyclicity: DAG validation prevents circular dependencies
  • Consistency: Only modifiable tasks can be edited
  • Atomicity: Each MCP operation is atomic and idempotent
  • Auditability: Full modification history maintained

🔍 Example Workflow

User Request

text
"Download MNIST dataset on laptop, train CNN on GPU server, 
evaluate on test server, deploy to production if accuracy > 95%"

Creation Mode Output

json
{
  "thought": "Decomposed into 4 tasks: (1) download on laptop, (2) train on GPU, (3) evaluate on test server, (4) conditional deploy based on accuracy",
  "status": "CONTINUE",
  "constellation": {
    "tasks": [
      {"task_id": "task_001", "name": "download_mnist", "device": "laptop"},
      {"task_id": "task_002", "name": "train_cnn", "device": "gpu_server"},
      {"task_id": "task_003", "name": "evaluate", "device": "test_server"},
      {"task_id": "task_004", "name": "deploy", "device": "prod_server"}
    ],
    "dependencies": [
      {"from": "task_001", "to": "task_002", "type": "SUCCESS_ONLY"},
      {"from": "task_002", "to": "task_003", "type": "SUCCESS_ONLY"},
      {"from": "task_003", "to": "task_004", "type": "CONDITIONAL", 
       "condition": "accuracy > 0.95"}
    ]
  }
}

Editing Mode Event

text
Task task_003 (evaluate) completed with result: {"accuracy": 0.92}

Editing Mode Output

json
{
  "thought": "Evaluation accuracy (92%) did not meet deployment threshold (95%). Adding retraining task with adjusted hyperparameters. Removing original deployment task.",
  "status": "CONTINUE",
  "actions": [
    {"tool": "add_task", "parameters": {
      "task_id": "task_005", 
      "name": "retrain_with_tuning",
      "device": "gpu_server",
      "description": "Retrain with learning rate decay and data augmentation"
    }},
    {"tool": "add_dependency", "parameters": {
      "from": "task_003", "to": "task_005", "type": "SUCCESS_ONLY"
    }},
    {"tool": "remove_task", "parameters": {"task_id": "task_004"}}
  ]
}

📊 Performance Characteristics

Creation Complexity

  • Time: $O(n \cdot m)$ where $n$ is task count, $m$ is LLM inference time
  • Space: $O(n + e)$ for $n$ tasks and $e$ edges
  • Validation: $O(n + e)$ for DAG cycle detection (DFS)

Editing Complexity

  • Event Processing: $O(k)$ for $k$ queued events (batched)
  • Modification: $O(1)$ per MCP command (constant time)
  • Re-validation: $O(n + e)$ for modified constellation

Scalability

Metric Typical Maximum Tested
Tasks per Constellation 5-20 100+
Dependencies per Constellation 4-30 200+
Editing Events per Session 1-10 50+
LLM Response Time 2-5s 15s

🎯 Summary

The Constellation Agent serves as the central weaver of distributed intelligence in UFO³ Galaxy. Through its dual-mode control loop, finite-state machine governance, and MCP-based constellation manipulation, it transforms abstract user goals into live, evolving constellations—maintaining both rigor and adaptability across the complete lifecycle of multi-device orchestration.

Key Capabilities:

  • Semantic Decomposition: Natural language → structured DAG
  • Dynamic Adaptation: Runtime graph evolution based on feedback
  • MCP Integration: Protocol-based tool invocation for extensibility
  • Formal Guarantees: DAG validity + safe concurrent modification
  • Complete Observability: Full lineage tracking and reasoning traces
  • Modular Design: Clean separation between reasoning and execution

Documents Docs Galaxy Constellation Orchestrator Overview (`documents/docs/galaxy/constellation_orchestrator/overview.md`)

Constellation Orchestrator Overview

Introduction

The Constellation Orchestrator is the execution engine at the heart of UFO's multi-device orchestration system. While the Constellation Agent handles reasoning and task graph evolution, the orchestrator transforms these declarative plans into concrete execution across heterogeneous devices.

Unlike traditional DAG schedulers that execute static task graphs, the Constellation Orchestrator operates as a living execution fabric where tasks evolve concurrently, react to runtime signals, and adapt to new decisions from the reasoning agent in real-time.

The Constellation Orchestrator bridges TaskConstellation and execution, enabling asynchronous, adaptive task orchestration across devices.

Key Capabilities

The orchestrator achieves three critical goals that traditional schedulers struggle to balance:

Capability Description Benefit
Asynchronous Parallelism Execute independent tasks concurrently across heterogeneous devices Maximize device utilization and minimize idle time
Safety & Consistency Maintain correctness under concurrent DAG updates from LLM reasoning Prevent race conditions and invalid execution states
Runtime Adaptivity React to feedback from both devices and LLM reasoning dynamically Enable intelligent re-planning and error recovery

Architecture Overview

The Constellation Orchestrator is built on five fundamental design pillars:

mermaid
graph TB
    A[Event-Driven Coordination] --> B[Orchestrator Core]
    C[Asynchronous Scheduling] --> B
    D[Safe Assignment Locking] --> B
    E[Consistency Enforcement] --> B
    F[Batched Editing] --> B
    
    B --> G[Device Execution]
    B --> H[Constellation Evolution]
    
    style B fill:#4a90e2,stroke:#333,stroke-width:3px,color:#fff
    style A fill:#7cb342,stroke:#333,stroke-width:2px
    style C fill:#7cb342,stroke:#333,stroke-width:2px
    style D fill:#7cb342,stroke:#333,stroke-width:2px
    style E fill:#7cb342,stroke:#333,stroke-width:2px
    style F fill:#7cb342,stroke:#333,stroke-width:2px

1. Event-Driven Coordination

The orchestrator operates as a fully event-driven system using an observer pattern and internal event bus. Instead of polling or global checkpoints, it reacts immediately to four primary event types:

  • TASK_STARTED - Task assigned and execution begins
  • TASK_COMPLETED - Task finishes successfully
  • TASK_FAILED - Task execution fails
  • CONSTELLATION_MODIFIED - DAG structure updated by agent

This design provides high responsiveness and eliminates synchronization overhead.

Learn more →

2. Asynchronous Scheduling

A continuous scheduling loop monitors the evolving TaskConstellation, identifies ready tasks (dependencies satisfied), and dispatches them concurrently to available devices. Critically, task execution and constellation editing proceed in parallel, overlapping computation with orchestration.

This enables maximum parallelism and minimal latency in cross-device workflows.

Learn more →

3. Safe Assignment Locking

To prevent race conditions when LLM-driven edits overlap with task execution, the orchestrator employs a safe assignment lock protocol. During edit cycles, new task assignments are suspended while modifications are applied atomically and synchronized with runtime progress.

This guarantees atomicity and prevents conflicts between execution and modification.

Learn more →

4. Consistency Enforcement

The orchestrator enforces three runtime invariants to preserve correctness even under partial or invalid LLM updates:

  • I1 (Single Assignment): Each task has at most one active device assignment
  • I2 (Acyclic Consistency): Edits preserve DAG acyclicity (no cycles)
  • I3 (Valid Update): Only PENDING tasks and their dependents can be modified

These invariants ensure structural integrity and semantic validity of the constellation.

Learn more →

5. Batched Constellation Editing

To balance responsiveness with efficiency, the orchestrator batches multiple task completion events and applies their resulting modifications atomically. This amortizes LLM invocation overhead while preserving atomicity and consistency.

This achieves both efficiency and adaptivity without excessive micro-edits.

Learn more →

System Components

The orchestrator consists of two primary components working in tandem:

TaskConstellationOrchestrator

The main execution orchestrator focused on flow control and coordination. It manages:

  • Event-driven task lifecycle (start, complete, fail)
  • Asynchronous scheduling loop
  • Safe assignment locking protocol
  • Integration with modification synchronizer

API Reference →

ConstellationManager

Handles device assignment, resource management, and constellation lifecycle. It provides:

  • Multiple assignment strategies (round-robin, capability-match, load-balance)
  • Device validation and status tracking
  • Constellation registration and metadata management

Learn more →

Execution Flow

The orchestration workflow follows this sequence:

mermaid
sequenceDiagram
    participant U as User Request
    participant O as Orchestrator
    participant C as Constellation
    participant S as Synchronizer
    participant D as Devices
    participant A as Agent

    U->>O: orchestrate_constellation()
    O->>C: Validate DAG
    O->>C: Assign devices
    
    loop Execution Loop
        O->>C: Get ready tasks
        O->>D: Dispatch tasks (async)
        D-->>O: Task completed event
        O->>S: Wait for modifications
        S->>A: Trigger editing
        A->>C: Update constellation
        A-->>S: Modification complete
        S->>O: Sync constellation state
    end
    
    O->>U: Return results

The orchestrator treats task execution as an open-world process - continuously evolving, reacting, and converging toward user intent rather than executing a fixed plan.

Design Highlights

Asynchronous by Default

Every operation runs asynchronously using Python's asyncio, enabling:

  • Concurrent task execution across devices
  • Non-blocking event handling
  • Parallel constellation editing

LLM-Aware Orchestration

Unlike traditional schedulers, the orchestrator is designed for reasoning-aware execution:

  • Expects and handles dynamic graph modifications
  • Synchronizes LLM reasoning with runtime execution
  • Validates and enforces safety under AI-driven changes

Production-Ready Safeguards

  • Timeout protection for modifications (default: 600s)
  • Automatic validation before every execution cycle
  • Device assignment verification
  • Cycle detection on every edit
  • Comprehensive error handling and logging

Performance Characteristics

Metric Description Implementation
Latency Time from task ready to execution start Minimized via event-driven dispatch
Throughput Tasks completed per unit time Maximized via async parallelism
Overhead Orchestration cost per task Reduced via batched editing
Scalability Performance with increasing tasks/devices Linear with async coordination

Getting Started

Basic Usage

python
from galaxy.constellation import TaskConstellationOrchestrator
from galaxy.client.device_manager import ConstellationDeviceManager

# Create orchestrator
device_manager = ConstellationDeviceManager()
orchestrator = TaskConstellationOrchestrator(device_manager)

# Orchestrate constellation
results = await orchestrator.orchestrate_constellation(
    constellation=my_constellation,
    assignment_strategy="capability_match"
)

With Modification Synchronizer

python
from galaxy.session.observers.constellation_sync_observer import (
    ConstellationModificationSynchronizer
)

# Create synchronizer
synchronizer = ConstellationModificationSynchronizer(orchestrator)
orchestrator.set_modification_synchronizer(synchronizer)

# Subscribe to events
event_bus.subscribe(synchronizer)

# Now orchestrator will wait for LLM edits to complete

Further Reading


!!!tip "Next Steps"
To understand how events drive orchestration, continue to Event-Driven Coordination.


Documents Docs Galaxy Observer Overview (`documents/docs/galaxy/observer/overview.md`)

Observer System — Overview

The Observer System in UFO Galaxy implements an event-driven architecture that enables real-time monitoring, visualization, and coordination of constellation execution. It provides a decoupled, extensible mechanism for components to react to system events without tight coupling.

The system implements the classic Observer Pattern (also known as Publish-Subscribe), enabling loose coupling between event producers and consumers. This allows the system to be extended with new observers without modifying existing code.


🎯 Purpose and Design Goals

The observer system serves several critical functions in the Galaxy framework:

  1. Real-time Monitoring — Track task execution, constellation lifecycle, and system events
  2. Visualization — Provide live updates for DAG topology and execution progress
  3. Metrics Collection — Gather performance statistics and execution data
  4. Synchronization — Coordinate between agent modifications and orchestrator execution
  5. Agent Output Handling — Display agent responses and actions in real-time

🏗️ Architecture Overview

The observer system consists of three main layers:

mermaid
graph TB
    subgraph "Event Publishers"
        A1[Orchestrator]
        A2[Agent]
        A3[Device Manager]
    end
    
    subgraph "Event Bus Layer"
        B[EventBusSingleton]
    end
    
    subgraph "Observer Layer"
        C1[ConstellationProgressObserver]
        C2[SessionMetricsObserver]
        C3[DAGVisualizationObserver]
        C4[ConstellationModificationSynchronizer]
        C5[AgentOutputObserver]
    end
    
    subgraph "Handler Layer"
        D1[TaskVisualizationHandler]
        D2[ConstellationVisualizationHandler]
    end
    
    A1 -->|publish events| B
    A2 -->|publish events| B
    A3 -->|publish events| B
    
    B -->|notify| C1
    B -->|notify| C2
    B -->|notify| C3
    B -->|notify| C4
    B -->|notify| C5
    
    C3 -->|delegate| D1
    C3 -->|delegate| D2
    
    style B fill:#4a90e2,stroke:#333,stroke-width:3px,color:#fff
    style C1 fill:#66bb6a,stroke:#333,stroke-width:2px
    style C2 fill:#66bb6a,stroke:#333,stroke-width:2px
    style C3 fill:#66bb6a,stroke:#333,stroke-width:2px
    style C4 fill:#ffa726,stroke:#333,stroke-width:2px
    style C5 fill:#66bb6a,stroke:#333,stroke-width:2px

Architecture Layers:

Layer Component Responsibility
Event Publishers Orchestrator, Agent, Device Manager Generate events during system operation
Event Bus EventBus singleton Central message broker, manages subscriptions and routing
Observers 5 specialized observers React to specific event types and perform actions
Handlers Task & Constellation handlers Delegate visualization logic for specific components

📊 Core Components

Event System Core

The foundation of the observer system consists of:

Component Location Description
EventBus galaxy/core/events.py Central message broker managing subscriptions
EventType galaxy/core/events.py Enumeration of all system event types
Event Classes galaxy/core/events.py Base (Event) and specialized (TaskEvent, ConstellationEvent, AgentEvent, DeviceEvent) event data structures
Interfaces galaxy/core/events.py IEventObserver, IEventPublisher contracts

For detailed documentation of the event system core components, see the Event System Core documentation.

Observer Implementations

Five specialized observers handle different aspects of system monitoring:

Observer File Location Primary Role Key Features
ConstellationProgressObserver galaxy/session/observers/base_observer.py Task progress tracking Queues completion events for agent, coordinates task lifecycle
SessionMetricsObserver galaxy/session/observers/base_observer.py Performance metrics Collects timing, success rates, modification statistics
DAGVisualizationObserver galaxy/session/observers/dag_visualization_observer.py Real-time visualization Displays constellation topology and execution flow
ConstellationModificationSynchronizer galaxy/session/observers/constellation_sync_observer.py Modification coordination Prevents race conditions between agent and orchestrator
AgentOutputObserver galaxy/session/observers/agent_output_observer.py Agent interaction display Shows agent responses and actions in real-time

🔄 Event Flow

The following diagram illustrates how events flow through the system:

mermaid
sequenceDiagram
    participant O as Orchestrator
    participant EB as EventBus
    participant CPO as ProgressObserver
    participant SMO as MetricsObserver
    participant DVO as VisualizationObserver
    participant A as Agent
    
    O->>EB: publish(TASK_STARTED)
    EB->>CPO: on_event(event)
    EB->>SMO: on_event(event)
    EB->>DVO: on_event(event)
    
    Note over DVO: Display task start
    Note over SMO: Increment task count
    
    O->>EB: publish(TASK_COMPLETED)
    EB->>CPO: on_event(event)
    EB->>SMO: on_event(event)
    EB->>DVO: on_event(event)
    
    CPO->>A: add_task_completion_event()
    Note over A: Process result,modify constellation
    
    A->>EB: publish(CONSTELLATION_MODIFIED)
    EB->>SMO: on_event(event)
    EB->>DVO: on_event(event)
    
    Note over DVO: Display updated DAG
    Note over SMO: Track modification

The event flow demonstrates how a single action (task completion) triggers multiple observers, each performing their specialized function without interfering with others.


📋 Event Types

The system defines the following event types:

Task Events

Track individual task execution lifecycle:

Event Type Trigger Data Includes
TASK_STARTED Task begins execution task_id, status, constellation_id
TASK_COMPLETED Task finishes successfully task_id, result, execution_time, newly_ready_tasks
TASK_FAILED Task encounters error task_id, error, retry_info

Constellation Events

Monitor constellation-level operations:

Event Type Trigger Data Includes
CONSTELLATION_STARTED Constellation begins processing constellation, initial_statistics, processing_time
CONSTELLATION_COMPLETED All tasks finished constellation, final_statistics, execution_time
CONSTELLATION_FAILED Constellation encounters error constellation, error
CONSTELLATION_MODIFIED Structure changed by agent old_constellation, new_constellation, on_task_id, modification_type, changes

Agent Events

Display agent interactions:

Event Type Trigger Data Includes
AGENT_RESPONSE Agent generates response agent_name, agent_type, response_data
AGENT_ACTION Agent executes action agent_name, action_type, actions

Device Events

Monitor device status (used by client):

Event Type Trigger Data Includes
DEVICE_CONNECTED Device joins pool device_id, device_status, device_info
DEVICE_DISCONNECTED Device leaves pool device_id, device_status
DEVICE_STATUS_CHANGED Device state changes device_id, device_status, all_devices

🚀 Usage Example

Here's a complete example showing how observers are initialized and used in a Galaxy session:

text
/* Detailed source-code truncated for AI context efficiency. */

🔑 Key Benefits

1. Decoupling

Events decouple components — publishers don't need to know about observers:

  • Orchestrator publishes task events without knowing who's listening
  • Agent publishes modification events without coordinating with orchestrator
  • New observers can be added without changing existing code

2. Extensibility

Add custom observers for new functionality:

python
from galaxy.core.events import IEventObserver, Event, EventType

class CustomMetricsObserver(IEventObserver):
    """Custom observer for domain-specific metrics."""
    
    def __init__(self):
        self.custom_metrics = {}
    
    async def on_event(self, event: Event) -> None:
        if event.event_type == EventType.TASK_COMPLETED:
            # Collect custom metrics
            task_type = event.data.get("task_type")
            if task_type not in self.custom_metrics:
                self.custom_metrics[task_type] = []
            
            self.custom_metrics[task_type].append({
                "duration": event.data.get("execution_time"),
                "result": event.result
            })

# Subscribe to specific events
event_bus = get_event_bus()
custom_observer = CustomMetricsObserver()
event_bus.subscribe(custom_observer, {EventType.TASK_COMPLETED})

3. Concurrent Execution

All observers are notified concurrently using asyncio.gather():

  • No observer blocks another
  • Exceptions in one observer don't affect others
  • Efficient parallel processing

4. Type-Safe Event Handling

Specialized event classes provide type safety:

python
async def on_event(self, event: Event) -> None:
    if isinstance(event, TaskEvent):
        # TaskEvent-specific handling
        task_id = event.task_id  # Type-safe access
        status = event.status
        
    elif isinstance(event, ConstellationEvent):
        # ConstellationEvent-specific handling
        constellation_id = event.constellation_id
        state = event.constellation_state

📚 Component Documentation

Explore detailed documentation for each observer:

!!! note "Additional Observers"
Documentation for ConstellationProgressObserver, DAGVisualizationObserver, ConstellationModificationSynchronizer, and AgentOutputObserver is available in their source code files. These observers handle task progress tracking, real-time visualization, modification synchronization, and agent output display respectively.



💡 Best Practices

Observer Lifecycle Management

Properly manage observer subscriptions to prevent memory leaks:

python
# Subscribe observers
observers = [progress_observer, metrics_observer, viz_observer]
for observer in observers:
    event_bus.subscribe(observer)

try:
    # Execute constellation
    await orchestrator.execute_constellation(constellation)
finally:
    # Clean up observers
    for observer in observers:
        event_bus.unsubscribe(observer)

Event-Specific Subscription

Subscribe only to relevant events for efficiency:

python
# Instead of subscribing to all events
event_bus.subscribe(observer)  # Receives ALL events

# Subscribe to specific event types
event_bus.subscribe(observer, {
    EventType.TASK_COMPLETED,
    EventType.TASK_FAILED,
    EventType.CONSTELLATION_MODIFIED
})

Error Handling in Observers

Always handle exceptions gracefully:

python
async def on_event(self, event: Event) -> None:
    try:
        # Process event
        await self._handle_event(event)
    except Exception as e:
        self.logger.error(f"Error processing event: {e}")
        # Don't re-raise - let other observers continue

🎓 Summary

The Observer System provides a robust, event-driven foundation for monitoring and coordinating Galaxy's constellation execution:

  • Event Bus acts as central message broker
  • 5 specialized observers handle different aspects of monitoring
  • Loose coupling enables extensibility and maintainability
  • Concurrent execution ensures efficient event processing
  • Type-safe events provide clear contracts and error prevention

For implementation details of specific observers, refer to the individual component documentation pages linked above.


Documents Docs Infrastructure Agents Overview (`documents/docs/infrastructure/agents/overview.md`)

Device Agent Architecture

Device Agents are the execution engines of UFO3's multi-device orchestration system. Each device agent operates as an autonomous, intelligent controller that translates high-level user intentions into low-level system commands. The architecture is designed for extensibility, safety, and scalability across heterogeneous computing environments.

Overview

UFO3 orchestrates tasks across multiple devices through a network of Device Agents. Originally designed as a Windows automation framework (UFO2), the architecture has evolved to support diverse platforms including Linux, macOS, and embedded systems. This document describes the abstract design principles and interfaces that enable this multi-platform capability.

Key Capabilities:

  • Multi-Platform: Windows agents (HostAgent, AppAgent), Linux agent, extensible to macOS and embedded systems
  • Safe Execution: Server-client separation isolates reasoning from system-level operations
  • Scalable Architecture: Hierarchical agent coordination supports complex cross-device workflows
  • LLM-Driven Reasoning: Dynamic decision-making using large language models
  • Modular Design: Three-layer architecture (State, Strategy, Command) enables customization

Three-Layer Architecture

Device agents implement a three-layer framework that separates concerns, promotes modularity, and enables extensibility:

mermaid
graph TB
    subgraph "Device Agent Architecture"
        subgraph "Level-1: State Layer (FSM)"
            S1[AgentState]
            S2[State Machine]
            S3[State Transitions]
            S1 --> S2 --> S3
        end
        
        subgraph "Level-2: Strategy Layer (Execution Logic)"
            P1[ProcessorTemplateStrategy Orchestrator]
            P2[DATA_COLLECTIONStrategies]
            P3[LLM_INTERACTIONStrategies]
            P4[ACTION_EXECUTIONStrategies]
            P5[MEMORY_UPDATEStrategies]
            P1 -->|manages & executes| P2
            P2 --> P3 --> P4 --> P5
        end
        
        subgraph "Level-3: Command Layer (System Interface)"
            C1[CommandDispatcher]
            C2[MCP Tools]
            C3[Atomic Commands]
            C1 --> C2 --> C3
        end
        
        S3 -->|delegates to| P1
        P5 -->|executes via| C1
    end
    
    LLM[Large Language Model]
    P3 -.->|reasoning| LLM
    LLM -.->|decisions| P4

Layer Responsibilities

Layer Level Responsibility Key Components Extensibility
State Level-1 Finite State Machine governing agent lifecycle AgentState, AgentStateManager, AgentStatus Register new states via @AgentStateManager.register
Strategy Level-2 Execution logic layer: processor manages sequence of modular strategies ProcessorTemplate, ProcessingStrategy, ProcessingPhase, Middleware Compose custom strategies via ComposedStrategy, add middleware
Command Level-3 Atomic system operations mapped to MCP tools BasicCommandDispatcher, Command, MCP integration Add new tools via client-side MCP server registration

Design Rationale:

The three-layer separation ensures:

  • State Layer (Level-1): Controls when and what to execute (state transitions, agent handoff)
  • Strategy Layer (Level-2): Defines how to execute (processor orchestrates modular strategies)
  • Command Layer (Level-3): Performs actual execution (deterministic system operations)

This separation allows replacing individual layers without affecting others.


Level-1: State Layer (FSM)

The State Layer implements a Finite State Machine (FSM) that governs the agent's execution lifecycle. Each state encapsulates:

  • A processor (strategy execution logic)
  • Transition rules (to next state)
  • Agent handoff logic (for multi-agent workflows)
mermaid
stateDiagram-v2
    [*] --> CONTINUE
    CONTINUE --> CONTINUE: Success
    CONTINUE --> PENDING: Wait for external event
    CONTINUE --> CONFIRM: User confirmation needed
    CONTINUE --> SCREENSHOT: Capture observation
    CONTINUE --> FINISH: Task complete
    CONTINUE --> FAIL: Error occurred
    CONTINUE --> ERROR: Critical failure
    
    PENDING --> CONTINUE: Event received
    CONFIRM --> CONTINUE: User confirmed
    CONFIRM --> FAIL: User rejected
    SCREENSHOT --> CONTINUE: Screenshot captured
    
    FINISH --> [*]
    FAIL --> [*]
    ERROR --> [*]

AgentStatus Enum

python
class AgentStatus(Enum):
    """Agent status enumeration"""
    ERROR = "ERROR"            # Critical error occurred
    FINISH = "FINISH"          # Task completed successfully
    CONTINUE = "CONTINUE"      # Normal execution
    FAIL = "FAIL"              # Task failed
    PENDING = "PENDING"        # Waiting for external event
    CONFIRM = "CONFIRM"        # Awaiting user confirmation
    SCREENSHOT = "SCREENSHOT"  # Screenshot capture needed

State Registration:

New states can be registered dynamically using the @AgentStateManager.register decorator:

python
@AgentStateManager.register
class CustomState(AgentState):
    async def handle(self, agent, context):
        # Custom state logic
        pass
    
    def next_state(self, agent):
        return AgentStateManager.get_state("CONTINUE")

See State Layer Documentation for complete details.


Level-2: Strategy Layer (Execution Logic)

The Strategy Layer implements the execution logic within each state. Each state encapsulates a processor that manages a sequence of strategies to implement step-level workflow. This layer consists of two key components:

Processor: Strategy Orchestrator

The ProcessorTemplate orchestrates the execution of strategies:

  • Registers Strategies: Configures which strategies execute in each phase
  • Manages Middleware: Wraps strategy execution with logging, metrics, error handling
  • Validates Dependencies: Ensures strategies have required data before execution
  • Controls Execution: Sequences strategies through fixed workflow phases
mermaid
graph TB
    State[AgentState] -->|encapsulates| Processor[ProcessorTemplateStrategy Orchestrator]
    
    Processor -->|1. Register| Strategies[ProcessingStrategies]
    Processor -->|2. Wrap| Middleware[Middleware Chain]
    Processor -->|3. Validate| Dependencies[Strategy Dependencies]
    Processor -->|4. Execute| Workflow[Workflow Phases]
    
    Workflow --> DC[DATA_COLLECTION]
    Workflow --> LLM[LLM_INTERACTION]
    Workflow --> AE[ACTION_EXECUTION]
    Workflow --> MU[MEMORY_UPDATE]
    
    DC & LLM & AE & MU -.->|implements| Strategies

Processor and Strategy Relationship:

  • Processor: Framework that manages the sequence of strategies
  • Strategy: Modular, reusable execution units

Together they form Level-2: Strategy Layer, which handles:

  • Data collection and environment inspection
  • Prompt construction and LLM reasoning
  • Action planning and tool invocation
  • Memory updates and context synchronization

Strategy: Modular Execution Units

ProcessingStrategies are modular execution units with a unified execute() interface:

mermaid
graph LR
    A[DATA_COLLECTION] --> B[LLM_INTERACTION]
    B --> C[ACTION_EXECUTION]
    C --> D[MEMORY_UPDATE]
    
    A1[ScreenshotsUI InfoSystem Status] --> A
    B1[Prompt ConstructionLLM CallResponse Parsing] --> B
    C1[Command DispatchMCP ExecutionResult Handling] --> C
    D1[Memory ItemsBlackboard UpdateContext Sync] --> D

Four Core Strategy Types

Strategy Type ProcessingPhase Purpose Examples
DATA_COLLECTION data_collection Gather contextual information Screenshot capture, UI tree extraction, system info
LLM_INTERACTION llm_interaction Construct prompts, interact with LLM, parse responses Prompt building, LLM reasoning, JSON parsing
ACTION_EXECUTION action_execution Execute commands from LLM/toolkits Click, type, scroll, API calls
MEMORY_UPDATE memory_update Update short-term/long-term memory Add memory items, update blackboard, sync context

Strategy Layer Configuration Example:

Each state configures its processor with strategies and middleware:

python
class AppAgentProcessor(ProcessorTemplate):
    def _setup_strategies(self):
        # Register strategies for each phase
        self.strategies[ProcessingPhase.DATA_COLLECTION] = ComposedStrategy([
            AppScreenshotCaptureStrategy(),
            AppControlInfoStrategy()
        ])
        self.strategies[ProcessingPhase.LLM_INTERACTION] = AppLLMInteractionStrategy()
        self.strategies[ProcessingPhase.ACTION_EXECUTION] = AppActionExecutionStrategy()
        self.strategies[ProcessingPhase.MEMORY_UPDATE] = AppMemoryUpdateStrategy()
    
    def _setup_middleware(self):
        # Add middleware for logging, metrics, error handling
        self.middleware_chain = [
            LoggingMiddleware(),
            PerformanceMetricsMiddleware(),
            ErrorHandlingMiddleware()
        ]

See Processor Documentation and Strategy Documentation for complete details.


Level-3: Command Layer (System Interface)

The Command Layer provides atomic, deterministic system operations. Each command maps to an MCP tool that executes on the device client.

mermaid
sequenceDiagram
    participant Agent as Device Agent (Server)
    participant Dispatcher as CommandDispatcher
    participant Protocol as AIP Protocol
    participant Client as Device Client
    participant MCP as MCP Tool

    Agent->>Dispatcher: execute_commands([command1, command2])
    Dispatcher->>Protocol: Send ServerMessage (COMMAND)
    Protocol->>Client: WebSocket (AIP)
    Client->>MCP: Route to MCP server
    MCP->>MCP: Execute tool function
    MCP->>Client: Return result
    Client->>Protocol: Send ClientMessage (RESULT)
    Protocol->>Dispatcher: Receive results
    Dispatcher->>Agent: Return List[Result]

Command Structure

python
@dataclass
class Command:
    """Atomic command to be executed on device client"""
    tool_name: str                   # MCP tool name (e.g., "click_element")
    parameters: Dict[str, Any]       # Tool arguments
    tool_type: str                   # "data_collection" or "action"
    call_id: str                     # Unique identifier

!!! warning "Deterministic Execution"
Commands are designed to be:

text
- **Atomic**: Single, indivisible operation
- **Deterministic**: Same inputs → same outputs
- **Auditable**: Full command history logged
- **Reversible**: Where possible, support undo operations

Extensibility:

New commands can be added by:

  1. Registering MCP tool on device client
  2. LLM dynamically selects tool from available MCP registry
  3. No server-side code changes required

See Command Layer Documentation for complete details.


Server-Client Architecture

Device agents use a server-client separation to balance safety, scalability, and functionality:

mermaid
graph TB
    subgraph "Server Side (UFO3 Orchestrator)"
        Server[Device Agent Server]
        State[State Machine]
        Processor[Strategy Processor]
        LLM[LLM Service]
        Memory[Memory & Context]
        
        Server --> State
        Server --> Processor
        Server --> Memory
        Processor -.-> LLM
    end
    
    subgraph "Communication Layer"
        AIP[AIP ProtocolWebSocket]
    end
    
    subgraph "Client Side (Device)"
        Client[Device Client]
        Dispatcher[Command Dispatcher]
        MCP[MCP Server Manager]
        Tools[MCP Tools]
        OS[Operating System]
        
        Client --> Dispatcher
        Dispatcher --> MCP
        MCP --> Tools
        Tools --> OS
    end
    
    Server <-->|Commands/Results| AIP
    AIP <-->|Commands/Results| Client

Separation of Concerns

Component Location Responsibilities Security Boundary
Agent Server Orchestrator State management, reasoning, planning, memory Untrusted (LLM-driven decisions)
Device Client Device Command execution, MCP tool calls, resource access Trusted (validated operations)
AIP Protocol Communication Message serialization, WebSocket transport, error handling Secure channel (authentication, encryption)

Why Server-Client Separation?

Safety: Isolates potentially unsafe LLM-generated decisions from direct system access. Clients validate all commands before execution.

Scalability: Single orchestrator server manages multiple device clients. Reduces per-device resource requirements.

Flexibility: Device clients can run on resource-constrained devices (embedded systems, mobile) while heavy reasoning occurs on server.

See Server-Client Architecture for complete details.


Supported Device Platforms

UFO3 currently supports Windows and Linux device agents, with architecture designed for extensibility to other platforms.

Windows Agents

mermaid
graph TB
    subgraph "Windows Device (Two-Tier Hierarchy)"
        Host[HostAgentApplication Selection]
        App1[AppAgentWord]
        App2[AppAgentExcel]
        App3[AppAgentBrowser]
        
        Host -->|delegates| App1
        Host -->|delegates| App2
        Host -->|delegates| App3
    end
    
    User[User Request] --> Host

HostAgent (Application-Level Coordinator):

  • Selects appropriate application(s) for user request
  • Decomposes tasks into application-specific subtasks
  • Coordinates multiple AppAgents
  • Manages application switching and data transfer

AppAgent (Application-Level Executor):

  • Controls specific Windows application (Word, Excel, browser, etc.)
  • Uses UI Automation for control element discovery
  • Executes application-specific actions (type, click, scroll)
  • Maintains application context and memory

!!! example "Windows Agent Example"
User Request: "Create a chart from sales.xlsx and insert into report.docx"

text
1. **HostAgent** decomposes: 
    - Open Excel → Create chart → Copy chart
    - Open Word → Paste chart
2. **AppAgent (Excel)**: Opens `sales.xlsx`, creates chart, copies to clipboard
3. **AppAgent (Word)**: Opens `report.docx`, pastes chart at cursor

Linux Agent

mermaid
graph TB
    subgraph "Linux Device (Single-Tier Architecture)"
        Linux[LinuxAgentDirect System Control]
        Shell[Shell Commands]
        Files[File Operations]
        Apps[Application Launch]
        
        Linux --> Shell
        Linux --> Files
        Linux --> Apps
    end
    
    User[User Request] --> Linux

LinuxAgent (System-Level Executor):

  • Direct shell command execution
  • File system operations
  • Application launch and management
  • Single-tier architecture (no application-level hierarchy)

!!! info "Architecture Difference"
Windows uses two-tier hierarchy (HostAgent → AppAgent) due to:

text
- UI Automation framework's application-centric model
- Distinct application contexts requiring specialized agents

**Linux** uses single-tier architecture because:

- Shell provides unified interface to all system operations
- Application control occurs through same command-line interface

Platform Comparison

Feature Windows (UFO2) Linux macOS (Future) Embedded (Future)
Agent Hierarchy Two-tier (Host → App) Single-tier TBD Single-tier
UI Control UI Automation X11/Wayland Accessibility API Platform-specific
Command Interface MCP tools (Win32 API) MCP tools (Shell) MCP tools (AppleScript) MCP tools (Custom)
Observation Screenshot + UI tree Screenshot + Shell output Screenshot + UI tree Sensor data
State Management Shared FSM Shared FSM Shared FSM Shared FSM
Strategy Layer Processor framework Processor framework Processor framework Processor framework
Current Status ✅ Production ✅ Production 🔜 Planned 🔜 Planned

Extensibility Path:

Adding a new platform requires:

  1. Implement Agent Class: Extend BasicAgent (inherit State layer, Processor framework)
  2. Create Processor: Subclass ProcessorTemplate, implement platform-specific strategies
  3. Define MCP Tools: Register platform-specific MCP tools on device client
  4. Register Agent: Use @AgentRegistry.register decorator

No changes to core State layer, Processor framework, or AIP protocol required.

See Agent Types Documentation for complete implementation details.


Agent Lifecycle

A typical device agent execution follows this lifecycle:

mermaid
sequenceDiagram
    participant User
    participant Orchestrator
    participant Agent
    participant State
    participant Processor
    participant LLM
    participant Dispatcher
    participant Client

    User->>Orchestrator: Submit task
    Orchestrator->>Agent: Initialize agent (CONTINUE state)
    
    loop Until FINISH/FAIL/ERROR
        Agent->>State: handle(agent, context)
        State->>Processor: execute strategies
        
        Processor->>Processor: DATA_COLLECTION
        Note over Processor: Screenshot, UI info
        
        Processor->>LLM: LLM_INTERACTION
        LLM-->>Processor: Action decision
        
        Processor->>Dispatcher: ACTION_EXECUTION
        Dispatcher->>Client: Execute commands
        Client-->>Dispatcher: Results
        Dispatcher-->>Processor: Results
        
        Processor->>Processor: MEMORY_UPDATE
        Note over Processor: Update memory, blackboard
        
        State->>State: next_state(agent)
        State->>Agent: Update agent status
    end
    
    Agent->>Orchestrator: Task complete/failed
    Orchestrator->>User: Return result

Execution Phases

  1. Initialization: Agent created with default state (CONTINUE), processor, memory
  2. State Handling: Current state's handle() method invoked with agent and context
  3. Strategy Execution: Processor runs strategies in sequence (DATA_COLLECTION → LLM_INTERACTION → ACTION_EXECUTION → MEMORY_UPDATE)
  4. State Transition: State's next_state() determines next FSM state
  5. Repeat/Terminate: Loop continues until terminal state (FINISH, FAIL, ERROR)

!!! tip "Multi-Agent Handoff"
For multi-agent scenarios (e.g., Windows HostAgent → AppAgent), states implement next_agent():

text
```python
def next_agent(self, agent: BasicAgent) -> BasicAgent:
    # HostAgent delegates to AppAgent
    if agent.status == "DELEGATE_TO_APP":
        return agent.create_app_agent(...)
    return agent
```

Memory and Context Management

Device agents maintain two types of memory:

Short-Term Memory (Agent Memory)

Purpose: Track agent's execution history within a session

Implementation: Memory class with MemoryItem entries

python
class Memory:
    """Agent's short-term memory"""
    _content: List[MemoryItem]
    
    def add_memory_item(self, memory_item: MemoryItem):
        """Add new memory entry"""
        self._content.append(memory_item)

Content: Actions taken, observations made, results received

Lifetime: Single session (cleared between tasks)

Long-Term Memory (Blackboard)

Purpose: Share information across agents and sessions

Implementation: Blackboard class with multiple memory types

python
class Blackboard:
    """Multi-agent shared memory"""
    _questions: Memory      # Q&A history
    _requests: Memory       # Request history
    _trajectories: Memory   # Action trajectories
    _screenshots: Memory    # Visual observations

Content: Common knowledge, successful action patterns, user preferences

Lifetime: Persistent across sessions (can be saved/loaded)

Blackboard Usage Example:

Scenario: HostAgent delegates to AppAgent (Excel)

  1. HostAgent adds to blackboard:
    • Request: "Create sales chart"
    • Context: Previous analysis results
  2. AppAgent reads from blackboard:
    • Retrieves request and context
    • Adds action trajectories as executed
    • Adds screenshot after chart creation
  3. HostAgent reads updated blackboard:
    • Verifies chart creation
    • Continues to next step (insert to Word)

See Memory System Documentation for complete details.


Integration with UFO3 Components

Device agents integrate with other UFO3 components:

mermaid
graph TB
    subgraph "UFO3 Architecture"
        Session[Session/Round Manager]
        Context[Global Context]
        Agent[Device Agent]
        Dispatcher[Command Dispatcher]
        AIP[AIP Protocol]
        Client[Device Client]
        MCP[MCP Servers]
    end
    
    Session -->|manages lifecycle| Agent
    Session -->|provides| Context
    Agent -->|reads/writes| Context
    Agent -->|sends commands| Dispatcher
    Dispatcher -->|uses| AIP
    AIP <-->|WebSocket| Client
    Client -->|calls| MCP

Integration Points

Component Relationship Description
Session Manager Parent Creates agents, manages agent lifecycle, coordinates multi-agent workflows
Round Manager Sibling Manages round-based execution, tracks round state, synchronizes with agent steps
Global Context Shared State Agent reads request/config, writes results/status, shares data across components
Command Dispatcher Execution Interface Agent sends commands, dispatcher routes to client, returns results
AIP Protocol Communication Serializes commands/results, manages WebSocket, handles errors/timeouts
Device Client Executor Receives commands, invokes MCP tools, returns results
MCP Servers Tool Registry Provides available tools, executes tool functions, returns structured results

See Session Documentation, Context Documentation, and AIP Protocol for integration details.


Design Patterns

Device agent architecture leverages several design patterns:

1. State Pattern (FSM Layer)

Purpose: Encapsulate state-specific behavior, enable dynamic state transitions

Implementation: AgentState abstract class, concrete state classes

python
class AgentState(ABC):
    @abstractmethod
    async def handle(self, agent, context):
        """Execute state-specific logic"""
        pass
    
    @abstractmethod
    def next_state(self, agent):
        """Determine next state"""
        pass

2. Strategy Pattern (Strategy Layer)

Purpose: Define family of algorithms (strategies), make them interchangeable

Implementation: ProcessingStrategy protocol, concrete strategy classes

python
class ProcessingStrategy(Protocol):
    async def execute(self, agent, context) -> ProcessingResult:
        """Execute strategy logic"""
        pass

3. Template Method Pattern (Processor Framework)

Purpose: Define skeleton of algorithm, let subclasses override specific steps

Implementation: ProcessorTemplate abstract class

python
class ProcessorTemplate(ABC):
    @abstractmethod
    def _setup_strategies(self):
        """Subclass defines which strategies to use"""
        pass
    
    async def process(self, agent, context):
        """Template method - runs strategies in sequence"""
        for phase, strategy in self.strategies.items():
            result = await strategy.execute(agent, context)
            # Handle result, update context

4. Singleton Pattern (State Manager)

Purpose: Ensure single instance of state registry

Implementation: AgentStateManager with metaclass

python
class AgentStateManager(ABC, metaclass=SingletonABCMeta):
    _state_mapping: Dict[str, Type[AgentState]] = {}
    
    def get_state(self, status: str) -> AgentState:
        """Lazy load and return state instance"""
        pass

5. Registry Pattern (Agent Registration)

Purpose: Register agent types, enable dynamic agent creation

Implementation: AgentRegistry decorator

python
@AgentRegistry.register(agent_name="appagent", processor_cls=AppAgentProcessor)
class AppAgent(BasicAgent):
    pass

6. Blackboard Pattern (Multi-Agent Coordination)

Purpose: Share data across multiple agents

Implementation: Blackboard class

python
class Blackboard:
    _questions: Memory
    _requests: Memory
    _trajectories: Memory
    _screenshots: Memory

Best Practices

State Design

  • Keep states focused: Each state should have single, clear responsibility
  • Use rule-based transitions for deterministic flows, LLM-driven transitions for adaptive behavior
  • Implement error states for graceful degradation
  • Document state invariants and transition conditions

Strategy Design

  • Keep strategies atomic: Each strategy should perform one cohesive task
  • Declare dependencies explicitly using get_dependencies()
  • Use ComposedStrategy to combine multiple strategies within a phase
  • Implement fail-fast for critical errors, continue-on-error for optional operations

Command Design

  • Keep commands atomic: Single, indivisible operation
  • Design commands to be idempotent where possible
  • Validate arguments on client side before execution
  • Return structured results with success/failure status

Memory Management

  • Use short-term memory for agent-specific execution history
  • Use blackboard for multi-agent coordination and persistent knowledge
  • Clear memory between sessions to avoid context pollution
  • Implement memory pruning for long-running sessions

!!! warning "Security Considerations"
- Validate all commands on client side before execution
- Sanitize LLM outputs before converting to commands
- Limit command scope via MCP tool permissions
- Audit all actions for compliance and debugging
- Isolate agents to prevent unauthorized cross-agent access


Deep Dive Into Layers:

Supporting Systems:

Integration Points:


Summary

Key Takeaways:

✅ Three-Layer Architecture: State (FSM) → Strategy (Execution Logic) → Command (System Interface)

✅ Server-Client Separation: Safe isolation of reasoning (server) from execution (client)

✅ Multi-Platform Support: Windows (two-tier), Linux (single-tier), extensible to macOS and embedded

✅ LLM-Driven Reasoning: Dynamic decision-making with structured command output

✅ Modular & Extensible: Register new states, compose strategies, add MCP tools without core changes

✅ Memory Systems: Short-term (agent memory) and long-term (blackboard) for coordination

✅ Design Patterns: State, Strategy, Template Method, Singleton, Registry, Blackboard

The Device Agent architecture provides a robust, extensible foundation for multi-device automation. By separating concerns across three layers and isolating reasoning from execution, UFO3 achieves both safety and flexibility for orchestrating complex cross-device workflows.


Reference

Below is the reference for the BasicAgent class. All device agents inherit from BasicAgent and implement platform-specific processors and states:

::: agents.agent.basic.BasicAgent


Documents Docs Infrastructure Modules Overview (`documents/docs/infrastructure/modules/overview.md`)

Module System Overview

The Module System is the core execution engine of UFO, orchestrating the complete lifecycle of user interactions from initial request to final completion. It manages sessions, rounds, context state, and command dispatch across both Windows and Linux platforms.

Quick Navigation:


Architecture Overview

The module system implements a hierarchical execution model with clear separation of concerns:

mermaid
graph TB
    subgraph "User Interaction Layer"
        UI[InteractorUser I/O]
    end
    
    subgraph "Session Management Layer"
        SF[SessionFactoryCreates sessions]
        SP[SessionPoolManages multiple sessions]
        S[SessionConversation lifecycle]
    end
    
    subgraph "Execution Layer"
        R[RoundSingle request handler]
        C[ContextShared state]
    end
    
    subgraph "Command Layer"
        D[DispatcherCommand routing]
        LCD[LocalCommandDispatcher]
        WSD[WebSocketCommandDispatcher]
    end
    
    subgraph "Platform Layer"
        WS[WindowsBaseSession]
        LS[LinuxBaseSession]
        SS[ServiceSession]
    end
    
    UI -.Request.-> SF
    SF --> SP
    SP --> S
    S --> R
    R --> C
    R --> D
    D --> LCD
    D --> WSD
    
    S -.inherits.-> WS
    S -.inherits.-> LS
    S -.inherits.-> SS
    
    style UI fill:#e1f5ff
    style SF fill:#fff4e1
    style SP fill:#f0ffe1
    style S fill:#ffe1f5
    style R fill:#e1ffe1
    style C fill:#ffe1e1
    style D fill:#f5e1ff

Core Components

1. Session Management

A Session represents a complete conversation between the user and UFO, potentially spanning multiple requests and rounds.

Session Hierarchy:

mermaid
classDiagram
    class BaseSession {
        <<abstract>>
        +task: str
        +context: Context
        +rounds: Dict[int, BaseRound]
        +run()
        +create_new_round()
        +is_finished()
    }
    
    class WindowsBaseSession {
        +host_agent: HostAgent
        +_init_agents()
    }
    
    class LinuxBaseSession {
        +agent: LinuxAgent
        +_init_agents()
    }
    
    class Session {
        +mode: str
        +next_request()
    }
    
    class ServiceSession {
        +task_protocol: TaskExecutionProtocol
        +_init_context()
    }
    
    class LinuxSession {
        +next_request()
    }
    
    class FollowerSession {
        +plan_reader: PlanReader
    }
    
    BaseSession <|-- WindowsBaseSession
    BaseSession <|-- LinuxBaseSession
    WindowsBaseSession <|-- Session
    WindowsBaseSession <|-- ServiceSession
    LinuxBaseSession <|-- LinuxSession
    Session <|-- FollowerSession

Session Types:

Session Type Platform Use Case Communication
Session Windows Interactive mode Local
ServiceSession Windows Server-controlled WebSocket (AIP)
LinuxSession Linux Interactive mode Local
LinuxServiceSession Linux Server-controlled WebSocket (AIP)
FollowerSession Windows Plan execution Local
FromFileSession Windows Batch processing Local
OpenAIOperatorSession Windows Operator mode Local

!!!example "Session Creation"
```python
from ufo.module.session_pool import SessionFactory

text
# Create interactive Windows session
factory = SessionFactory()
sessions = factory.create_session(
    task="email_task",
    mode="normal",
    plan="",
    request="Open Outlook and send an email"
)

# Create Linux service session
linux_session = factory.create_service_session(
    task="data_task",
    should_evaluate=True,
    id="session_001",
    request="Process CSV files",
    platform_override="linux"
)
```

2. Round Execution

A Round handles a single user request by orchestrating agents through a state machine, executing actions until completion.

Round Lifecycle:

mermaid
stateDiagram-v2
    [*] --> Created: Initialize Round
    Created --> AgentHandle: agent.handle(context)
    AgentHandle --> StateTransition: Determine next state
    StateTransition --> AgentSwitch: Switch agent if needed
    AgentSwitch --> SubtaskCheck: Check if subtask ends
    
    SubtaskCheck --> CaptureSnapshot: Subtask complete
    SubtaskCheck --> AgentHandle: Continue
    
    CaptureSnapshot --> AgentHandle: Next subtask
    
    AgentHandle --> RoundComplete: is_finished() = True
    RoundComplete --> Evaluation: should_evaluate = True
    RoundComplete --> [*]: should_evaluate = False
    Evaluation --> [*]
    
    note right of AgentHandle
        Agent processes current state
        Updates context
        Executes actions
    end note
    
    note right of StateTransition
        State pattern determines:
        - Next state
        - Next agent
        - Round completion
    end note

Key Round Operations:

Operation Purpose Trigger
agent.handle(context) Process current state Each iteration
state.next_state(agent) Determine next state After handle
state.next_agent(agent) Switch agent if needed After state transition
capture_last_snapshot() Save UI state Subtask/Round end
evaluation() Assess completion Round end (if enabled)

!!!warning "Round Termination Conditions"
A round finishes when:
- state.is_round_end() returns True
- Session step exceeds ufo_config.system.max_step
- Agent enters ERROR state


3. Context State Management

Context is a type-safe key-value store that maintains state across all rounds in a session.

Context Architecture:

mermaid
graph LR
    subgraph "Context Storage"
        CN[ContextNames Enum]
        CV[Context Values Dict]
    end
    
    subgraph "Tracked Data"
        ID[Session/Round IDs]
        ST[Steps & Costs]
        LOG[Loggers]
        APP[Application State]
        CMD[Command Dispatcher]
    end
    
    subgraph "Access Patterns"
        GET[context.get(key)]
        SET[context.set(key, value)]
        UPD[context.update_dict(key, dict)]
    end
    
    CN -.defines.-> CV
    CV --> ID
    CV --> ST
    CV --> LOG
    CV --> APP
    CV --> CMD
    
    GET -.reads.-> CV
    SET -.writes.-> CV
    UPD -.merges.-> CV
    
    style CN fill:#e1f5ff
    style CV fill:#fff4e1
    style GET fill:#f0ffe1
    style SET fill:#ffe1f5
    style UPD fill:#f5e1ff

Context Categories:

Category Context Names Type Purpose
Identifiers ID, CURRENT_ROUND_ID int Session/round tracking
Execution State SESSION_STEP, ROUND_STEP int/dict Progress tracking
Cost Tracking SESSION_COST, ROUND_COST float/dict LLM API costs
Requests REQUEST, SUBTASK, PREVIOUS_SUBTASKS str/list Task information
Application APPLICATION_WINDOW, APPLICATION_PROCESS_NAME UIAWrapper/str UI automation
Logging LOGGER, REQUEST_LOGGER, EVALUATION_LOGGER FileWriter Log outputs
Communication HOST_MESSAGE, CONTROL_REANNOTATION list Agent messages
Infrastructure command_dispatcher BasicCommandDispatcher Command execution

!!!example "Context Usage Patterns"
```python
from ufo.module.context import Context, ContextNames

text
# Initialize context
context = Context()

# Set values
context.set(ContextNames.REQUEST, "Open Notepad")
context.set(ContextNames.SESSION_STEP, 0)

# Get values
request = context.get(ContextNames.REQUEST)  # "Open Notepad"
step = context.get(ContextNames.SESSION_STEP)  # 0

# Update dictionaries (for round-specific tracking)
round_costs = {1: 0.05, 2: 0.03}
context.update_dict(ContextNames.ROUND_COST, round_costs)

# Auto-sync current round values
current_cost = context.current_round_cost  # Auto-synced
```

4. Command Dispatching

Dispatchers route commands to execution environments (local MCP tools or remote WebSocket clients) and handle result delivery.

Dispatcher Architecture:

mermaid
graph TB
    subgraph "Agent Layer"
        AG[Agent generates commands]
    end
    
    subgraph "Dispatcher Layer"
        BD[BasicCommandDispatcherAbstract base]
        LCD[LocalCommandDispatcherMCP tools]
        WSD[WebSocketCommandDispatcherAIP protocol]
    end
    
    subgraph "Execution Layer"
        CR[CommandRouter]
        CM[ComputerManager]
        MCP[MCP Servers]
        WS[WebSocket Client]
    end
    
    subgraph "Result Handling"
        RES[Results: List~Result~]
        ERR[Error Results]
    end
    
    AG --> BD
    BD -.implements.-> LCD
    BD -.implements.-> WSD
    
    LCD --> CR
    CR --> CM
    CM --> MCP
    
    WSD --> WS
    
    MCP --> RES
    WS --> RES
    LCD --> ERR
    WSD --> ERR
    
    style AG fill:#e1f5ff
    style BD fill:#fff4e1
    style LCD fill:#f0ffe1
    style WSD fill:#ffe1f5
    style RES fill:#e1ffe1

Dispatcher Comparison:

Dispatcher Use Case Communication Error Handling Timeout
LocalCommandDispatcher Interactive sessions Direct MCP calls Generates error Results 6000s
WebSocketCommandDispatcher Service sessions AIP protocol messages Generates error Results 6000s

!!!example "Command Dispatch Flow"
```python
from aip.messages import Command

text
# Create commands
commands = [
    Command(
        tool_name="click_element",
        parameters={"control_label": "1", "button": "left"},
        tool_type="windows"
    )
]

# Execute via dispatcher (attached to context)
results = await context.command_dispatcher.execute_commands(
    commands=commands,
    timeout=30.0
)

# Process results
for result in results:
    if result.status == ResultStatus.SUCCESS:
        print(f"Action succeeded: {result.result}")
    else:
        print(f"Action failed: {result.error}")
```

5. User Interaction

Interactor provides rich CLI experiences for user input with styled prompts, panels, and confirmations.

Interaction Flows:

mermaid
sequenceDiagram
    participant U as User
    participant I as Interactor
    participant S as Session
    participant R as Round
    
    U->>I: Start UFO
    I->>I: first_request()
    I-->>U: 🛸 Welcome Panel
    U->>I: "Open Notepad"
    I->>S: Initial request
    
    S->>R: Create Round 1
    R->>R: Execute...
    R-->>S: Round complete
    
    S->>I: new_request()
    I-->>U: 🛸 Next Request Panel
    U->>I: "Type hello"
    I->>S: Next request
    
    S->>R: Create Round 2
    R->>R: Execute...
    R-->>S: Round complete
    
    S->>I: new_request()
    I-->>U: 🛸 Next Request Panel
    U->>I: "N"
    I-->>U: 👋 Goodbye Panel
    I->>S: complete=True
    S->>S: Terminate
    
    S->>I: experience_asker()
    I-->>U: 💾 Save Experience Panel
    U->>I: Yes
    I->>S: Save experience

Interactor Functions:

Function Purpose Returns Example UI
first_request() Initial request prompt str 🛸 Welcome Panel with examples
new_request() Subsequent requests Tuple[str, bool] 🛸 Next Request Panel
experience_asker() Save experience prompt bool 💾 Learning & Memory Panel
question_asker() Collect information str 🤔 Numbered Question Panel
sensitive_step_asker() Security confirmation bool 🔒 Security Check Panel

!!!example "Styled User Prompts"
```python
from ufo.module import interactor

text
# First interaction with rich welcome
request = interactor.first_request()
# Shows:
# ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
# ┃ 🛸 UFO Assistant                      ┃
# ┃ 🚀 Welcome to UFO - Your AI Assistant ┃
# ┃ ...examples...                        ┃
# ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛

# Get next request
request, complete = interactor.new_request()
if complete:
    print("User exited")

# Ask for permission on sensitive actions
proceed = interactor.sensitive_step_asker(
    action="Delete file",
    control_text="important.docx"
)
if not proceed:
    print("Action cancelled by user")
```

6. Session Factory & Pool

SessionFactory creates platform-specific sessions based on mode and configuration, while SessionPool manages batch execution.

Factory Creation Logic:

mermaid
graph TB
    START[SessionFactory.create_session]
    
    PLATFORM{Platform?}
    MODE{Mode?}
    
    WNORMAL[Windows Session]
    WSERVICE[Windows ServiceSession]
    WFOLLOWER[Windows FollowerSession]
    WBATCH[Windows FromFileSession]
    WOPERATOR[Windows OpenAIOperatorSession]
    
    LNORMAL[Linux Session]
    LSERVICE[Linux ServiceSession]
    
    START --> PLATFORM
    PLATFORM -->|Windows| MODE
    PLATFORM -->|Linux| MODE
    
    MODE -->|normal| WNORMAL
    MODE -->|service| WSERVICE
    MODE -->|follower| WFOLLOWER
    MODE -->|batch_normal| WBATCH
    MODE -->|operator| WOPERATOR
    
    MODE -->|normal Linux| LNORMAL
    MODE -->|service Linux| LSERVICE
    
    style START fill:#e1f5ff
    style PLATFORM fill:#fff4e1
    style MODE fill:#f0ffe1
    style WNORMAL fill:#ffe1f5
    style LNORMAL fill:#ffe1f5

Session Modes:

Mode Platform Description Input Evaluation
normal Both Interactive single-task User input Optional
service Both WebSocket-controlled Remote request Optional
follower Windows Replay recorded plan Plan JSON file Optional
batch_normal Windows Multiple tasks from files JSON folder Per-task
operator Windows OpenAI Operator API User input Optional
normal_operator Both Interactive with operator User input Optional

!!!example "SessionFactory Usage"
```python
from ufo.module.session_pool import SessionFactory, SessionPool

text
factory = SessionFactory()

# Interactive Windows session
sessions = factory.create_session(
    task="task1",
    mode="normal",
    plan="",
    request="Open calculator"
)

# Batch Windows sessions from folder
batch_sessions = factory.create_session(
    task="batch_task",
    mode="batch_normal",
    plan="./plans/",  # Folder with multiple .json files
    request=""
)

# Run all sessions
pool = SessionPool(batch_sessions)
await pool.run_all()
```

Cross-Platform Support

The module system provides a unified API while allowing platform-specific behavior through inheritance.

Platform Differences:

Aspect Windows Linux
Agent Architecture HostAgent → AppAgent (two-tier) LinuxAgent (single-tier)
HostAgent ✅ Used for planning ❌ Not used
Session Base WindowsBaseSession LinuxBaseSession
UI Automation UIA (pywinauto) Custom automation
Service Mode ServiceSession LinuxServiceSession
Evaluation ✅ Full support ⚠️ Limited
Markdown Logs ✅ Supported ⚠️ Planned

!!!example "Platform Detection"
```python
import platform

text
# Auto-detect platform
current_platform = platform.system().lower()  # 'windows' or 'linux'

# Override platform
sessions = factory.create_session(
    task="cross_platform_task",
    mode="normal",
    plan="",
    request="List files",
    platform_override="linux"  # Force Linux session
)
```

Execution Flow

Understanding how components interact during a complete user request:

text
/* Detailed source-code truncated for AI context efficiency. */

File Structure

text
ufo/module/
├── __init__.py
├── basic.py                    # BaseSession, BaseRound, FileWriter
├── context.py                  # Context, ContextNames
├── dispatcher.py               # Command dispatchers
├── interactor.py               # User interaction functions
├── session_pool.py             # SessionFactory, SessionPool
└── sessions/
    ├── __init__.py
    ├── platform_session.py     # WindowsBaseSession, LinuxBaseSession
    ├── session.py              # Session, FollowerSession, FromFileSession
    ├── service_session.py      # ServiceSession
    ├── linux_session.py        # LinuxSession, LinuxServiceSession
    └── plan_reader.py          # PlanReader for follower mode

Key Design Patterns

1. State Pattern

Agents use the State pattern to manage transitions and determine control flow.

python
# Agent state determines:
next_state = agent.state.next_state(agent)
next_agent = agent.state.next_agent(agent)
is_done = agent.state.is_round_end()

2. Factory Pattern

SessionFactory creates appropriate session types based on platform and mode.

3. Command Pattern

Commands encapsulate actions with parameters, enabling async execution and result tracking.

4. Observer Pattern

Context changes notify dependent components (implicit through shared state).


Best Practices

!!!tip "Session Management"
- ✅ Always initialize context before creating rounds
- ✅ Use SessionFactory for session creation (handles platform differences)
- ✅ Attach command dispatcher to context early
- ✅ Call context._sync_round_values() before accessing round-specific data
- ❌ Don't access round context before round initialization

!!!tip "Round Execution"
- ✅ Let the state machine control agent transitions
- ✅ Capture snapshots at subtask boundaries
- ✅ Check is_finished() before each iteration
- ❌ Don't bypass state transitions
- ❌ Don't manually manipulate agent states

!!!tip "Context Usage"
- ✅ Use ContextNames enum for type-safe access
- ✅ Update dictionaries with update_dict() for merging
- ✅ Use properties (current_round_cost) for auto-synced values
- ❌ Don't directly access _context dictionary
- ❌ Don't store non-serializable objects without marking them

!!!tip "Command Dispatch"
- ✅ Always await execute_commands() (async)
- ✅ Handle timeout exceptions gracefully
- ✅ Check ResultStatus before using results
- ❌ Don't ignore error results
- ❌ Don't assume commands succeed


Configuration

Key configuration options from ufo_config:

Setting Location Default Purpose
max_step system.max_step 50 Max steps per session
max_round system.max_round 10 Max rounds per session
eva_session system.eva_session True Evaluate session
eva_round system.eva_round False Evaluate each round
save_experience system.save_experience "ask" When to save experience
log_to_markdown system.log_to_markdown True Generate markdown logs
save_ui_tree system.save_ui_tree True Save UI tree snapshots

Documentation Index

Document Description
Session Session lifecycle and management
Round Round execution and orchestration
Context State management and context names
Dispatcher Command routing and execution
Session Pool Factory and batch management
Platform Sessions Windows/Linux implementations

Next Steps

Learning Path:

  1. Understand Sessions: Read Session to grasp the conversation model
  2. Learn Rounds: Study Round to understand action execution
  3. Master Context: Review Context for state management
  4. Explore Dispatch: Check Dispatcher for command execution
  5. Platform Specifics: See Platform Sessions for Windows/Linux differences

Documents Docs Tutorials Creating App Agent Overview (`documents/docs/tutorials/creating_app_agent/overview.md`)

Enhancing AppAgent Capabilities

UFO² provides a flexible framework for application developers and users to enhance AppAgent capabilities for specific applications. AppAgent enhancement is about augmenting the existing AppAgent's capabilities through:

  • Knowledge (help documents, demonstrations) to guide decision-making
  • Native API tools (via MCP servers) for efficient automation
  • Application-specific context for better understanding

Enhancement Components

The AppAgent can be enhanced through three complementary approaches:

Component Description Tutorial Implementation Guide
Help Documents Provide application-specific guidance and instructions to help the agent understand tasks and workflows Provision Guide Learning from Help Documents
User Demonstrations Supply recorded user interactions to teach the agent how to perform specific tasks through examples Provision Guide Learning from Demonstrations
Native API Tools Create custom MCP action servers that wrap application COM APIs or other native interfaces for efficient automation Wrapping Guide Creating MCP Servers

Enhancement Workflow

mermaid
graph TB
    Enhancement[AppAgent Enhancement Workflow]
    
    Enhancement --> KnowledgeLayer[Knowledge LayerRAG-based]
    Enhancement --> ToolLayer[Tool LayerMCP Servers]
    
    KnowledgeLayer --> HelpDocs[HelpDocuments]
    KnowledgeLayer --> DemoTraj[UserDemonstrations]
    
    ToolLayer --> UITools[UI AutomationTools]
    ToolLayer --> APITools[Native APITools]
    
    HelpDocs --> EnhancedAgent[Enhanced AppAgent]
    DemoTraj --> EnhancedAgent
    UITools --> EnhancedAgent
    APITools --> EnhancedAgent
    
    style Enhancement fill:#e1f5ff,stroke:#01579b,stroke-width:3px
    style KnowledgeLayer fill:#fff3e0,stroke:#e65100,stroke-width:2px
    style ToolLayer fill:#f3e5f5,stroke:#4a148c,stroke-width:2px
    style HelpDocs fill:#fffde7,stroke:#f57f17,stroke-width:2px
    style DemoTraj fill:#fffde7,stroke:#f57f17,stroke-width:2px
    style UITools fill:#fce4ec,stroke:#880e4f,stroke-width:2px
    style APITools fill:#fce4ec,stroke:#880e4f,stroke-width:2px
    style EnhancedAgent fill:#e8f5e9,stroke:#1b5e20,stroke-width:3px

When to Use Each Component?

Help Documents

Use when:

  • You have official documentation, tutorials, or guides for your application
  • Tasks require domain-specific knowledge or procedures
  • You want the agent to understand application concepts and terminology

Example: Providing Excel formula documentation to help the agent use advanced Excel functions correctly.

User Demonstrations

Use when:

  • You can demonstrate the task yourself
  • The task involves a specific sequence of UI interactions
  • Visual/procedural knowledge is easier to show than describe

Example: Recording how to create a pivot table in Excel to teach the agent the exact steps.

Native API Tools

Use when:

  • Your application exposes COM APIs, REST APIs, or other programmable interfaces
  • GUI automation is slow or unreliable for certain operations
  • You need deterministic, high-performance automation

Example: Creating an MCP server that wraps Excel's COM API for inserting tables, formatting cells, etc.

Enhancement Strategy

!!!tip "Hybrid Approach for Best Results"
Combine all three components for maximum effectiveness:

text
1. **Knowledge Foundation**: Provide help documents for conceptual understanding
2. **Procedural Learning**: Add demonstrations for complex workflows
3. **Efficient Execution**: Implement native API tools for performance-critical operations

The AppAgent will:
- Use knowledge to **understand** what to do
- Reference demonstrations to **learn** how to do it
- Leverage API tools when available for **efficient** execution
- Fall back to UI automation when needed

Getting Started

Follow the tutorials in order to enhance your AppAgent:

  1. Provide Help Documents - Start with knowledge
  2. Add User Demonstrations - Teach by example
  3. Wrap Native APIs - Enable efficient automation

Documents Docs Tutorials Creating Device Agent Index (`documents/docs/tutorials/creating_device_agent/index.md`)

Creating Device Agents - Tutorial Series

This tutorial series teaches you how to create new device agents for UFO³, using LinuxAgent as a reference implementation.

📚 Tutorial Structure

[Part 0: Overview](overview.md)

Introduction to device agents and architecture overview

  • Understanding device agents vs third-party agents
  • Server-client architecture
  • LinuxAgent as reference implementation
  • Tutorial roadmap

Time: 15 minutes | Difficulty: ⭐


[Part 1: Core Components](core_components.md)

Building server-side components

  • Agent Class implementation
  • Processor and strategy orchestration
  • State Manager and FSM
  • Processing Strategies (LLM, Action)
  • Prompter for LLM interaction

Time: 45 minutes | Difficulty: ⭐⭐⭐


[Part 2: MCP Server Development](mcp_server.md)

Creating platform-specific MCP servers (Placeholder - Under Development)

  • MCP server architecture
  • Defining MCP tools
  • Command execution logic
  • Error handling and validation

Time: 30 minutes | Difficulty: ⭐⭐


[Part 3: Client Setup](client_setup.md)

Setting up the device client (Placeholder - Under Development)

  • Client initialization and configuration
  • MCP server manager integration
  • WebSocket connection setup
  • Platform detection

Time: 20 minutes | Difficulty: ⭐⭐


[Part 4: Configuration & Deployment](configuration.md)

Configuring and deploying your agent (Placeholder - Under Development)

  • third_party.yaml configuration
  • devices.yaml device registration
  • Prompt template creation
  • Deployment steps
  • Galaxy integration

Time: 25 minutes | Difficulty: ⭐⭐


[Part 5: Testing & Debugging](testing.md)

Testing and debugging your implementation (Placeholder - Under Development)

  • Unit testing strategies
  • Integration testing
  • Debugging techniques
  • Common issues and solutions

Time: 30 minutes | Difficulty: ⭐⭐⭐


[Part 6: Complete Example: MobileAgent](example_mobile_agent.md)

Hands-on walkthrough creating MobileAgent (Placeholder - Under Development)

  • Step-by-step implementation
  • Android/iOS platform specifics
  • UI Automator integration
  • Complete working example

Time: 60 minutes | Difficulty: ⭐⭐⭐⭐


Quick Navigation

I Want To... Go To
Understand device agent architecture Overview
Study LinuxAgent implementation Overview
Create Agent Class Core Components - Step 1
Build Processor Core Components - Step 2
Implement State Machine Core Components - Step 3
Write Processing Strategies Core Components - Step 4
Create Prompter Core Components - Step 5
Build MCP Server MCP Server (placeholder)
Setup Client Client Setup (placeholder)
Configure & Deploy Configuration (placeholder)
Test & Debug Testing (placeholder)
Complete Example MobileAgent Example (placeholder)

Prerequisites

Before starting, ensure you have:

  • ✅ Python 3.10+
  • ✅ UFO³ repository cloned
  • ✅ Basic understanding of async programming
  • ✅ Familiarity with Agent Architecture

Learning Path

mermaid
graph LR
    A[Overview✅ Complete] --> B[Core Components✅ Complete]
    B --> C[MCP Server📝 Placeholder]
    C --> D[Client Setup📝 Placeholder]
    D --> E[Configuration📝 Placeholder]
    E --> F[Testing📝 Placeholder]
    F --> G[Complete Example📝 Placeholder]
    
    style A fill:#c8e6c9
    style B fill:#c8e6c9
    style C fill:#fff3e0
    style D fill:#fff3e0
    style E fill:#fff3e0
    style F fill:#fff3e0
    style G fill:#fff3e0

Recommended Path:

  1. ✅ Completed: Overview - Understand architecture
  2. ✅ Completed: Core Components - Build server-side components
  3. 📝 Placeholder: MCP Server - Create device commands
  4. 📝 Placeholder: Client Setup - Setup device client
  5. 📝 Placeholder: Configuration - Configure and deploy
  6. 📝 Placeholder: Testing - Test and debug
  7. 📝 Placeholder: Complete Example - Full MobileAgent implementation

Additional Resources


Getting Help

If you encounter issues:

  1. 📖 Review the FAQ
  2. 🐛 Check troubleshooting guides
  3. 💬 Ask in GitHub Discussions
  4. 🐞 Report bugs on GitHub Issues

Contributing

Found an issue or want to improve these tutorials?

  • 📝 Submit a PR with improvements
  • 💡 Suggest new topics
  • 🔍 Report errors or unclear sections

Ready to start? → Begin with Overview


Documents Docs Tutorials Creating Device Agent Overview (`documents/docs/tutorials/creating_device_agent/overview.md`)

Creating a New Device Agent - Complete Tutorial

This comprehensive tutorial teaches you how to create a new device agent (like MobileAgent, AndroidAgent, or iOSAgent) and integrate it with UFO³'s multi-device orchestration system. We'll use LinuxAgent as our primary reference implementation.


📋 Table of Contents

  1. Introduction
  2. Prerequisites
  3. Understanding Device Agents
  4. LinuxAgent: Reference Implementation
  5. Architecture Overview
  6. Tutorial Roadmap

Introduction

What is a Device Agent?

A Device Agent is a specialized AI agent that controls and automates tasks on a specific type of device or platform. Unlike traditional third-party agents that extend specific functionality, device agents represent entire computing platforms with their own:

  • Execution Environment: Device-specific OS, runtime, and APIs
  • Control Mechanism: UI automation, CLI commands, or platform APIs
  • Communication Protocol: Client-server architecture via WebSocket
  • MCP Integration: Device-specific MCP servers for command execution

Device Agent vs Third-Party Agent

Aspect Device Agent Third-Party Agent
Scope Full platform control (Windows, Linux, Mobile) Specific functionality (Hardware, Web)
Architecture Client-Server separation Runs on orchestrator server
Communication WebSocket + AIP Protocol Direct method calls
MCP Servers Platform-specific MCP servers Shares MCP servers
Examples WindowsAgent, LinuxAgent, MobileAgent HardwareAgent, WebAgent
Deployment Separate client process on device Part of orchestrator

When to Create a Device Agent

Create a Device Agent when you need to:

  • Control an entirely new platform (mobile, IoT, embedded)
  • Execute tasks on remote or distributed devices
  • Integrate with Galaxy multi-device orchestration
  • Isolate execution for security or scalability

Create a Third-Party Agent when you need to:

  • Extend existing platform with new capabilities
  • Add specialized tools or APIs
  • Run alongside existing agents

Prerequisites

Before starting this tutorial, ensure you have:

Knowledge Requirements

  • ✅ Python 3.10+: Intermediate Python programming skills
  • ✅ Async Programming: Understanding of async/await patterns
  • ✅ UFO³ Basics: Familiarity with Agent Architecture
  • ✅ MCP Protocol: Understanding of Model Context Protocol
  • ✅ WebSocket: Basic knowledge of WebSocket communication
Priority Topic Link Time
🥇 Agent Architecture Overview Infrastructure/Agents 20 min
🥇 LinuxAgent Quick Start Quick Start: Linux 15 min
🥈 Server-Client Architecture Server Overview, Client Overview 30 min
🥈 MCP Integration MCP Overview 20 min
🥉 AIP Protocol AIP Protocol 15 min

Development Environment

bash
# Clone UFO³ repository
git clone https://github.com/microsoft/UFO.git
cd UFO

# Install dependencies
pip install -r requirements.txt

# Verify installation
python -c "import ufo; print('UFO³ installed successfully')"

Understanding Device Agents

Three-Layer Architecture

All device agents in UFO³ follow a unified three-layer architecture:

mermaid
graph TB
    subgraph "Device Agent Architecture"
        subgraph "Level-1: State Layer (FSM)"
            S1[AgentState]
            S2[State Machine]
            S3[State Transitions]
            S1 --> S2 --> S3
        end
        
        subgraph "Level-2: Strategy Layer (Execution Logic)"
            P1[ProcessorTemplate]
            P2[DATA_COLLECTION]
            P3[LLM_INTERACTION]
            P4[ACTION_EXECUTION]
            P5[MEMORY_UPDATE]
            P1 --> P2 --> P3 --> P4 --> P5
        end
        
        subgraph "Level-3: Command Layer (System Interface)"
            C1[CommandDispatcher]
            C2[MCP Tools]
            C3[Device Commands]
            C1 --> C2 --> C3
        end
        
        S3 -->|delegates to| P1
        P5 -->|executes via| C1
    end
    
    style S1 fill:#e1f5ff
    style P1 fill:#fff3e0
    style C1 fill:#f3e5f5

Key Layers:

  1. State Layer (Level-1): Finite State Machine controlling agent lifecycle
  2. Strategy Layer (Level-2): Processing pipeline with modular strategies
  3. Command Layer (Level-3): Atomic system operations via MCP

For detailed architecture, see Agent Architecture Documentation.


Server-Client Separation

Device agents use a server-client architecture for security and scalability:

mermaid
graph LR
    subgraph "Server Side (Orchestrator)"
        Server[Device Agent Server]
        State[State Machine]
        Processor[Strategy Processor]
        LLM[LLM Service]
        
        Server --> State
        Server --> Processor
        Processor -.-> LLM
    end
    
    subgraph "Communication"
        AIP[AIP ProtocolWebSocket]
    end
    
    subgraph "Client Side (Device)"
        Client[Device Client]
        MCP[MCP Server Manager]
        Tools[Platform Tools]
        OS[Device OS]
        
        Client --> MCP
        MCP --> Tools
        Tools --> OS
    end
    
    Server <-->|Commands/Results| AIP
    AIP <-->|Commands/Results| Client
    
    style Server fill:#e1f5ff
    style Client fill:#c8e6c9
    style AIP fill:#fff3e0

Separation Benefits:

Component Location Responsibilities Security
Agent Server Orchestrator Reasoning, planning, state management Untrusted (LLM-driven)
Device Client Target Device Command execution, resource access Trusted (validated operations)
AIP Protocol Network Message transport, serialization Encrypted channel

Separation Benefits:

  • Security: Isolates LLM reasoning from system-level execution
  • Scalability: Single orchestrator manages multiple devices
  • Flexibility: Clients run on resource-constrained devices (mobile, IoT)
  • Safety: Client validates all commands before execution

LinuxAgent: Reference Implementation

Why LinuxAgent as Reference?

LinuxAgent is the ideal reference for creating new device agents because:

  • ✅ Simple Architecture: Single-tier agent (no HostAgent delegation)
  • ✅ Clear Separation: Clean server-client boundary
  • ✅ Well-Documented: Comprehensive code and documentation
  • ✅ Production-Ready: Battle-tested in real deployments
  • ✅ Minimal Complexity: Focuses on core device agent patterns

LinuxAgent Components

mermaid
graph TB
    subgraph "Server Side (ufo/agents/)"
        LA[LinuxAgent Classcustomized_agent.py]
        LAP[LinuxAgentProcessorcustomized_agent_processor.py]
        LAS[LinuxAgent Strategieslinux_agent_strategy.py]
        LAST[LinuxAgent Stateslinux_agent_state.py]
        
        LA --> LAP
        LAP --> LAS
        LA --> LAST
    end
    
    subgraph "Client Side (ufo/client/)"
        Client[UFO Clientclient.py]
        MCP[MCP Server Managermcp_server_manager.py]
        LinuxMCP[Linux MCP Serverlinux_mcp_server.py]
        
        Client --> MCP
        MCP --> LinuxMCP
    end
    
    subgraph "Configuration"
        Config[third_party.yaml]
        Devices[devices.yaml]
        Prompts[Prompt Templates]
    end
    
    LA -.reads.-> Config
    Client -.reads.-> Devices
    LA -.uses.-> Prompts
    
    style LA fill:#c8e6c9
    style LAP fill:#c8e6c9
    style LAS fill:#c8e6c9
    style LAST fill:#c8e6c9
    style Client fill:#e1f5ff
    style MCP fill:#e1f5ff
    style LinuxMCP fill:#e1f5ff

File Locations:

Component File Path Purpose
Agent Class ufo/agents/agent/customized_agent.py LinuxAgent definition
Processor ufo/agents/processors/customized/customized_agent_processor.py LinuxAgentProcessor
Strategies ufo/agents/processors/strategies/linux_agent_strategy.py LLM & Action strategies
States ufo/agents/states/linux_agent_state.py State machine states
Prompter ufo/prompter/customized/linux_agent_prompter.py Prompt construction
Client ufo/client/client.py Device client entry point
MCP Server ufo/client/mcp/http_servers/linux_mcp_server.py Command execution

LinuxAgent Architecture Diagram

mermaid
sequenceDiagram
    participant User
    participant Server as LinuxAgent Server
    participant AIP as AIP Protocol
    participant Client as Linux Client
    participant MCP as Linux MCP Server
    participant Shell as Bash Shell
    
    User->>Server: User Request: "List files in /tmp"
    
    Server->>Server: State: ContinueLinuxAgentState
    Server->>Server: Processor: LinuxAgentProcessor
    
    Server->>Server: Strategy: LLM_INTERACTION
    Note over Server: Construct prompt, call LLM
    Server->>Server: LLM Response: execute_command("ls -la /tmp")
    
    Server->>Server: Strategy: ACTION_EXECUTION
    Server->>AIP: COMMAND: execute_command
    AIP->>Client: WebSocket: COMMAND
    
    Client->>MCP: Call MCP Tool: execute_command
    MCP->>Shell: Execute: ls -la /tmp
    Shell-->>MCP: stdout, stderr, exit_code
    MCP-->>Client: Result
    Client->>AIP: WebSocket: RESULT
    AIP->>Server: RESULT
    
    Server->>Server: Strategy: MEMORY_UPDATE
    Server->>Server: Update memory & blackboard
    
    Server->>Server: State Transition: FINISH
    Server->>User: Task Complete

Key Execution Flow:

  1. User Request → LinuxAgent Server receives request
  2. State Machine → Activates ContinueLinuxAgentState
  3. Processor → Executes LinuxAgentProcessor strategies
  4. LLM Interaction → Generates shell command
  5. Action Execution → Sends command via AIP to client
  6. MCP Execution → Client executes via Linux MCP Server
  7. Result Handling → Server receives result, updates memory
  8. State Transition → Moves to FINISH state

Architecture Overview

Complete Device Agent Architecture

When creating a new device agent (e.g., MobileAgent), you'll implement these components:

mermaid
graph TB
    subgraph "1. Agent Definition"
        A1[Agent ClassMobileAgent]
        A2[ProcessorMobileAgentProcessor]
        A3[State ManagerMobileAgentStateManager]
    end
    
    subgraph "2. Processing Strategies"
        S1[DATA_COLLECTIONScreenshot, UI Tree]
        S2[LLM_INTERACTIONPrompt Construction]
        S3[ACTION_EXECUTIONCommand Dispatch]
        S4[MEMORY_UPDATEContext Update]
    end
    
    subgraph "3. MCP Server"
        M1[MCP Servermobile_mcp_server.py]
        M2[MCP Toolstap, swipe, type, etc.]
    end
    
    subgraph "4. Configuration"
        C1[third_party.yamlAgent Config]
        C2[devices.yamlDevice Registry]
        C3[Prompt TemplatesLLM Prompts]
    end
    
    subgraph "5. Client"
        CL1[Device Clientclient.py]
        CL2[MCP Managermcp_server_manager.py]
    end
    
    A1 --> A2
    A2 --> S1 & S2 & S3 & S4
    S3 --> M1
    M1 --> M2
    A1 -.reads.-> C1
    CL1 --> CL2
    CL2 --> M1
    CL1 -.reads.-> C2
    A2 -.uses.-> C3
    
    style A1 fill:#c8e6c9
    style A2 fill:#c8e6c9
    style A3 fill:#c8e6c9
    style M1 fill:#e1f5ff
    style CL1 fill:#e1f5ff

Implementation Checklist:

  • Agent Class: Define MobileAgent inheriting from CustomizedAgent
  • Processor: Create MobileAgentProcessor with custom strategies
  • State Manager: Implement MobileAgentStateManager and states
  • Strategies: Build platform-specific LLM and action strategies
  • MCP Server: Develop MCP server with platform tools
  • Prompter: Create custom prompter for mobile context
  • Client Setup: Configure client to run on mobile device
  • Configuration: Add agent config to third_party.yaml
  • Device Registry: Register device in devices.yaml
  • Prompt Templates: Write LLM prompt templates

Tutorial Roadmap

This tutorial is split into 6 detailed guides:

📘 Part 1: [Core Components](core_components.md)

Learn to implement the server-side components:

  • Agent Class definition
  • Processor and strategies
  • State Manager and states
  • Prompter for LLM interaction

Time: 45 minutes
Difficulty: ⭐⭐⭐


📘 Part 2: [MCP Server Development](mcp_server.md)

Create a platform-specific MCP server:

  • MCP server architecture
  • Defining MCP tools
  • Command execution logic
  • Error handling and validation

Time: 30 minutes
Difficulty: ⭐⭐


📘 Part 3: [Client Configuration](client_setup.md)

Set up the device client:

  • Client initialization
  • MCP server manager integration
  • WebSocket connection setup
  • Platform detection

Time: 20 minutes
Difficulty: ⭐⭐


📘 Part 4: [Configuration & Deployment](configuration.md)

Configure and deploy your agent:

  • third_party.yaml configuration
  • devices.yaml device registration
  • Prompt template creation
  • Galaxy integration

Time: 25 minutes
Difficulty: ⭐⭐


📘 Part 5: [Testing & Debugging](testing.md)

Test and debug your implementation:

  • Unit testing strategies
  • Integration testing
  • Debugging techniques
  • Common issues and solutions

Time: 30 minutes
Difficulty: ⭐⭐⭐


📘 Part 6: [Complete Example: MobileAgent](example_mobile_agent.md)

Hands-on walkthrough creating MobileAgent:

  • Step-by-step implementation
  • Android/iOS platform specifics
  • UI Automator integration
  • Complete working example

Time: 60 minutes
Difficulty: ⭐⭐⭐⭐


Quick Start Guide

For experienced developers, here's a minimal implementation checklist:

1️⃣ Create Agent Class

python
# ufo/agents/agent/customized_agent.py

@AgentRegistry.register(
    agent_name="MobileAgent",
    third_party=True,
    processor_cls=MobileAgentProcessor
)
class MobileAgent(CustomizedAgent):
    def __init__(self, name, main_prompt, example_prompt):
        super().__init__(name, main_prompt, example_prompt,
                         process_name=None, app_root_name=None, is_visual=None)
        self._blackboard = Blackboard()
        self.set_state(self.default_state)
        self._context_provision_executed = False
    
    @property
    def default_state(self):
        return ContinueMobileAgentState()

2️⃣ Create Processor

python
# ufo/agents/processors/customized/customized_agent_processor.py

class MobileAgentProcessor(CustomizedProcessor):
    def _setup_strategies(self):
        # Compose multiple data collection strategies
        self.strategies[ProcessingPhase.DATA_COLLECTION] = ComposedStrategy(
            strategies=[
                MobileScreenshotCaptureStrategy(fail_fast=True),
                MobileAppsCollectionStrategy(fail_fast=False),
                MobileControlsCollectionStrategy(fail_fast=False),
            ],
            name="MobileDataCollectionStrategy",
            fail_fast=True,
        )
        
        self.strategies[ProcessingPhase.LLM_INTERACTION] = (
            MobileLLMInteractionStrategy(fail_fast=True)
        )
        self.strategies[ProcessingPhase.ACTION_EXECUTION] = (
            MobileActionExecutionStrategy(fail_fast=False)
        )
        self.strategies[ProcessingPhase.MEMORY_UPDATE] = (
            AppMemoryUpdateStrategy(fail_fast=False)
        )

3️⃣ Create MCP Server

python
# ufo/client/mcp/http_servers/mobile_mcp_server.py

def create_mobile_mcp_server(host="localhost", port=8020):
    mcp = FastMCP("Mobile MCP Server", stateless_http=False, 
                  json_response=True, host=host, port=port)
    
    @mcp.tool()
    async def tap_element(x: int, y: int) -> dict:
        # Execute tap via ADB or platform API
        pass
    
    mcp.run(transport="streamable-http")

4️⃣ Configure Agent

yaml
# config/ufo/third_party.yaml

ENABLED_THIRD_PARTY_AGENTS: ["MobileAgent"]

THIRD_PARTY_AGENT_CONFIG:
  MobileAgent:
    VISUAL_MODE: True
    AGENT_NAME: "MobileAgent"
    APPAGENT_PROMPT: "ufo/prompts/third_party/mobile_agent.yaml"
    APPAGENT_EXAMPLE_PROMPT: "ufo/prompts/third_party/mobile_agent_example.yaml"
    INTRODUCTION: "MobileAgent controls Android/iOS devices..."

5️⃣ Register Device

yaml
# config/galaxy/devices.yaml

devices:
  - device_id: "mobile_agent_1"
    server_url: "ws://localhost:5010/ws"
    os: "android"
    capabilities: ["ui_automation", "app_testing"]
    metadata:
      device_model: "Pixel 6"
      android_version: "13"
    max_retries: 5

6️⃣ Start Server & Client

bash
# Terminal 1: Start Agent Server
python -m ufo.server.app --port 5010

# Terminal 2: Start Device Client
python -m ufo.client.client \
  --ws --ws-server ws://localhost:5010/ws \
  --client-id mobile_agent_1 \
  --platform android

# Terminal 3: Start MCP Server (on device or accessible endpoint)
python -m ufo.client.mcp.http_servers.mobile_mcp_server --port 8020

Next Steps

Ready to Build Your Device Agent?

Start with Part 1: Core Components →

Or jump to a specific topic:



Summary

Key Takeaways:

  • Device Agents control entire platforms (Windows, Linux, Mobile)
  • Server-Client Architecture separates reasoning from execution
  • Three-Layer Design provides modular, extensible framework
  • LinuxAgent is the best reference implementation
  • 6-Part Tutorial covers all aspects of device agent creation
  • MCP Integration enables platform-specific command execution
  • Galaxy Integration supports multi-device orchestration

Ready to build your first device agent? Let's get started! 🚀


Documents Docs Ufo2 App Agent Overview (`documents/docs/ufo2/app_agent/overview.md`)

AppAgent: Application Execution Agent

AppAgent is the core execution runtime in UFO, responsible for carrying out individual subtasks within a specific Windows application. Each AppAgent functions as an isolated, application-specialized worker process launched and orchestrated by the central HostAgent.


What is AppAgent?

AppAgent Architecture: Application-specialized worker process for subtask execution

AppAgent operates as a child agent under the HostAgent's orchestration:

  • Isolated Runtime: Each AppAgent is dedicated to a single Windows application
  • Subtask Executor: Executes specific subtasks delegated by HostAgent
  • Application Expert: Tailored with deep knowledge of the target app's API surface, control semantics, and domain logic
  • Hybrid Execution: Leverages both GUI automation and API-based actions through MCP commands

Unlike monolithic Computer-Using Agents (CUAs) that treat all GUI contexts uniformly, each AppAgent is tailored to a single application and operates with specialized knowledge of its interface and capabilities.


Core Responsibilities

mermaid
graph TB
    subgraph "AppAgent Core Responsibilities"
        SR[Sense:Capture Application State]
        RE[Reason:Analyze Next Action]
        EX[Execute:GUI or API Action]
        RP[Report:Write Results to Blackboard]
    end
    
    SR --> RE
    RE --> EX
    EX --> RP
    RP --> SR
    
    style SR fill:#e3f2fd
    style RE fill:#fff3e0
    style EX fill:#f1f8e9
    style RP fill:#fce4ec
Responsibility Description Example
State Sensing Capture application UI, detect controls, understand current state Screenshot Word window → Detect 50 controls → Annotate UI elements
Reasoning Analyze state and determine next action using LLM "Table visible with Export button [12] → Click to export data"
Action Execution Execute GUI clicks or API calls via MCP commands click_input(control_id=12) or execute_word_command("export_table")
Result Reporting Write execution results to shared Blackboard Write extracted data to subtask_result_1 for HostAgent

ReAct-Style Control Loop

Upon receiving a subtask and execution context from the HostAgent, the AppAgent initializes a ReAct-style control loop where it iteratively:

  1. Observes the current application state (screenshot + control detection)
  2. Thinks about the next step (LLM reasoning)
  3. Acts by executing either a GUI or API-based action (MCP commands)
mermaid
sequenceDiagram
    participant HostAgent
    participant AppAgent
    participant Application
    participant Blackboard
    
    HostAgent->>AppAgent: Delegate subtask"Extract table from Word"
    
    loop ReAct Loop
        AppAgent->>Application: Observe (screenshot + controls)
        Application-->>AppAgent: UI state
        AppAgent->>AppAgent: Think (LLM reasoning)
        AppAgent->>Application: Act (click/API call)
        Application-->>AppAgent: Action result
    end
    
    AppAgent->>Blackboard: Write result
    AppAgent->>HostAgent: Return control

The MCP command system enables reliable control over dynamic and complex UIs by favoring structured API commands whenever available, while retaining fallback to GUI-based interaction commands when necessary.


Execution Architecture

Finite State Machine

AppAgent uses a finite state machine with 7 states to control its execution flow:

  • CONTINUE: Continue processing the current subtask
  • FINISH: Successfully complete the subtask
  • ERROR: Encounter an unrecoverable error
  • FAIL: Fail to complete the subtask
  • PENDING: Wait for user input or clarification
  • CONFIRM: Request user confirmation for sensitive actions
  • SCREENSHOT: Capture and re-annotate the application screenshot

State Details: See State Machine Documentation for complete state definitions and transitions.

4-Phase Processing Pipeline

Each execution round follows a 4-phase pipeline:

mermaid
graph LR
    DC[Phase 1:DATA_COLLECTIONScreenshot + Controls] --> LLM[Phase 2:LLM_INTERACTIONReasoning]
    LLM --> AE[Phase 3:ACTION_EXECUTIONGUI/API Action]
    AE --> MU[Phase 4:MEMORY_UPDATERecord Action]
    
    style DC fill:#e1f5ff
    style LLM fill:#fff4e6
    style AE fill:#e8f5e9
    style MU fill:#fce4ec

Strategy Details: See Processing Strategy Documentation for complete pipeline implementation.


Hybrid GUI–API Execution

AppAgent executes actions through the MCP (Model-Context Protocol) command system, which provides a unified interface for both GUI automation and native API calls:

python
# GUI-based command (fallback)
command = Command(
    tool_name="click_input",
    parameters={"control_id": "12", "button": "left"}
)
await command_dispatcher.execute_commands([command])

# API-based command (preferred when available)
command = Command(
    tool_name="word_export_table",
    parameters={"format": "csv", "path": "output.csv"}
)
await command_dispatcher.execute_commands([command])

Implementation: See Hybrid Actions for details on the MCP command system.


Knowledge Enhancement

AppAgent is enhanced with Retrieval Augmented Generation (RAG) from heterogeneous sources:

Knowledge Source Purpose Configuration
Help Documents Application-specific documentation Learning from Help Documents
Bing Search Latest information and updates Learning from Bing Search
Self-Demonstrations Successful action trajectories Experience Learning
Human Demonstrations Expert-provided workflows Learning from Demonstrations

Knowledge Substrate Overview: See Knowledge Substrate for the complete RAG architecture.


Command System

AppAgent executes actions through the MCP (Model-Context Protocol) command system:

Application-Level Commands:

  • capture_window_screenshot - Capture application window
  • get_control_info - Detect UI controls via UIA/OmniParser
  • click_input - Click on UI control
  • set_edit_text - Type text into input field
  • annotation - Annotate screenshot with control labels

Command Details: See Command System Documentation for complete command reference.


Control Detection Backends

AppAgent supports multiple control detection backends for comprehensive UI understanding:

UIA (UI Automation):
Native Windows UI Automation API for standard controls

  • ✅ Fast and accurate
  • ✅ Works with most Windows applications
  • ❌ May miss custom controls

OmniParser (Visual Detection):
Vision-based grounding model for visual elements

  • ✅ Detects icons, images, custom controls
  • ✅ Works with web content
  • ❌ Requires external service

Hybrid (UIA + OmniParser):
Best of both worlds - maximum coverage

  • ✅ Native controls + visual elements
  • ✅ Comprehensive UI understanding

Control Detection Details: See Control Detection Overview.


Input and Output

AppAgent Input

Input Description Source
User Request Original user request in natural language HostAgent
Sub-Task Specific subtask to execute HostAgent delegation
Application Context Target app name, window info HostAgent
Control Information Detected UI controls with labels Data collection phase
Screenshots Clean, annotated, previous step images Data collection phase
Blackboard Shared memory for inter-agent communication Global context
Retrieved Knowledge Help docs, demos, search results RAG system

AppAgent Output

Output Description Consumer
Observation Current UI state description LLM context
Thought Reasoning about next action Execution log
ControlLabel Selected control to interact with Action executor
Function MCP command to execute (click_input, set_edit_text, etc.) Command dispatcher
Args Command parameters Command dispatcher
Status Agent state (CONTINUE, FINISH, etc.) State machine
Blackboard Update Execution results HostAgent

Example Output:

json
{
    "Observation": "Word document with table, Export button at [12]",
    "Thought": "Click Export to extract table data",
    "ControlLabel": "12",
    "Function": "click_input",
    "Args": {"button": "left"},
    "Status": "CONTINUE"
}

Detailed Documentation:

Core Features:

Tutorials:


API Reference

:::agents.agent.app_agent.AppAgent


Summary

AppAgent Key Characteristics:

✅ Application-Specialized Worker: Dedicated to single Windows application
✅ ReAct Control Loop: Iterative observe → think → act execution
✅ Hybrid Execution: GUI automation + API calls via MCP commands
✅ 7-State FSM: Robust state management for execution control
✅ 4-Phase Pipeline: Structured data collection → reasoning → action → memory
✅ Knowledge-Enhanced: RAG from docs, demos, and search
✅ Orchestrated by HostAgent: Child agent in hierarchical architecture

Next Steps:

  1. Deep Dive: Read State Machine and Processing Strategy for implementation details
  2. Learn Features: Explore Core Features for advanced capabilities
  3. Hands-On Tutorial: Follow Creating AppAgent guide

Documents Docs Ufo2 Dataflow Overview (`documents/docs/ufo2/dataflow/overview.md`)

Introduction

This repository contains the implementation of the Data Collection process for training the Large Action Models (LAMs) in the paper of Large Action Models: From Inception to Implementation. The Data Collection process is designed to streamline task processing, ensuring that all necessary steps are seamlessly integrated from initialization to execution. This module is part of the UFO project.

Dataflow

Dataflow uses UFO to implement instantiation, execution, and dataflow for a given task, with options for batch processing and single processing.

  1. Instantiation: Instantiation refers to the process of setting up and preparing a task for execution. This step typically involves choosing template, prefill and filter.
  2. Execution: Execution is the actual process of running the task. This step involves carrying out the actions or operations specified by the Instantiation. And after execution, an evaluate agent will evaluate the quality of the whole execution process.
  3. Dataflow: Dataflow is the overarching process that combines instantiation and execution into a single pipeline. It provides an end-to-end solution for processing tasks, ensuring that all necessary steps (from initialization to execution) are seamlessly integrated.

You can use instantiation and execution independently if you only need to perform one specific part of the process. When both steps are required for a task, the dataflow process streamlines them, allowing you to execute tasks from start to finish in a single pipeline.

The overall processing of dataflow is as below. Given a task-plan data, the LLMwill instantiatie the task-action data, including choosing template, prefill, filter.

How To Use

1. Install Packages

You should install the necessary packages in the UFO root folder:

bash
pip install -r requirements.txt

2. Configure the LLMs

Before running dataflow, you need to provide your LLM configurations individually for PrefillAgent and FilterAgent. You can create your own config file dataflow/config/config.yaml, by copying the dataflow/config/config.yaml.template and editing config for PREFILL_AGENT and FILTER_AGENT as follows:

OpenAI

bash
VISUAL_MODE: True, # Whether to use the visual mode
API_TYPE: "openai" , # The API type, "openai" for the OpenAI API.  
API_BASE: "https://api.openai.com/v1/chat/completions", # The the OpenAI API endpoint.
API_KEY: "sk-",  # The OpenAI API key, begin with sk-
API_VERSION: "2024-02-15-preview", # "2024-02-15-preview" by default
API_MODEL: "gpt-4-vision-preview",  # The only OpenAI model

Azure OpenAI (AOAI)

bash
VISUAL_MODE: True, # Whether to use the visual mode
API_TYPE: "aoai" , # The API type, "aoai" for the Azure OpenAI.  
API_BASE: "YOUR_ENDPOINT", #  The AOAI API address. Format: https://{your-resource-name}.openai.azure.com
API_KEY: "YOUR_KEY",  # The aoai API key
API_VERSION: "2024-02-15-preview", # "2024-02-15-preview" by default
API_MODEL: "gpt-4-vision-preview",  # The only OpenAI model
API_DEPLOYMENT_ID: "YOUR_AOAI_DEPLOYMENT", # The deployment id for the AOAI API

You can also non-visial model (e.g., GPT-4) for each agent, by setting VISUAL_MODE: False and proper API_MODEL (openai) and API_DEPLOYMENT_ID (aoai).

Non-Visual Model Configuration

You can utilize non-visual models (e.g., GPT-4) for each agent by configuring the following settings in the config.yaml file:

  • VISUAL_MODE: False # To enable non-visual mode.
  • Specify the appropriate API_MODEL (OpenAI) and API_DEPLOYMENT_ID (AOAI) for each agent.

Ensure you configure these settings accurately to leverage non-visual models effectively.

Other Configurations

config_dev.yaml specifies the paths of relevant files and contains default settings. The match strategy for the window match and control filter supports options: 'contains', 'fuzzy', and 'regex', allowing flexible matching strategy for users. The MAX_STEPS is the max step for the execute_flow, which can be set by users.

!!!note
The specific implementation and invocation method of the matching strategy can refer to windows_app_env.

!!!note
BE CAREFUL! If you are using GitHub or other open-source tools, do not expose your config.yaml online, as it contains your private keys.

3. Prepare Files

Certain files need to be prepared before running the task.

3.1. Tasks as JSON

The tasks that need to be instantiated should be organized in a folder of JSON files, with the default folder path set to dataflow /tasks . This path can be changed in the dataflow/config/config.yaml file, or you can specify it in the terminal, as mentioned in 4. Start Running. For example, a task stored in dataflow/tasks/prefill/ may look like this:

json
{
    // The app you want to use
    "app": "word",
    // A unique ID to distinguish different tasks 
    "unique_id": "1",
    // The task and steps to be instantiated
    "task": "Type 'hello' and set the font type to Arial",
    "refined_steps": [
        "Type 'hello'",
        "Set the font to Arial"
    ]
}

3.2. Templates and Descriptions

You should place an app file as a reference for instantiation in a folder named after the app.

For example, if you have template1.docx for Word, it should be located at dataflow/templates/word/template1.docx.

Additionally, for each app folder, there should be a description.json file located at dataflow/templates/word/description.json, which describes each template file in detail. It may look like this:

json
{
    "template1.docx": "A document with a rectangle shape",
    "template2.docx": "A document with a line of text"
}

If a description.json file is not present, one template file will be selected at random.

3.3. Final Structure

Ensure the following files are in place:

  • JSON files to be instantiated
  • Templates as references for instantiation
  • Description file in JSON format

The structure of the files can be:

txt
dataflow/
|
├── tasks
│   └── prefill
│       ├── bulleted.json
│       ├── delete.json
│       ├── draw.json
│       ├── macro.json
│       └── rotate.json
├── templates
│   └── word
│       ├── description.json
│       ├── template1.docx
│       ├── template2.docx
│       ├── template3.docx
│       ├── template4.docx
│       ├── template5.docx
│       ├── template6.docx
│       └── template7.docx
└── ...

4. Start Running

After finishing the previous steps, you can use the following commands in the command line. We provide single / batch process, for which you need to give the single file path / folder path. Determine the type of path provided by the user and automatically decide whether to process a single task or batch tasks.

Also, you can choose to use instantiation / execution sections individually, or use them as a whole section, which is named as dataflow.

The default task hub is set to be "TASKS_HUB" in dataflow/config_dev.yaml.

  • Dataflow Task:
bash
python -m dataflow -dataflow --task_path path_to_task_file
  • Instantiation Task:
bash
python -m dataflow -instantiation --task_path path_to_task_file
  • Execution Task:
bash
python -m dataflow -execution --task_path path_to_task_file

!!! note

text
1. Users should be careful to save the original files while using this project; otherwise, the files will be closed when the app is shut down.
2. After starting the project, users should not close the app window while the program is taking screenshots.

Workflow

Instantiation

There are three key steps in the instantiation process:

  1. Choose a template file according to the specified app and instruction.
  2. Prefill the task using the current screenshot.
  3. Filter the established task.

Given the initial task, the dataflow first choose a template (Phase 1), the prefill the initial task based on word envrionment to obtain task-action data (Phase 2). Finnally, it will filter the established task to evaluate the quality of task-action data. (Phase 3)

!!! note
The more detailed code design documentation for instantiation can be found in instantiation.

Execution

The instantiated plans will be executed by a execute task. After execution, evalution agent will evaluation the quality of the entire execution process.

!!! note
The more detailed code design documentation for execution can be found in execution.

Result

The results will be saved in the results\ directory under instantiation, execution, and dataflow, and will be further stored in subdirectories based on the execution outcomes.

!!! note
The more detailed information of result can be found in result.

Quick Start

We prepare two cases to show the dataflow, which can be found in dataflow\tasks\prefill. So after installing required packages, you can type the following command in the command line:

text
python -m dataflow -dataflow

And you can see the hints showing in the terminal, which means the dataflow is working.

After the two tasks are finished, the task and output files would appear as follows:

bash
UFO/
├── dataflow/
│   └── results/
│       ├── saved_document/       	# Directory for saved documents
│       │   ├── bulleted.docx     	# Result of the "bulleted" task
│       │   └── rotate.docx       	# Result of the "rotate" task
│       ├── dataflow/            		 # Dataflow results directory
│       │   ├── execution_pass/   	# Successfully executed tasks
│       │   │   ├── bulleted.json 	# Execution result for the "bulleted" task
│       │   │   ├── rotate.json  	 # Execution result for the "rotate" task
│       │   │   └── ...
└── ...

The specific results can be referenced in the result in JSON format along with example data.

Log files

The corresponding logs can be found in the directories logs/bulleted and logs/rotate, as shown below. Detailed logs for each workflow are recorded, capturing every step of the execution process.

Reference

AppEnum

::: data_flow_controller.AppEnum

TaskObject

::: data_flow_controller.TaskObject

DataFlowController

::: data_flow_controller.DataFlowController


Documents Docs Ufo2 Host Agent Overview (`documents/docs/ufo2/host_agent/overview.md`)

HostAgent: Desktop Orchestrator

HostAgent serves as the centralized control plane of UFO². It interprets user-specified goals, decomposes them into structured subtasks, instantiates and dispatches AppAgent modules, and coordinates their progress across the system. HostAgent provides system-level services for introspection, planning, application lifecycle management, and multi-agent synchronization.


Architecture Overview

Operating atop the native Windows substrate, HostAgent monitors active applications, issues shell commands to spawn new processes as needed, and manages the creation and teardown of application-specific AppAgent instances. All coordination occurs through a persistent state machine, which governs the transitions across execution phases.

Figure: HostAgent architecture showing the finite state machine, processing pipeline, and interactions with AppAgents through the Blackboard pattern.

Core Responsibilities

Task Decomposition

Given a user's natural language input, HostAgent identifies the underlying task goal and decomposes it into a dependency-ordered subtask graph.

Example: User request "Extract data from Word and create an Excel chart" becomes:

  1. Extract table from Word document
  2. Create chart in Excel with extracted data
Figure: HostAgent decomposes user requests into sequential subtasks, assigns each to the appropriate application, and orchestrates AppAgents to complete them in dependency order.

Application Lifecycle Management

For each subtask, HostAgent inspects system process metadata (via UIA APIs) to determine whether the target application is running. If not, it launches the program and registers it with the runtime.

AppAgent Instantiation

HostAgent spawns the corresponding AppAgent for each active application, providing it with task context, memory references, and relevant toolchains (e.g., APIs, documentation).

Task Scheduling and Control

The global execution plan is serialized into a finite state machine (FSM), allowing HostAgent to enforce execution order, detect failures, and resolve dependencies across agents. See State Machine Details for the FSM architecture.

Shared State Communication

HostAgent reads from and writes to a global blackboard, enabling inter-agent communication and system-level observability for debugging and replay.


Key Characteristics

  • Scope: Desktop-level orchestrator (system-wide, not application-specific)
  • Lifecycle: Single instance per session, persists throughout task execution
  • Hierarchy: Parent agent that manages multiple child AppAgents
  • Communication: Owns and coordinates the shared Blackboard
  • Control: 7-state finite state machine with 4-phase processing pipeline

Execution Workflow

mermaid
sequenceDiagram
    participant User
    participant HostAgent
    participant Blackboard
    participant AppAgent1
    participant AppAgent2
    
    User->>HostAgent: "Extract Word table, create Excel chart"
    HostAgent->>HostAgent: Decompose into subtasks
    HostAgent->>Blackboard: Write subtask 1
    HostAgent->>AppAgent1: Create/Get Word AppAgent
    AppAgent1->>AppAgent1: Execute Word task
    AppAgent1->>Blackboard: Write result 1
    AppAgent1-->>HostAgent: Return FINISH
    
    HostAgent->>Blackboard: Read result 1
    HostAgent->>Blackboard: Write subtask 2
    HostAgent->>AppAgent2: Create/Get Excel AppAgent
    AppAgent2->>Blackboard: Read result 1
    AppAgent2->>AppAgent2: Execute Excel task
    AppAgent2->>Blackboard: Write result 2
    AppAgent2-->>HostAgent: Return FINISH
    
    HostAgent->>HostAgent: Verify completion
    HostAgent-->>User: Task completed

Deep Dive Topics


Input and Output

HostAgent Input

Input Description Type
User Request Natural language task description String
Application Information Active application metadata List of Dicts
Desktop Screenshots Visual context of desktop state Image
Previous Sub-Tasks Completed subtask history List of Dicts
Previous Plan Planned future subtasks List of Strings
Blackboard Shared memory space Dictionary

HostAgent Output

Output Description Type
Observation Desktop screenshot analysis String
Thought Reasoning process String
Current Sub-Task Active subtask description String
Message Information for AppAgent String
ControlLabel Selected application index String
ControlText Selected application name String
Plan Future subtask sequence List of Strings
Status Agent state (CONTINUE/ASSIGN/FINISH/etc.) String
Comment User-facing information String
Questions Clarification requests List of Strings
Bash System command to execute String

Example Output:

json
{
    "Observation": "Desktop shows Microsoft Word with document open containing a table",
    "Thought": "User wants to extract data from Word first",
    "Current Sub-Task": "Extract the table data from the document",
    "Message": "Starting data extraction from Word document",
    "ControlLabel": "0",
    "ControlText": "Microsoft Word - Document1",
    "Plan": ["Extract table from Word", "Create chart in Excel"],
    "Status": "ASSIGN",
    "Comment": "Delegating table extraction to Word AppAgent",
    "Questions": [],
    "Bash": ""
}

Architecture & Design:

Configuration:

System Integration:


API Reference

:::agents.agent.host_agent.HostAgent


Summary

HostAgent is the desktop-level orchestrator that:

  • Decomposes tasks and coordinates AppAgents
  • Operates at system level, not application level
  • Uses a 7-state FSM: CONTINUE → ASSIGN → AppAgent → CONTINUE → FINISH
  • Executes a 4-phase pipeline: DATA_COLLECTION → LLM → ACTION → MEMORY
  • Creates, caches, and reuses AppAgent instances
  • Provides shared Blackboard memory for all agents
  • Maintains single instance per session managing multiple AppAgents

Next Steps:

  1. Read State Machine for FSM details
  2. Read Processing Strategy for pipeline architecture
  3. Read Command System for available desktop operations
  4. Read AppAgent for application-level execution

Documents Docs Ufo2 Prompts Overview (`documents/docs/ufo2/prompts/overview.md`)

Prompts

All prompts used in UFO are stored in the ufo/prompts directory. The folder structure is as follows:

text
📦prompts
 ┣ 📂demonstration       # Prompts for summarizing human demonstrations
 ┣ 📂evaluation          # Prompts for the EvaluationAgent
 ┣ 📂examples            # Demonstration examples for in-context learning
   ┣ 📂nonvisual        # Examples for non-visual LLMs
   ┗ 📂visual           # Examples for visual LLMs
 ┣ 📂experience          # Prompts for summarizing agent self-experience
 ┣ 📂share               # Shared prompt templates
   ┗ 📂base             # Basic version of shared prompts
     ┣ 📜api.yaml       # Basic API prompt
     ┣ 📜app_agent.yaml # Basic AppAgent prompt template
     ┗ 📜host_agent.yaml # Basic HostAgent prompt template
 ┗ 📂third_party         # Third-party integration prompts (e.g., Linux agents)

Visual LLMs can process screenshots while non-visual LLMs rely on text-only control information.

Agent Prompts

Agent prompts are constructed from the following components:

Component Description Source
Basic Template Base template with system and user roles YAML files in share/base/
API Documentation Skills and APIs available to the agent Dynamically generated from MCP tools
Examples In-context learning demonstrations YAML files in examples/visual/ or examples/nonvisual/

You can find the base templates in the share/base directory.

How Prompts Are Constructed

The agent's Prompter class is responsible for:

  1. Loading YAML templates from the file system
  2. Formatting API documentation from available tools
  3. Selecting appropriate examples based on model type (visual/nonvisual)
  4. Combining all components into a structured message list for the LLM
  5. Injecting runtime context (observations, screenshots, retrieved knowledge)

Each agent type has its own specialized Prompter:

  • HostAgentPrompter: Desktop-level orchestration with third-party agent support
  • AppAgentPrompter: Application-level interactions with multi-action capabilities
  • EvaluationAgentPrompter: Task evaluation and success assessment

For comprehensive details about the Prompter class architecture, template loading, and prompt construction workflow, see the Prompter documentation.


Documents Docs Ufo2 Core Features Control Detection Overview (`documents/docs/ufo2/core_features/control_detection/overview.md`)

Control Detection

We support different control detection methods to detect controls in the application to accommodate both standard (UIA) and custom controls (Visual).

Detection Methods

Method Description Use Case
UIA Uses Windows UI Automation framework to detect standard controls. Provides APIs to access and manipulate UI elements in Windows applications. Standard Windows applications with native controls
Visual (OmniParser) Uses OmniParser vision-based detection to identify custom controls through computer vision techniques based on visual appearance. Applications with custom controls, icons, or visual elements not accessible via UIA
Hybrid Combines both UIA and OmniParser detection methods. Merges results from both approaches, removing duplicates based on IoU overlap. Maximum coverage for applications with both standard and custom controls

Configuration

Configure the control detection method by setting the CONTROL_BACKEND parameter in config/ufo/system.yaml:

yaml
# Use UIA only (default, recommended)
CONTROL_BACKEND: ["uia"]

# Use OmniParser only
CONTROL_BACKEND: ["omniparser"]

# Use hybrid mode (UIA + OmniParser)
CONTROL_BACKEND: ["uia", "omniparser"]

See System Configuration for detailed configuration options.


Documents Docs Ufo2 Core Features Knowledge Substrate Overview (`documents/docs/ufo2/core_features/knowledge_substrate/overview.md`)

Knowledge Substrate

UFO provides versatile mechanisms to enhance the AppAgent's capabilities through RAG (Retrieval-Augmented Generation) and other knowledge retrieval techniques. These mechanisms improve the AppAgent's task understanding, plan quality, and interaction efficiency with applications.

Supported Knowledge Sources

UFO currently supports the following knowledge retrieval methods:

Knowledge Source Description
Help Documents Retrieve knowledge from offline help documentation indexed for specific applications.
Bing Search Search online information via Bing to obtain up-to-date knowledge.
Self-Experience Learn from the agent's own successful task execution history.
User Demonstrations Learn from action trajectories demonstrated by users.

Context Provision

UFO provides knowledge to the AppAgent through the context_provision method defined in the AppAgent class:

text
/* Detailed source-code truncated for AI context efficiency. */

The context_provision method loads various knowledge retrievers based on the configuration settings in config.yaml:

  • Offline document retriever: Loads indexed help documentation for the target application
  • Online search retriever: Creates a Bing search indexer when a search request is provided
  • Experience retriever: Loads the agent's historical successful experiences
  • Demonstration retriever: Loads user-demonstrated action trajectories
  • MCP context: Loads Model Context Protocol tool information for the current application

Retriever API Reference

UFO employs the Retriever class located in ufo/rag/retriever.py to retrieve knowledge from various sources. For detailed API documentation, see:

:::rag.retriever.Retriever


Documents Docs Ufo2 Evaluation Benchmark Overview (`documents/docs/ufo2/evaluation/benchmark/overview.md`)

Benchmark Overview

UFO² is rigorously benchmarked on two publicly‑available live‑task suites:

Benchmark Scope
Windows Agent Arena (WAA) 154 real Windows tasks across 15 applications (Office, Edge, File Explorer, VS Code, …)
OSWorld (Windows) 49 cross‑application tasks that mix Office 365, browser and system utilities

The integration of these benchmarks into UFO² is in separate repositories. Please follow the above documents for more details.

!!!note
we have revised the verification scripts of some cases to ensure the correctness of the results.


Documents Docs Ufo2 Evaluation Logs Overview (`documents/docs/ufo2/evaluation/logs/overview.md`)

UFO Logs

UFO generates comprehensive logs for debugging, analysis, and evaluation. Understanding these logs is essential for diagnosing issues and improving agent performance.

Log Types

Log Type Description Location
Request Log LLM prompt requests at each step logs/{task_name}/request.log
Step Log Agent responses and execution details logs/{task_name}/response.log
Evaluation Log Task evaluation results logs/{task_name}/evaluation.log
Screenshots UI screenshots and visual captures logs/{task_name}/
UI Tree Application UI structure data logs/{task_name}/ui_tree/

All logs are stored in the logs/{task_name} directory, where {task_name} is auto-generated based on timestamp.


Documents Docs Choose Path (`documents/docs/choose_path.md`)

Choosing Your Path: UFO² or UFO³ Galaxy?

Not sure which UFO framework to use? This guide will help you make the right choice based on your specific needs.


🗺️ Quick Decision Tree

Use this interactive flowchart to find the best solution for your use case:

mermaid
graph TD
    Start[What are you trying to automate?] --> Q1{Involves multipledevices/platforms?}
    
    Q1 -->|Yes| Q2{Need parallelexecution acrossdevices?}
    Q1 -->|No| Q3{Complex multi-appworkflow on Windows?}
    
    Q2 -->|Yes| Galaxy[✨ Use UFO³ Galaxy]
    Q2 -->|No, sequential| Q4{Can tasks runindependently?}
    
    Q4 -->|Yes, independent| UFO2_Multi[Use UFO² on each deviceseparately]
    Q4 -->|No, dependencies| Galaxy
    
    Q3 -->|Yes| UFO2[🪟 Use UFO²]
    Q3 -->|No, simple task| UFO2
    
    Q3 -->|Might scale later| Hybrid[Use UFO² now,Galaxy-ready setup]
    
    Galaxy --> GalaxyDoc[📖 See Galaxy Quick Start]
    UFO2 --> UFO2Doc[📖 See UFO² Quick Start]
    UFO2_Multi --> UFO2Doc
    Hybrid --> MigrationDoc[📖 See Migration Guide]
    
    style Galaxy fill:#fff9c4
    style UFO2 fill:#c8e6c9
    style UFO2_Multi fill:#c8e6c9
    style Hybrid fill:#e1bee7
    
    click GalaxyDoc "./getting_started/quick_start_galaxy.md"
    click UFO2Doc "./getting_started/quick_start_ufo2.md"
    click MigrationDoc "./getting_started/migration_ufo2_to_galaxy.md"

📊 Quick Comparison Matrix

Dimension UFO² Desktop AgentOS UFO³ Galaxy
Target Scope Single Windows desktop Multiple devices (Windows/Linux/macOS)
Best For Simple local automation Complex cross-device workflows
Setup Complexity ⭐ Simple ⭐⭐⭐ Moderate (requires device pool)
Learning Curve ⭐⭐ Easy ⭐⭐⭐⭐ Advanced
Execution Model Sequential multi-app Parallel DAG orchestration
Network Required ❌ No ✅ Yes (WebSocket between devices)
Parallelism Within single device Across multiple devices
Fault Tolerance Retry on same device Retry + task migration
Typical Latency 10-30s (local) 20-60s (includes orchestration)
Ideal Task Count 1-5 steps 5-20+ steps with dependencies

Quick Rule of Thumb:

  • 1 device + simple workflow → UFO²
  • 2+ devices OR complex dependencies → Galaxy
  • Not sure? → Start with UFO², migrate later (Migration Guide)

🎯 Scenario-Based Recommendations

Scenario 1: Desktop Productivity Automation

Task: "Create a weekly report: extract data from Excel, generate charts in PowerPoint, send via Outlook"

Recommendation: ✅ UFO²

Why:

  • All applications on one Windows desktop
  • Sequential workflow (Excel → PowerPoint → Outlook)
  • No cross-device dependencies

Learn More: UFO² Overview


Scenario 2: Development Workflow Automation

Task: "Clone repo on my laptop, build Docker image on GPU server, run tests on CI cluster, open results on my desktop"

Recommendation: ✅ UFO³ Galaxy

Why:

  • Spans 3+ devices (laptop, GPU server, CI cluster, desktop)
  • Sequential dependencies (clone → build → test → display)
  • Requires device coordination and data transfer

Learn More: Galaxy Overview


Scenario 3: Batch Data Processing

Task: "Process 100 files: fetch from cloud, clean data, run ML model, save results"

Recommendation: Depends on setup

Setup Recommendation Why
Single powerful workstation ✅ UFO² All processing on one machine, simpler
Distributed cluster ✅ Galaxy Parallel processing across nodes, faster
Mix (local + cloud GPU) ✅ Galaxy Heterogeneous resources

Learn More:


Scenario 4: Cross-Platform Testing

Task: "Test web app on Windows Chrome, Linux Firefox, and macOS Safari"

Recommendation: ✅ UFO³ Galaxy

Why:

  • Requires 3 different OS platforms
  • Parallel execution saves time
  • Centralized result aggregation

Learn More: Galaxy Multi-Platform Support


Scenario 5: File Management & Organization

Task: "Organize Downloads folder by file type, compress old files, upload to cloud"

Recommendation: ✅ UFO²

Why:

  • Single-device local file operations
  • No network dependencies
  • Simple sequential workflow

Learn More: UFO² Quick Start


Scenario 6: Multi-Stage Data Pipeline

Task: "Collect logs from 5 Linux servers, aggregate on central server, analyze, generate dashboard on Windows"

Recommendation: ✅ UFO³ Galaxy

Why:

  • Multiple source devices (5 Linux servers)
  • Parallel log collection (5x faster than sequential)
  • Cross-platform (Linux → Windows)
  • Complex dependency graph

Learn More: Galaxy Task Constellation


Scenario 7: Learning Agent Development

Task: "I'm new to agent development and want to learn by building simple automation"

Recommendation: ✅ UFO²

Why:

  • Simpler architecture (easier to understand)
  • Faster feedback loop (local execution)
  • Comprehensive documentation and examples
  • Can upgrade to Galaxy later

Learn More: UFO² Quick Start


Scenario 8: Enterprise Workflow Integration

Task: "Integrate with existing CI/CD pipeline across dev laptops, build servers, and test farms"

Recommendation: ✅ UFO³ Galaxy

Why:

  • Enterprise-scale device coordination
  • Fault tolerance with automatic recovery
  • Formal safety guarantees for correctness
  • Supports heterogeneous infrastructure

Learn More: Galaxy Architecture


🔀 Hybrid Approaches

You don't have to choose just one! Here are common hybrid patterns:

Pattern 1: UFO² as Galaxy Device

Setup: Run UFO² as a Galaxy device (requires both server and client)

bash
# Terminal 1: Start UFO² Server on Windows desktop
python -m ufo.server.app --port 5000

# Terminal 2: Start UFO² Client (connect to server)
python -m ufo.client.client --ws --ws-server ws://localhost:5000/ws --client-id my_windows_device --platform windows

Benefits:

  • Keep UFO² for local Windows expertise
  • Gain Galaxy's cross-device orchestration
  • Best of both worlds

Learn More: UFO² as Galaxy Device


Pattern 2: Gradual Migration

Strategy: Start with UFO² for immediate needs, prepare for Galaxy expansion

Phase 1: Use UFO² standalone

bash
python -m ufo --task "Your current task"

Phase 2: Make UFO² Galaxy-compatible

yaml
# config/galaxy/devices.yaml (prepare in advance)
devices:
  - device_id: "my_windows"
    server_url: "ws://localhost:5000/ws"  # Where UFO client connects to UFO server
    os: "windows"
    capabilities: ["office", "web"]

Phase 3: Start UFO device agent and connect to Galaxy

bash
# Terminal 1: Start UFO Server on your Windows machine
python -m ufo.server.app --port 5000

# Terminal 2: Start UFO Client (connects to UFO server above)
python -m ufo.client.client --ws --ws-server ws://localhost:5000/ws --client-id my_windows --platform windows

# Terminal 3: Start Galaxy (on control machine, can be same or different)
python -m galaxy --request "Cross-device workflow"

Learn More: Migration Guide


Pattern 3: Domain-Specific Split

Strategy: Use different frameworks for different workflow types

Workflow Type Framework Example
Daily desktop tasks UFO² Email processing, document creation
Development workflows Galaxy Code build → test → deploy
Data processing Galaxy (if distributed) Multi-node ML training
Quick automation UFO² One-off tasks

Learn More: When to Use Which


🚫 Common Misconceptions

Misconception 1: "Galaxy is always better because it's newer"

Reality: UFO² is better for simple single-device tasks due to:

  • Lower latency (no network overhead)
  • Simpler setup and debugging
  • Battle-tested stability

Use Galaxy only when you actually need multi-device orchestration.


Misconception 2: "I need to rewrite everything to migrate to Galaxy"

Reality: UFO² can run as a Galaxy device with minimal changes:

bash
# Terminal 1: Start UFO Server
python -m ufo.server.app --port 5000

# Terminal 2: Start UFO Client in WebSocket mode
python -m ufo.client.client --ws --ws-server ws://localhost:5000/ws --client-id my_device --platform windows

Learn More: Migration Guide


Misconception 3: "Galaxy can't run on a single device"

Reality: Galaxy works perfectly on one device if you need:

  • DAG-based workflow planning
  • Advanced monitoring and trajectory reports
  • Preparation for future multi-device expansion
yaml
# Single-device Galaxy setup
devices:
  - device_id: "localhost"
    server_url: "ws://localhost:5005/ws"

Misconception 4: "UFO² is deprecated in favor of Galaxy"

Reality: UFO² is actively maintained and recommended for single-device use:

  • More efficient for local tasks
  • Simpler for beginners
  • Core component when used as Galaxy device

Both frameworks are complementary, not competing.


🎓 Learning Paths

For Beginners

Week 1-2: Start with UFO²

  1. UFO² Quick Start
  2. Build simple automation (file management, email, etc.)
  3. Understand HostAgent/AppAgent architecture

Week 3-4: Explore Advanced UFO²
4. Hybrid GUI-API Actions
5. MCP Server Integration
6. Customization & Learning

Week 5+: Graduate to Galaxy (if needed)
7. Migration Guide
8. Galaxy Quick Start
9. Build cross-device workflows


For Experienced Developers

Direct to Galaxy if you already know you need multi-device:

  1. Galaxy Quick Start
  2. Task Constellation Concepts
  3. ConstellationAgent Deep Dive
  4. Performance Monitoring

📋 Decision Checklist

Still unsure? Answer these questions:

Q1: Does your workflow involve 2+ physical devices?

  • ✅ Yes → Galaxy
  • ❌ No → Continue to Q2

Q2: Do you need parallel execution across different machines?

  • ✅ Yes → Galaxy
  • ❌ No → Continue to Q3

Q3: Does your workflow have complex dependencies (DAG structure)?

  • ✅ Yes, complex DAG → Galaxy
  • ❌ No, simple sequence → Continue to Q4

Q4: Are you comfortable with distributed systems concepts?

  • ✅ Yes → Galaxy (if any of Q1-Q3 is yes)
  • ❌ No → UFO² (learn basics first)

Q5: Do you need cross-platform support (Windows + Linux)?

  • ✅ Yes → Galaxy
  • ❌ No, Windows only → UFO²

Result:


🔗 Next Steps

If you chose UFO²:

  1. 📖 UFO² Quick Start Guide
  2. 🎯 UFO² Overview & Architecture
  3. 🛠️ Configuration Guide

If you chose Galaxy:

  1. 📖 Galaxy Quick Start Guide
  2. 🎯 Galaxy Overview & Architecture
  3. 🌟 Task Constellation Concepts

If you're still exploring:

  1. 📊 Detailed Comparison
  2. 🎬 Demo Video
  3. 📄 Research Paper

💡 Pro Tips

!!! tip "Start Simple"
When in doubt, start with UFO². It's easier to scale up to Galaxy later than to debug a complex Galaxy setup when you don't need it.

!!! tip "Hybrid is Valid"
Don't feel locked into one choice. You can use UFO² for local tasks and Galaxy for cross-device workflows simultaneously.

!!! tip "Test Before Committing"
Try both for a simple workflow to see which feels more natural for your use case:
```bash
# UFO² test
python -m ufo --task "Create test report"

text
# Galaxy test  
python -m galaxy --request "Create test report"
```

!!! warning "Network Requirements"
Galaxy requires stable network connectivity between devices. If your environment has network restrictions, UFO² might be more reliable.


🤝 Getting Help

Still have questions? Check the Migration FAQ or open a discussion on GitHub!


Documents Docs Faq (`documents/docs/faq.md`)

Frequently Asked Questions (FAQ)

Quick answers to common questions about UFO³ Galaxy, UFO², Linux Agents, and general troubleshooting.


🎯 General Questions

Q: What is UFO³?

A: UFO³ is the third iteration of the UFO project, encompassing three major frameworks:

  • UFO² - Desktop AgentOS for Windows automation
  • UFO³ Galaxy - Multi-device orchestration framework
  • Linux Agent - Server and CLI automation for Linux

Q: Why is it called UFO?

A: UFO stands for UI Focused agent. The name was given to the first version of the project and has been retained through all iterations (UFO v1, UFO², UFO³) as the project evolved from a simple UI-focused agent to a comprehensive multi-device orchestration framework.

Q: Which version should I use?

A: Choose based on your needs:

Use Case Recommended Version
Windows desktop automation only UFO²
Cross-device workflows (Windows + Linux) UFO³ Galaxy
Linux server management only Linux Agent
Multi-device orchestration UFO³ Galaxy

Q: What's the difference between UFO² and UFO³ Galaxy?

A: UFO² is for single Windows desktop automation with:

  • Deep Windows OS integration (UIA, Win32, COM)
  • Office application automation
  • GUI + API hybrid execution

UFO³ Galaxy orchestrates multiple devices with:

  • Cross-platform support (Windows + Linux)
  • Distributed task execution
  • Device capability-based routing
  • Constellation-based DAG orchestration

See Migration Guide for details.

Q: Can I use UFO on Linux or macOS?

A: Yes and No:

  • ✅ Linux: Supported via Linux Agent for server/CLI automation
  • ❌ macOS: Not currently supported (Windows and Linux only)
  • Windows: Full UFO² desktop automation support

🔧 Installation & Setup

Q: Which Python version do I need?

A: Python 3.10 or higher is required for all UFO³ components.

bash
# Check your Python version
python --version

Q: What models does UFO support?

A: UFO³ supports multiple LLM providers:

  • OpenAI - GPT-4o, GPT-4, GPT-3.5
  • Azure OpenAI - All Azure-hosted models
  • Google Gemini - Gemini Pro, Gemini Flash
  • Anthropic Claude - Claude 3.5, Claude 3
  • Qwen - Local or API deployment
  • DeepSeek - DeepSeek models
  • Ollama - Local model hosting
  • And more...

See Model Configuration Guide for the complete list and setup instructions.

Q: Can I use non-vision models in UFO?

A: Yes! You can disable visual mode:

yaml
# config/ufo/system.yaml
VISUAL_MODE: false

However, UFO² is designed for vision models. Non-vision models may have reduced performance for GUI automation tasks.

Q: Can I host my own LLM endpoint?

A: Yes! UFO³ supports custom endpoints:

yaml
# config/ufo/agents.yaml
HOST_AGENT:
  API_TYPE: "openai"  # Or compatible API
  API_BASE: "http://your-endpoint.com/v1/chat/completions"
  API_KEY: "your-key"
  API_MODEL: "your-model-name"

See Model Configuration for details.

Q: Do I need API keys for all agents?

A: No, only for LLM-powered agents:

Component Requires API Key Purpose
ConstellationAgent (Galaxy) ✅ Yes Orchestration reasoning
HostAgent (UFO²) ✅ Yes Task planning
AppAgent (UFO²) ✅ Yes Action execution
LinuxAgent ✅ Yes Command planning
Device Server ❌ No Message routing only
MCP Servers ❌ No Tool provider only

⚙️ Configuration

Q: Where are configuration files located?

A: UFO³ uses a modular configuration system in config/:

text
config/
├── ufo/                    # UFO² configuration
│   ├── agents.yaml         # LLM and agent settings
│   ├── system.yaml         # Runtime settings
│   ├── rag.yaml           # Knowledge retrieval
│   └── mcp.yaml           # MCP server configuration
└── galaxy/                 # Galaxy configuration
    ├── agent.yaml          # ConstellationAgent LLM
    ├── devices.yaml        # Device pool
    └── constellation.yaml  # Runtime settings

Q: Can I still use the old `ufo/config/config.yaml`?

A: Yes, for backward compatibility, but we recommend migrating to the new modular system:

bash
# Check current configuration
python -m ufo.tools.validate_config ufo --show-config

# Migrate from legacy to new
python -m ufo.tools.migrate_config

See Configuration Migration Guide for details.

Q: How do I protect my API keys?

A: Best practices for API key security:

  1. Never commit .yaml files with keys - Use .template files

    bash
    # Good pattern
    config/ufo/agents.yaml.template  # Commit this (with placeholders)
    config/ufo/agents.yaml           # DON'T commit (has real keys)
  2. Use environment variables for sensitive data:

    yaml
    # In agents.yaml
    HOST_AGENT:
      API_KEY: ${OPENAI_API_KEY}  # Reads from environment
  3. Add to .gitignore:

    text
    config/**/agents.yaml
    config/**/agent.yaml
    !**/*.template

🌌 UFO³ Galaxy Questions

Q: What's the minimum number of devices for Galaxy?

A: Galaxy requires at least 1 device agent (Windows or Linux) to be useful, but you can start with just one device and add more later.

yaml
# Minimal Galaxy setup (1 device)
devices:
  - device_id: "my_windows_pc"
    server_url: "ws://localhost:5000/ws"
    os: "windows"

Q: Can Galaxy mix Windows and Linux devices?

A: Yes! Galaxy can orchestrate heterogeneous devices:

yaml
devices:
  - device_id: "windows_desktop"
    os: "windows"
    capabilities: ["office", "excel", "outlook"]
    
  - device_id: "linux_server"
    os: "linux"
    capabilities: ["server", "database", "log_analysis"]

Galaxy automatically routes tasks based on device capabilities.

Q: Do all devices need to be on the same network?

A: No, devices can be distributed across networks using SSH tunneling:

  • Same network: Direct WebSocket connections
  • Different networks: Use SSH tunnels (reverse/forward)
  • Cloud + local: SSH tunnels with public gateways

See Linux Quick Start - SSH Tunneling for examples.

Q: How does Galaxy decide which device to use?

A: Galaxy uses capability-based routing:

  1. Analyzes the task requirements
  2. Matches against device capabilities in devices.yaml
  3. Considers device metadata (OS, performance, etc.)
  4. Selects the best-fit device(s)

Example:

yaml
# Task: "Analyze error logs on the production server"
# → Galaxy routes to device with:
capabilities:
  - "log_analysis"
  - "server_management"
os: "linux"

🐧 Linux Agent Questions

Q: Does the Linux Agent require a GUI?

A: No! The Linux Agent is designed for headless servers:

  • Executes CLI commands via MCP
  • No X11/desktop environment needed
  • Works over SSH
  • Perfect for remote servers

Q: Can I run multiple Linux Agents on one machine?

A: Yes, using different ports and client IDs:

bash
# Agent 1
python -m ufo.server.app --port 5001
python -m ufo.client.client --ws --client-id linux_1 --platform linux

# Agent 2 (same machine)
python -m ufo.server.app --port 5002
python -m ufo.client.client --ws --client-id linux_2 --platform linux

Q: What's the MCP service for?

A: The MCP (Model Context Protocol) service provides the actual command execution tools for the Linux Agent:

text
Linux Agent (LLM reasoning)
     ↓
MCP Service (tool provider)
     ↓
Bash commands (actual execution)

Without MCP, the Linux Agent can't execute commands - it can only plan them.


🪟 UFO² Questions

Q: Does UFO² work on Windows 10?

A: Yes! UFO² supports:

  • ✅ Windows 11 (recommended)
  • ✅ Windows 10 (fully supported)
  • ❌ Windows 8.1 or earlier (not tested)

Q: Can UFO² automate Office apps?

A: Yes! UFO² has enhanced Office support through:

  • MCP Office servers - Direct API access to Excel, Word, Outlook, PowerPoint
  • GUI automation - Fallback for unsupported operations
  • Hybrid execution - Automatically chooses API or GUI

Enable MCP in config/ufo/mcp.yaml for better Office automation.

Q: Does UFO² interrupt my work?

A: UFO² can run automation tasks on your current desktop. For non-disruptive operation, you can run it on a separate machine or virtual desktop environment.

Note: Picture-in-Picture mode is planned for future releases.

Q: Can I use UFO² without MCP?

A: UFO² requires MCP (Model Context Protocol) servers for tool execution. MCP provides the interface between the LLM agents and system operations (Windows APIs, Office automation, etc.). Without MCP, UFO² cannot perform actions.


🐛 Common Issues & Troubleshooting

Issue: "Configuration file not found"

Error:

text
FileNotFoundError: config/ufo/agents.yaml not found

Solution:

bash
# Copy template files
cp config/ufo/agents.yaml.template config/ufo/agents.yaml

# Edit with your API keys
notepad config/ufo/agents.yaml  # Windows
nano config/ufo/agents.yaml     # Linux

Issue: "API Authentication Error"

Error:

text
openai.AuthenticationError: Invalid API key

Solutions:

  1. Check API key format:

    yaml
    API_KEY: "sk-..."  # OpenAI starts with sk-
    API_KEY: "..."     # Azure uses deployment key
  2. Verify API_TYPE matches your provider:

    yaml
    API_TYPE: "openai"  # For OpenAI
    API_TYPE: "aoai"    # For Azure OpenAI
  3. Check for extra spaces/quotes in YAML

  4. For Azure: Verify API_DEPLOYMENT_ID is set

Issue: "Connection aborted / Remote end closed connection"

Error:

text
Error making API request: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))

Solutions:

  • Check network connection (VPN, proxy, firewall)
  • Verify LLM endpoint is accessible: curl https://api.openai.com/v1/models
  • Check endpoint status (Azure, OpenAI, etc.)
  • Try increasing timeout in config
  • Verify API base URL is correct

Issue: "Device not connecting to Galaxy"

Error:

text
ERROR - [WS] Failed to connect to ws://localhost:5000/ws
Connection refused

Checklist:

  • Is the server running? (curl http://localhost:5000/api/health)
  • Port number correct? (Server: --port 5000, Client: ws://...:5000/ws)
  • Platform flag set? (--platform windows or --platform linux)
  • Firewall blocking? (Allow port 5000)
  • SSH tunnel established? (If using remote devices)

Issue: "device_id mismatch in Galaxy"

Error:

text
ERROR - Device 'linux_agent_1' not found in configuration

Cause: Mismatch between devices.yaml and client command

Solution: Ensure exact match:

Location Field Example
devices.yaml device_id: "linux_agent_1"
Client command --client-id linux_agent_1

Critical: IDs must match exactly (case-sensitive, no typos).

Issue: "MCP service not responding (Linux)"

Error:

text
ERROR - Cannot connect to MCP server at http://127.0.0.1:8010

Solutions:

  1. Check if MCP service is running:

    bash
    curl http://localhost:8010/health
    ps aux | grep linux_mcp_server
  2. Restart MCP service:

    bash
    pkill -f linux_mcp_server
    python -m ufo.client.mcp.http_servers.linux_mcp_server
  3. Check port conflict:

    bash
    lsof -i :8010
    # If port taken, use different port:
    python -m ufo.client.mcp.http_servers.linux_mcp_server --port 8011

Issue: "Tasks failing after X steps"

Cause: MAX_STEP limit reached

Solution: Increase step limit in config/ufo/system.yaml:

yaml
# Default is 50
MAX_STEP: 100  # For complex tasks

# Or disable limit (not recommended)
MAX_STEP: -1

Issue: "Too many LLM calls / high cost"

Solutions:

  1. Enable action sequences (bundles actions):

    yaml
    # config/ufo/system.yaml
    ACTION_SEQUENCE: true
  2. Use vision-capable models for GUI tasks:

    yaml
    # config/ufo/agents.yaml
    APP_AGENT:
      API_MODEL: "gpt-4o"  # Use vision models for GUI automation

    Note: Non-vision models like gpt-3.5-turbo cannot process screenshots and should not be used for GUI automation tasks.

  3. Enable experience learning (reuse patterns):

    yaml
    # config/ufo/rag.yaml
    RAG_EXPERIENCE: true

Issue: "Why is the latency high?"

A: Latency depends on several factors:

  • LLM response time - GPT-4o typically takes 10-30 seconds per step
  • Network speed - API calls to OpenAI/Azure endpoints
  • Endpoint workload - Provider server load
  • Visual mode - Image processing adds overhead

To reduce latency:

  • Use faster models (gpt-3.5-turbo vs gpt-4o)
  • Enable action sequences to batch operations
  • Use local models (Ollama) if acceptable
  • Disable visual mode if not needed

Issue: "Can I use non-English requests?"

A: Yes! Most modern LLMs support multiple languages:

  • GPT-4o, GPT-4: Excellent multilingual support
  • Gemini: Good multilingual support
  • Qwen: Excellent for Chinese
  • Claude: Good multilingual support

Performance may vary by language and model. Test with your specific language and model combination.


📚 Where to Find More Help

Documentation

Topic Link
Getting Started UFO² Quick Start, Galaxy Quick Start, Linux Quick Start
Configuration Configuration Overview
Troubleshooting Quick start guides have detailed troubleshooting sections
Architecture Project Structure
More Guidance User & Developer Guide

Community & Support

Debugging Tips

  1. Enable debug logging:

    yaml
    # config/ufo/system.yaml
    LOG_LEVEL: "DEBUG"
  2. Check log files:

    text
    logs/<task-name>/
    ├── request.log                    # Request logs
    ├── response.log                   # Response logs
    ├── action_step*.png               # Screenshots at each step
    └── action_step*_annotated.png     # Annotated screenshots
  3. Validate configuration:

    bash
    python -m ufo.tools.validate_config ufo --show-config
    python -m ufo.tools.validate_config galaxy --show-config
  4. Test LLM connectivity:

    python
    # Test your API key
    from openai import OpenAI
    client = OpenAI(api_key="your-key")
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": "Hello"}]
    )
    print(response.choices[0].message.content)

💡 Still have questions? Check the More Guidance page for additional resources, or reach out to the community!


Documents Docs Project Directory Structure (`documents/docs/project_directory_structure.md`)

Project Directory Structure

This repository implements UFO³, a multi-tier AgentOS architecture spanning from single-device automation (UFO²) to cross-device orchestration (Galaxy). This document provides an overview of the directory structure to help you understand the codebase organization.

New to UFO³? Start with the Documentation Home for an introduction and Quick Start Guide to get up and running.

Architecture Overview:

  • 🌌 Galaxy: Multi-device DAG-based orchestration framework that coordinates agents across different platforms
  • 🎯 UFO²: Single-device Windows desktop agent system that can serve as Galaxy's sub-agent
  • 🔌 AIP: Agent Integration Protocol for cross-device communication
  • ⚙️ Modular Configuration: Type-safe configs in config/galaxy/ and config/ufo/

📦 Root Directory Structure

text
UFO/
├── galaxy/                 # 🌌 Multi-device orchestration framework
├── ufo/                    # 🎯 Desktop AgentOS (can be Galaxy sub-agent)
├── config/                 # ⚙️ Modular configuration system
├── aip/                    # 🔌 Agent Integration Protocol
├── documents/              # 📖 MkDocs documentation site
├── vectordb/               # 🗄️ Vector database for RAG
├── learner/                # 📚 Help document indexing tools
├── record_processor/       # 🎥 Human demonstration parser
├── dataflow/               # 📊 Data collection pipeline
├── model_worker/           # 🤖 Custom LLM deployment tools
├── logs/                   # 📝 Execution logs (auto-generated)
├── scripts/                # 🛠️ Utility scripts
├── tests/                  # 🧪 Unit and integration tests
└── requirements.txt        # 📦 Python dependencies

🌌 Galaxy Framework (`galaxy/`)

The cross-device orchestration framework that transforms natural language requests into executable DAG workflows distributed across heterogeneous devices.

Directory Structure

text
/* Detailed source-code truncated for AI context efficiency. */

Key Components

Component Description Documentation
ConstellationAgent AI-powered agent that generates and modifies task DAGs Galaxy Overview
TaskConstellation DAG container with validation and state management Constellation
TaskOrchestrator Event-driven execution coordinator Constellation Orchestrator
DeviceManager Multi-device coordination and assignment Device Manager
Visualization Rich console DAG monitoring Galaxy Overview

Galaxy Documentation:


🎯 UFO² Desktop AgentOS (`ufo/`)

Single-device desktop automation system implementing a two-tier agent architecture (HostAgent + AppAgent) with hybrid GUI-API automation.

Directory Structure

text
/* Detailed source-code truncated for AI context efficiency. */

Key Components

Component Description Documentation
HostAgent Desktop-level orchestration with 7-state FSM HostAgent Overview
AppAgent Application-level execution with 6-state FSM AppAgent Overview
MCP System Extensible command execution framework MCP Overview
Automator Hybrid GUI-API automation with fallback Core Features
RAG Knowledge retrieval from multiple sources Knowledge Substrate

UFO² Documentation:


🔌 Agent Integration Protocol (`aip/`)

Standardized message passing protocol for cross-device communication between Galaxy and UFO² agents.

text
aip/
├── messages.py             # Message types (Command, Result, Event, Error)
├── protocol/               # Protocol definitions
├── transport/              # Transport layers (HTTP, WebSocket, MQTT)
├── endpoints/              # API endpoints
├── extensions/             # Protocol extensions
└── resilience/             # Retry and error handling

Purpose: Enables Galaxy to coordinate UFO² agents running on different devices and platforms through standardized messaging over HTTP/WebSocket.

Documentation: See AIP Overview for protocol details and Message Types for message specifications.


🐧 Linux Agent

Lightweight CLI-based agent for Linux devices that integrates with Galaxy as a third-party device agent.

Key Features:

  • CLI Execution: Execute shell commands on Linux systems
  • Galaxy Integration: Register as device in Galaxy's multi-device orchestration
  • Simple Architecture: Minimal dependencies, easy deployment
  • Cross-Platform Tasks: Enable Windows + Linux workflows in Galaxy

Configuration: Configured in config/ufo/third_party.yaml under THIRD_PARTY_AGENT_CONFIG.LinuxAgent

Linux Agent Documentation:


📱 Mobile Agent

Android device automation agent that enables UI automation, app control, and mobile-specific operations through ADB integration.

Key Features:

  • UI Automation: Touch, swipe, and text input via ADB
  • Visual Context: Screenshot capture and UI hierarchy analysis
  • App Management: Launch apps, navigate between applications
  • Galaxy Integration: Serve as mobile device in cross-platform workflows
  • Platform Support: Android devices (physical and emulators)

Configuration: Configured in config/ufo/third_party.yaml under THIRD_PARTY_AGENT_CONFIG.MobileAgent

Mobile Agent Documentation:


⚙️ Configuration (`config/`)

Modular configuration system with type-safe schemas and auto-discovery.

text
config/
├── galaxy/                 # Galaxy configuration
│   ├── agent.yaml.template     # ConstellationAgent LLM settings template
│   ├── agent.yaml              # ConstellationAgent LLM settings (active)
│   ├── constellation.yaml      # Constellation orchestration settings
│   ├── devices.yaml            # Multi-device registry
│   └── dag_templates/          # Pre-built DAG templates (future)
│
├── ufo/                    # UFO² configuration
│   ├── agents.yaml.template    # Agent LLM configs template
│   ├── agents.yaml             # Agent LLM configs (active)
│   ├── system.yaml             # System settings
│   ├── rag.yaml                # RAG settings
│   ├── mcp.yaml                # MCP server configs
│   ├── third_party.yaml        # Third-party agent configs (LinuxAgent, etc.)
│   └── prices.yaml             # API pricing data
│
├── config_loader.py        # Auto-discovery config loader
└── config_schemas.py       # Pydantic validation schemas

Configuration Files:

  • Template files (.yaml.template) should be copied to .yaml and edited
  • Active config files (.yaml) contain API keys and should NOT be committed
  • Galaxy: Uses config/galaxy/agent.yaml for ConstellationAgent LLM settings
  • UFO²: Uses config/ufo/agents.yaml for HostAgent/AppAgent LLM settings
  • Third-Party: Configure LinuxAgent and HardwareAgent in config/ufo/third_party.yaml
  • Use python -m ufo.tools.convert_config to migrate from legacy configs

Configuration Documentation:


📖 Documentation (`documents/`)

MkDocs documentation site with comprehensive guides and API references.

text
documents/
├── docs/                   # Markdown documentation source
│   ├── getting_started/    # Installation and quick starts
│   ├── galaxy/             # Galaxy framework docs
│   ├── ufo2/               # UFO² architecture docs
│   ├── linux/              # Linux agent documentation
│   ├── mcp/                # MCP server documentation
│   ├── aip/                # Agent Interaction Protocol docs
│   ├── configuration/      # Configuration guides
│   ├── infrastructure/     # Core infrastructure (agents, modules)
│   ├── server/             # Server-client architecture docs
│   ├── client/             # Client components docs
│   ├── tutorials/          # Step-by-step tutorials
│   ├── modules/            # Module-specific docs
│   └── about/              # Project information
│
├── mkdocs.yml              # MkDocs configuration
└── site/                   # Generated static site

Documentation Sections:

Section Description
Getting Started Installation, quick starts, migration guides
Galaxy Multi-device orchestration, DAG workflows, device management
UFO² Desktop agents, automation features, benchmarks
Linux Linux agent integration, CLI executor for Galaxy
MCP Server documentation, custom server development
AIP Agent Interaction Protocol, message types, transport layers
Configuration System settings, model configs, deployment
Infrastructure Core components, agent design, server-client architecture
Tutorials Creating agents, custom automators, advanced usage

🗄️ Supporting Modules

VectorDB (`vectordb/`)

Vector database storage for RAG knowledge sources (help documents, execution traces, user demonstrations). See RAG Configuration for setup details.

Learner (`learner/`)

Tools for indexing help documents into vector database for RAG retrieval. Integrates with the Knowledge Substrate feature.

Record Processor (`record_processor/`)

Parses human demonstrations from Windows Step Recorder for learning from user actions.

Dataflow (`dataflow/`)

Data collection pipeline for Large Action Model (LAM) training. See the Dataflow documentation for workflow details.

Model Worker (`model_worker/`)

Custom LLM deployment tools for running local models. See Model Configuration for supported providers.

Logs (`logs/`)

Auto-generated execution logs organized by task and timestamp, including screenshots, UI trees, and agent actions.


🎯 Galaxy vs UFO² vs Linux Agent vs Mobile Agent: When to Use What?

Aspect Galaxy UFO² Linux Agent Mobile Agent
Scope Multi-device orchestration Single-device Windows automation Single-device Linux CLI Single-device Android automation
Use Cases Cross-platform workflows, distributed tasks Desktop automation, Office tasks Server management, CLI operations Mobile app testing, UI automation
Architecture DAG-based task workflows Two-tier state machines Simple CLI executor UI automation via ADB
Platform Orchestrator (platform-agnostic) Windows Linux Android
Complexity Complex multi-step workflows Simple to moderate tasks Simple command execution UI interaction and app control
Best For Cross-device collaboration Windows desktop tasks Linux server operations Mobile app automation
Integration Orchestrates all agents Can be Galaxy device Can be Galaxy device Can be Galaxy device

Choosing the Right Framework:

  • Use Galaxy when: Tasks span multiple devices/platforms, complex workflows with dependencies
  • Use UFO² Standalone when: Single-device Windows automation, rapid prototyping
  • Use Linux Agent when: Linux server/CLI operations needed in Galaxy workflows
  • Use Mobile Agent when: Android device automation, mobile app testing, UI interactions
  • Best Practice: Galaxy orchestrates UFO² (Windows) + Linux Agent (Linux) + Mobile Agent (Android) for comprehensive cross-platform tasks

🚀 Quick Start

Galaxy Multi-Device Orchestration

bash
# Interactive mode
python -m galaxy --interactive

# Single request
python -m galaxy --request "Your cross-device task"

Documentation: Galaxy Quick Start

UFO² Desktop Automation

bash
# Interactive mode
python -m ufo --task <task_name>

# With custom config
python -m ufo --task <task_name> --config_path config/ufo/

Documentation: UFO² Quick Start


Getting Started

Galaxy Framework

UFO² Desktop AgentOS

Linux Agent

Mobile Agent

MCP System

Agent Integration Protocol

Configuration


🏗️ Architecture Principles

UFO³ follows SOLID principles and established software engineering patterns:

  • Single Responsibility: Each component has a focused purpose
  • Open/Closed: Extensible through interfaces and plugins
  • Interface Segregation: Focused interfaces for different capabilities
  • Dependency Inversion: Dependency injection for loose coupling
  • Event-Driven: Observer pattern for real-time monitoring
  • State Machines: Well-defined states and transitions for agents
  • Command Pattern: Encapsulated DAG editing with undo/redo

📝 Additional Resources


Next Steps:

  1. Start with Galaxy Quick Start for multi-device orchestration
  2. Or explore UFO² Quick Start for single-device automation
  3. Check FAQ for common questions
  4. Join our community and contribute!

Documents Docs About CODE OF CONDUCT (`documents/docs/about/CODE_OF_CONDUCT.md`)

Microsoft Open Source Code of Conduct

This project has adopted the Microsoft Open Source Code of Conduct.

Resources:


Documents Docs About CONTRIBUTING (`documents/docs/about/CONTRIBUTING.md`)

Contributing

This project welcomes contributions and suggestions. Most contributions require you to
agree to a Contributor License Agreement (CLA) declaring that you have the right to,
and actually do, grant us the rights to use your contribution. For details, visit
https://cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether you need
to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the
instructions provided by the bot. You will only need to do this once across all repositories using our CLA.

!!! note
You should sunmit your pull request to the pre-release branch, not the main branch.

This project has adopted the Microsoft Open Source Code of Conduct.
For more information see the Code of Conduct FAQ
or contact [email protected] with any additional questions or comments.


Documents Docs About DISCLAIMER (`documents/docs/about/DISCLAIMER.md`)

Disclaimer: Code Execution and Data Handling Notice

By choosing to run the provided code, you acknowledge and agree to the following terms and conditions regarding the functionality and data handling practices:

1. Code Functionality:

The code you are about to execute has the capability to capture screenshots of your working desktop environment and active applications. These screenshots will be processed and sent to the GPT model for inference.

2. Data Privacy and Storage:

It is crucial to note that Microsoft, the provider of this code, explicitly states that it does not collect or save any of the transmitted data. The captured screenshots are processed in real-time for the purpose of inference, and no permanent storage or record of this data is retained by Microsoft.

3. User Responsibility:

By running the code, you understand and accept the responsibility for the content and nature of the data present on your desktop during the execution period. It is your responsibility to ensure that no sensitive or confidential information is visible or captured during this process.

4. Security Measures:

Microsoft has implemented security measures to safeguard the action execution. However, it is recommended that you run the code in a secure and controlled environment to minimize potential risks. Ensure that you are running the latest security updates on your system.

You explicitly provide consent for the GPT model to analyze the captured screenshots for the purpose of generating relevant outputs. This consent is inherent in the act of executing the code.

6. No Guarantee of Accuracy:

The outputs generated by the GPT model are based on patterns learned during training and may not always be accurate or contextually relevant. Microsoft does not guarantee the accuracy or suitability of the inferences made by the model.

7. Indemnification:

Users agree to defend, indemnify, and hold Microsoft harmless from and against all damages, costs, and attorneys' fees in connection with any claims arising from the use of this Repo.

8. Reporting Infringements:

If anyone believes that this Repo infringes on their rights, please notify the project owner via the provided project owner email. Microsoft will investigate and take appropriate actions as necessary.

9. Modifications to the Disclaimer:

Microsoft reserves the right to update or modify this disclaimer at any time without prior notice. It is your responsibility to review the disclaimer periodically for any changes.

By proceeding to execute the code, you acknowledge that you have read, understood, and agreed to the terms outlined in this disclaimer. If you do not agree with these terms, refrain from running the provided code.


Documents Docs About SUPPORT (`documents/docs/about/SUPPORT.md`)

Support

How to file issues and get help

This project uses GitHub Issues to track bugs and feature requests. Please search the existing
issues before filing new issues to avoid duplicates. For new issues, file your bug or
feature request as a new Issue.

You may use GitHub Issues to raise questions, bug reports, and feature requests.

For help and questions about using this project, please please contact [email protected].

Microsoft Support Policy

Support for this PROJECT or PRODUCT is limited to the resources listed above.


Documents Docs Aip Endpoints (`documents/docs/aip/endpoints.md`)

AIP Endpoints

Endpoints combine protocol, transport, and resilience components to provide production-ready AIP communication for servers, clients, and orchestrators.

Endpoint Types at a Glance

Endpoint Type Role Used By Key Features
DeviceServerEndpoint Server Device Agent Service ✅ Multiplexed connections
✅ Session management
✅ Task dispatching
✅ Result aggregation
DeviceClientEndpoint Client Device Agent Client ✅ Auto-reconnection
✅ Heartbeat management
✅ Command execution
✅ Telemetry reporting
ConstellationEndpoint Orchestrator ConstellationClient ✅ Multi-device coordination
✅ Task distribution
✅ Device info querying
✅ Connection pooling

Endpoint Architecture

Endpoint Inheritance Hierarchy:

AIP provides three specialized endpoint implementations that all inherit common functionality from a shared base class:

mermaid
graph TB
    Base[AIPEndpoint Base]
    Base --> Server[DeviceServerEndpointServer-Side]
    Base --> Client[DeviceClientEndpointClient-Side]
    Base --> Constellation[ConstellationEndpointOrchestrator]
    
    Base -.->|Protocol| P[Message Handling]
    Base -.->|Resilience| R[Reconnection + Heartbeat]
    Base -.->|Sessions| S[State Tracking]
    
    style Base fill:#e1f5ff
    style Server fill:#fff4e1
    style Client fill:#f0ffe1
    style Constellation fill:#ffe1f5

The dashed arrows indicate capabilities that the base class provides to all subclasses. This inheritance design ensures consistent behavior across all endpoint types while allowing specialization for server, client, and orchestrator roles.

Base Endpoint Components:

All endpoints inherit from AIPEndpoint, which provides:

  • Protocol: Message serialization and handling
  • Reconnection Strategy: Automatic reconnection with backoff
  • Timeout Manager: Operation timeout management
  • Session Handlers: Per-session state tracking

Base Endpoint: AIPEndpoint

Common Methods

Method Purpose Example Usage
start() Start endpoint await endpoint.start()
stop() Stop endpoint await endpoint.stop()
is_connected() Check connection if endpoint.is_connected(): ...
send_with_timeout() Send with timeout await endpoint.send_with_timeout(msg, 30.0)
receive_with_timeout() Receive with timeout msg = await endpoint.receive_with_timeout(ServerMessage, 60.0)

Basic Usage Pattern:

python
from aip.endpoints.base import AIPEndpoint

# Start endpoint
await endpoint.start()

# Check connection
if endpoint.is_connected():
    await endpoint.handle_message(msg)

# Send with timeout
await endpoint.send_with_timeout(msg, timeout=30.0)

# Clean shutdown
await endpoint.stop()

DeviceServerEndpoint

Wraps UFO's server-side WebSocket handler with AIP protocol support for managing multiple device connections simultaneously.

Configuration

python
from aip.endpoints import DeviceServerEndpoint

endpoint = DeviceServerEndpoint(
    ws_manager=ws_manager,              # WebSocket connection manager
    session_manager=session_manager,    # Session state manager
    local=False                         # Local vs remote deployment
)

Integration with FastAPI

python
from fastapi import FastAPI, WebSocket
from aip.endpoints import DeviceServerEndpoint

app = FastAPI()
endpoint = DeviceServerEndpoint(ws_manager, session_manager)

@app.websocket("/ws")
async def websocket_route(websocket: WebSocket):
    await endpoint.handle_websocket(websocket)

Key Features

Feature Description Benefit
Multiplexed Connections Handle multiple clients simultaneously Scale to many devices
Session Management Track active sessions per device Maintain conversation context
Task Dispatching Route tasks to appropriate clients Targeted execution
Result Aggregation Collect and format execution results Unified response handling
Auto Task Cancellation Cancel tasks on disconnect Prevent orphaned tasks

Backward Compatibility:

The Device Server Endpoint maintains full compatibility with UFO's existing WebSocket handler.

Task Cancellation on Disconnection

python
# Automatically called when device disconnects
await endpoint.cancel_device_tasks(
    device_id="device_001",
    reason="device_disconnected"
)

DeviceClientEndpoint

Wraps UFO's client-side WebSocket client with AIP protocol support, automatic reconnection, and heartbeat management.

Configuration

python
from aip.endpoints import DeviceClientEndpoint

endpoint = DeviceClientEndpoint(
    ws_url="ws://localhost:8000/ws",
    ufo_client=ufo_client,
    max_retries=3,
    timeout=120.0
)

Automatic Features

Feature Default Behavior Configuration
Heartbeat Starts on connection 20s interval (fixed)
Reconnection Exponential backoff max_retries=3, initial_backoff=2.0
Message Routing Auto-routes to UFO client Handled internally
Connection Management Auto-connect on start Transparent to user

Lifecycle Management Example:

python
# Start and connect
await endpoint.start()

# Handle messages automatically
# (routed to underlying UFO client)

# Stop heartbeat and close
await endpoint.stop()

Reconnection Strategy

python
from aip.resilience import ReconnectionStrategy

reconnection_strategy = ReconnectionStrategy(
    max_retries=3,
    initial_backoff=2.0,
    max_backoff=60.0
)

endpoint = DeviceClientEndpoint(
    ws_url=url,
    ufo_client=client,
    reconnection_strategy=reconnection_strategy
)

ConstellationEndpoint

Enables the ConstellationClient to communicate with multiple devices simultaneously, managing connections, tasks, and queries.

Configuration

python
from aip.endpoints import ConstellationEndpoint

endpoint = ConstellationEndpoint(
    task_name="multi_device_task",
    message_processor=processor  # Optional custom processor
)

Multi-Device Operations

Operation Method Description
Connect connect_to_device() Establish connection to device
Send Task send_task_to_device() Dispatch task to specific device
Query Info request_device_info() Get device telemetry
Check Status is_device_connected() Verify connection health
Disconnect disconnect_device() Close device connection
Disconnect All stop() Shutdown all connections

Connecting to Devices

python
# Connect using AgentProfile
connection = await endpoint.connect_to_device(
    device_info=agent_profile,  # AgentProfile object
    message_processor=processor
)

Learn more about AgentProfile configuration in the Galaxy documentation.

Sending Tasks

python
# Dispatch task to specific device
result = await endpoint.send_task_to_device(
    device_id="device_001",
    task_request={
        "request": "Open Notepad",
        "task_name": "open_notepad",
        "session_id": "session_123"
    }
)

Querying Device Info

python
# Request telemetry update
device_info = await endpoint.request_device_info("device_001")

if device_info:
    print(f"OS: {device_info['os']}")
    print(f"CPU: {device_info['cpu']}")
    print(f"GPU: {device_info.get('gpu', 'N/A')}")

Connection Management

Managing Multiple Devices:

python
# Check connection before sending
if endpoint.is_device_connected("device_001"):
    await endpoint.send_task_to_device(...)

# Disconnect specific device
await endpoint.disconnect_device("device_001")

# Disconnect all devices
await endpoint.stop()

Disconnection Handling

python
# Automatically triggered on device disconnect
await endpoint.on_device_disconnected("device_001")

# Cancels pending tasks
await endpoint.cancel_device_tasks(
    device_id="device_001",
    reason="device_disconnected"
)

# Attempts reconnection (if enabled)
success = await endpoint.reconnect_device("device_001")

Endpoint Lifecycle Patterns

Server Lifecycle

Server Endpoint State Transitions:

This state diagram shows the lifecycle of a server endpoint from initialization through connection handling to shutdown:

mermaid
stateDiagram-v2
    [*] --> Initialize: Create endpoint
    Initialize --> Started: start()
    Started --> Listening: Accept connections
    Listening --> Handling: Handle WebSocket
    Handling --> Listening: Connection closed
    Listening --> Stopped: stop()
    Stopped --> [*]

The Listening → Handling loop represents the server accepting multiple client connections. Each connection is handled independently while the server remains in the listening state.

Server Lifecycle Code:

python
# 1. Initialize
endpoint = DeviceServerEndpoint(client_manager, session_manager)

# 2. Start
await endpoint.start()

# 3. Handle connections
@app.websocket("/ws")
async def handle_ws(websocket: WebSocket):
    await endpoint.handle_websocket(websocket)

# 4. Stop (on shutdown)
await endpoint.stop()

Client Lifecycle

Client Endpoint State Transitions with Auto-Reconnection:

This diagram shows the client lifecycle including automatic reconnection attempts when the connection is lost:

mermaid
stateDiagram-v2
    [*] --> Initialize: Create endpoint
    Initialize --> Connecting: start()
    Connecting --> Connected: Connection established
    Connected --> Heartbeat: Auto-start heartbeat
    Heartbeat --> Handling: Handle messages
    Handling --> Heartbeat: Continue
    Heartbeat --> Reconnecting: Connection lost
    Reconnecting --> Connected: Reconnect successful
    Reconnecting --> Stopped: Max retries
    Connected --> Stopped: stop()
    Stopped --> [*]

The Heartbeat → Handling loop represents normal operation with periodic heartbeats. The Reconnecting → Connected transition shows automatic recovery from network failures.

Client Lifecycle Code:

python
# 1. Initialize
endpoint = DeviceClientEndpoint(ws_url, ufo_client)

# 2. Connect
await endpoint.start()

# 3. Handle messages (automatic)
# UFO client receives and processes messages

# 4. Disconnect
await endpoint.stop()

Constellation Lifecycle

Constellation Lifecycle Code:

python
# 1. Initialize
endpoint = ConstellationEndpoint(task_name)

# 2. Start
await endpoint.start()

# 3. Connect to devices
await endpoint.connect_to_device(device_info1)
await endpoint.connect_to_device(device_info2)

# 4. Send tasks
await endpoint.send_task_to_device(device_id, task_request)

# 5. Cleanup (disconnects all devices)
await endpoint.stop()

Resilience Features

!!!warning "Built-In Resilience"
All endpoints include automatic reconnection, timeout management, and heartbeat monitoring for production reliability.

Resilience Configuration

Component Configuration Purpose
Reconnection ReconnectionStrategy Auto-reconnect with backoff
Timeout TimeoutManager Enforce operation timeouts
Heartbeat HeartbeatManager Monitor connection health

Configuring Resilience:

python
from aip.resilience import ReconnectionStrategy, ReconnectionPolicy

strategy = ReconnectionStrategy(
    max_retries=5,
    initial_backoff=1.0,
    max_backoff=60.0,
    backoff_multiplier=2.0,
    policy=ReconnectionPolicy.EXPONENTIAL_BACKOFF
)

endpoint = DeviceClientEndpoint(
    ws_url=url,
    ufo_client=client,
    reconnection_strategy=strategy
)

Timeout Operations

python
# Send with custom timeout
await endpoint.send_with_timeout(msg, timeout=30.0)

# Receive with custom timeout
msg = await endpoint.receive_with_timeout(ServerMessage, timeout=60.0)

→ See detailed resilience documentation


Error Handling Patterns

Connection Errors

python
try:
    await endpoint.start()
except ConnectionError as e:
    logger.error(f"Failed to connect: {e}")
    # Reconnection handled automatically if enabled

Task Execution Errors

python
try:
    result = await endpoint.send_task_to_device(device_id, task)
except TimeoutError:
    logger.error("Task execution timeout")
except Exception as e:
    logger.error(f"Task failed: {e}")

Custom Disconnection Handling

python
class CustomEndpoint(DeviceClientEndpoint):
    async def on_device_disconnected(self, device_id: str) -> None:
        logger.warning(f"Device {device_id} disconnected")
        
        # Custom cleanup logic
        await self.custom_cleanup(device_id)
        
        # Call parent implementation
        await super().on_device_disconnected(device_id)

Best Practices

Endpoint Selection:

Use Case Endpoint Type
Device agent server DeviceServerEndpoint
Device agent client DeviceClientEndpoint
Multi-device orchestrator ConstellationEndpoint

!!!warning "Configuration Guidelines"
- Set appropriate timeouts based on deployment environment
- Configure reconnection based on network reliability
- Monitor connection health with is_connected() checks
- Implement custom handlers for application-specific cleanup

!!!success "Resource Management"
- Always call stop() during shutdown to prevent leaks
- Use message processors for custom message handling
- Handle disconnections with on_device_disconnected overrides

Custom Message Processor:

python
class MyProcessor:
    async def process_message(self, msg):
        # Custom processing
        logger.info(f"Processing: {msg.type}")
        # ...

endpoint = ConstellationEndpoint(
    task_name="task",
    message_processor=MyProcessor()
)

Quick Reference

Import Endpoints

python
from aip.endpoints import (
    AIPEndpoint,           # Base class
    DeviceServerEndpoint,  # Server-side
    DeviceClientEndpoint,  # Client-side
    ConstellationEndpoint, # Orchestrator-side
)

Documents Docs Aip Messages (`documents/docs/aip/messages.md`)

AIP Message Reference

AIP uses Pydantic-based messages for automatic validation, serialization, and type safety. All messages transmit as JSON over WebSocket.

Message Overview

Bidirectional Communication

Message Flow Overview:

This diagram illustrates all message types and their directions in the AIP protocol, showing how clients and servers communicate bidirectionally:

mermaid
graph LR
    Client[Device Client]
    Server[Device Service]
    
    Client -->|REGISTER| Server
    Client -->|COMMAND_RESULTS| Server
    Client -->|TASK_END| Server
    Client -->|HEARTBEAT| Server
    
    Server -->|TASK| Client
    Server -->|COMMAND| Client
    Server -->|HEARTBEAT| Client
    Server -->|TASK_END| Client
    
    Client <-->|DEVICE_INFO| Server
    Client <-->|ERROR| Server
    
    style Client fill:#f0ffe1
    style Server fill:#fff4e1

Unidirectional arrows indicate request-response patterns, while bidirectional arrows (<-->) indicate messages that can be initiated by either party. Note that both HEARTBEAT and TASK_END can flow in both directions depending on the scenario.

Message Types Quick Reference

Direction Message Type Purpose Key Fields
Client → Server
REGISTER Initial capability advertisement client_id, metadata
COMMAND_RESULTS Return command execution results action_results, prev_response_id
TASK_END Notify task completion status, session_id
HEARTBEAT Keepalive signal client_id
Server → Client
TASK Task assignment user_request, task_name
COMMAND Command execution request actions, response_id
HEARTBEAT Keepalive acknowled