Newer
Older
copilot / bin / agent
#!/usr/bin/env python3
"""
Local AI Agent - Unified Interface
Integrates DeepSeek + Ollama with auto shell execution
"""

import os
import sys
import json
import subprocess
import logging
from datetime import datetime
from pathlib import Path

# Setup logging
LOG_DIR = Path("/opt/local-agent/logs")
LOG_DIR.mkdir(parents=True, exist_ok=True)
logging.basicConfig(
    level=logging.INFO,
    format='[%(asctime)s] %(levelname)s: %(message)s',
    handlers=[
        logging.FileHandler(LOG_DIR / "agent.log"),
        logging.StreamHandler()
    ]
)
log = logging.getLogger(__name__)

class LocalAgent:
    def __init__(self):
        self.deepseek_bin = "/root/.local/bin/deepseek"
        self.ollama_url = "http://localhost:11434"
        self.dangerous_patterns = [
            "rm -rf /", "mkfs", "dd if=/dev/zero", ":(){:|:&};"
        ]
    
    def is_safe(self, command: str) -> bool:
        """Check if command is safe to execute"""
        for pattern in self.dangerous_patterns:
            if pattern in command:
                log.warning(f"BLOCKED: {command} - dangerous pattern")
                return False
        return True
    
    def execute_shell(self, cmd: str) -> dict:
        """Execute shell command safely"""
        if not self.is_safe(cmd):
            return {"error": "Command blocked for safety", "code": 1}
        
        log.info(f"EXEC: {cmd}")
        try:
            result = subprocess.run(
                cmd, shell=True, capture_output=True, 
                text=True, timeout=300
            )
            return {
                "stdout": result.stdout,
                "stderr": result.stderr,
                "code": result.returncode
            }
        except subprocess.TimeoutExpired:
            return {"error": "Command timeout", "code": 124}
        except Exception as e:
            return {"error": str(e), "code": 1}
    
    def ask_deepseek(self, question: str) -> dict:
        """Ask DeepSeek a question"""
        log.info(f"DEEPSEEK: {question}")
        try:
            result = subprocess.run(
                [self.deepseek_bin, "-q", question, "--json"],
                capture_output=True, text=True, timeout=60
            )
            if result.returncode == 0:
                return json.loads(result.stdout)
            return {"error": result.stderr}
        except Exception as e:
            return {"error": str(e)}
    
    def run(self, args):
        """Main entry point"""
        if not args or args[0] == "-h":
            print("""
Local AI Agent v1.0
Usage:
  agent [--deepseek] <question>     # Ask DeepSeek
  agent [--exec] <command>          # Execute shell command
  agent [--status]                  # Show service status
  agent [--logs]                    # Tail agent logs
            """)
            return
        
        if args[0] in ["--deepseek", "-d"]:
            result = self.ask_deepseek(" ".join(args[1:]))
            print(json.dumps(result, indent=2))
        elif args[0] in ["--exec", "-e"]:
            result = self.execute_shell(" ".join(args[1:]))
            print(json.dumps(result, indent=2))
        elif args[0] in ["--status", "-s"]:
            self.show_status()
        elif args[0] in ["--logs", "-l"]:
            subprocess.run(["tail", "-f", str(LOG_DIR / "agent.log")])
        else:
            # Default: execute as command
            result = self.execute_shell(" ".join(args))
            if result.get("stdout"):
                print(result["stdout"])
            if result.get("stderr"):
                print(result["stderr"], file=sys.stderr)
            sys.exit(result.get("code", 1))
    
    def show_status(self):
        """Show service status"""
        subprocess.run([
            "systemctl", "status", 
            "ollama", "local-agent", "ssh", 
            "--no-pager"
        ])

if __name__ == "__main__":
    agent = LocalAgent()
    agent.run(sys.argv[1:])