File size: 4,298 Bytes
d7a146b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21849be
 
 
 
 
 
 
 
 
 
 
d7a146b
 
 
 
 
 
 
 
21849be
 
 
d7a146b
 
9e40862
 
 
 
 
 
 
 
 
d7a146b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#!/usr/bin/env python3
"""
OpenClaw Agent Army - Hugging Face Spaces Entry Point
"""

import os
import sys
import time
import subprocess
from pathlib import Path

# Set environment
os.environ['OPENCLAWDIR'] = '/app/.openclaw'

def check_and_install_deps():
    """Check and install missing dependencies"""
    print("πŸ” Checking dependencies...")
    
    # Check if we're in the correct directory
    if not os.path.exists('supervisor.py'):
        print("❌ Not in the correct directory. supervisor.py not found.")
        return False
    
    # Create .openclaw structure if missing
    os.makedirs('.openclaw', exist_ok=True)
    os.makedirs('.openclaw/workspace', exist_ok=True)
    os.makedirs('.openclaw/agents', exist_ok=True)
    
    # Copy config to .openclaw if needed
    if os.path.exists('config.json') and not os.path.exists('.openclaw/workspace/config.json'):
        import shutil
        shutil.copy('config.json', '.openclaw/workspace/config.json')
    
    # Copy agent files
    if os.path.exists('agent_army/agents') and not os.path.exists('.openclaw/agents/gig1'):
        import shutil
        for agent_file in Path('agent_army/agents').glob('*.py'):
            if agent_file.name not in ['__init__.py', 'common.py']:
                shutil.copy(agent_file, f'.openclaw/agents/{agent_file.name}')
    
    # Copy skills
    if os.path.exists('skills') and not os.path.exists('.openclaw/workspace/skills'):
        import shutil
        shutil.copytree('skills', '.openclaw/workspace/skills', dirs_exist_ok=True)
    
    return True

def start_agent_supervisor():
    """Start the agent supervisor"""
    print("πŸš€ Starting Agent Army Supervisor...")
    
    # Check if openclaw command exists
    try:
        subprocess.run(['openclaw', '--version'], capture_output=True, check=True)
        # Use openclaw CLI if available
        os.system('openclaw gateway --port 7860 --host 0.0.0.0')
    except (subprocess.CalledProcessError, FileNotFoundError):
        # Fall back to direct supervisor
        os.system('python3 supervisor.py')

def start_xvfb():
    """Start Xvfb for headless Chrome"""
    try:
        print("πŸ–₯️  Starting Xvfb virtual display...")
        subprocess.Popen(['Xvfb', ':99', '-screen', '0', '1920x1080x24', '-nolisten', 'tcp', '-fbdir', '/var/tmp'])
        time.sleep(2)  # Give Xvfb time to start
        print("βœ… Xvfb started")
    except Exception as e:
        print(f"⚠️  Xvfb start failed: {e}")
        print("⚠️  Chrome may not work without virtual display")

def main():
    print("=" * 50)
    print("OPENCLAW AGENT ARMY - HUGGING FACE SPACE")
    print("=" * 50)
    
    # Check Python version
    print(f"Python version: {sys.version}")
    
    # Start Xvfb for headless Chrome (must be before agents)
    start_xvfb()
    
    # Install dependencies if needed
    print("πŸ“¦ Ensuring dependencies are installed...")
    try:
        subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', 
                       '--upgrade', 'pip'], check=False, timeout=60)
        subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', '-r', 'requirements.txt'], 
                       check=False, timeout=120)
    except subprocess.TimeoutExpired:
        print("⚠️  pip install timed out, continuing...")
    except Exception as e:
        print(f"⚠️  pip install error: {e}, continuing...")
    
    # Check structure
    if not check_and_install_deps():
        print("❌ Setup failed. Check logs.")
        sys.exit(1)
    
    print("βœ… Setup complete")
    print("\nπŸ“Š Agent Status:")
    
    # Check for running agents
    try:
        result = subprocess.run(['ps', 'aux'], capture_output=True, text=True)
        agent_count = result.stdout.count('gig_real.py') + result.stdout.count('trading_real.py')
        print(f"   Active agent processes: {agent_count}")
    except:
        pass
    
    print("\n🌐 Starting services...")
    
    # Start supervisor in foreground
    start_agent_supervisor()

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\nπŸ‘‹ Shutting down...")
        sys.exit(0)
    except Exception as e:
        print(f"❌ Error: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)