Newer
Older
cortex-hub / agent-node / agent_node / main.py
import sys
import os

# Add root to path to find protos and other packages
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

import signal
from agent_node.node import AgentNode
from agent_node.config import NODE_ID, HUB_URL, AUTH_TOKEN, SECRET_KEY, AUTO_UPDATE, UPDATE_CHECK_INTERVAL
from agent_node.core import updater

def main():
    print(f"[*] Starting Agent Node: {NODE_ID}...")

    # 0. Auto-Update Check (before anything else — if we're behind, restart now)
    if AUTO_UPDATE:
        updater.init(hub_http_url=HUB_URL, auth_token=SECRET_KEY, check_interval_secs=UPDATE_CHECK_INTERVAL)
        updater.check_and_update_once()  # May restart process — does not return if update applied

    # 1. Initialization
    node = AgentNode()
    
    # 2. Signal Handling for Graceful Shutdown
    def handle_exit(sig, frame):
        node.stop()
        sys.exit(0)
        
    signal.signal(signal.SIGINT, handle_exit)
    signal.signal(signal.SIGTERM, handle_exit)

    # Handshake: Sync configuration and Sandbox Policy
    node.sync_configuration()
    
    # 3. Background: Start health reporting (Heartbeats)
    node.start_health_reporting()

    # 4. Background: Periodic auto-update checks
    if AUTO_UPDATE:
        updater.start_background_updater()

    # 5. Foreground: Run Persistent Task Stream
    node.run_task_stream()

if __name__ == '__main__':
    main()