<!-- Copyright (C) 2026 Stefy Lanza <stefy@nexlab.net> -->
<!-- SPDX-License-Identifier: GPL-3.0-or-later -->
<!-- Copyleft: GNU GPLv3 or later applies to this file. -->

# Hermes Node Protocol
# Copyright (c) 2026 Stefy (nextime) Lanza <stefy@nexlab.net>
# All rights reserved.
# 
# This software is released under the MIT License with a copyleft clause.
# See the LICENSE file for full terms.
# Hermes Node Agent — Windows Deployment Guide

**Platform:** Windows 10/11, Windows Server 2016+  
**Version:** 2.0  
**Date:** 2026-04-30

This guide covers deploying the Hermes Node Agent on Windows machines using the graphical installer.

---

## Overview

The Windows package includes:

- **hermes-node-agent.exe** — Main agent (connects to gateway)
- **hermes-node-manager.exe** — System tray GUI for management
- **NSSM** — Service wrapper (runs agent as Windows service)
- **Graphical installer** — One-click setup with uninstaller

---

## Installation

### Option A: Graphical Installer (Recommended)

1. **Download** `hermes-node-agent-installer.exe`
2. **Right-click** → **Run as Administrator**
3. Follow the installation wizard:
   - Accept license
   - Choose install location (default: `C:\Program Files\Hermes Node`)
   - Select components:
     - ☑ Install Windows Service (recommended)
     - ☑ Start Manager at login (recommended)
     - ☐ Create desktop shortcut (optional)
4. Click **Install**
5. When prompted, click **Finish** to launch the manager

### Option B: Silent Installation (for deployment tools)

```cmd
hermes-node-agent-installer.exe /VERYSILENT /NORESTART /TASKS="starttray"
```

Parameters:
- `/VERYSILENT` — No UI, no prompts
- `/NORESTART` — Don't reboot after install
- `/TASKS="starttray"` — Enable auto-start at login
- `/DIR="C:\Custom\Path"` — Custom install directory

---

## First-Time Configuration

After installation, the **Hermes Node Manager** will appear in your system tray (near the clock).

### Step 1: Configure Connection

1. **Right-click** the tray icon (blue "H")
2. Select **Configuration**
3. Fill in the required fields:
   - **Gateway URL**: `wss://your-gateway-host:8765`
   - **Node Name**: Unique identifier (default: computer name)
   - **Token**: Authentication token from gateway admin
   - **sexec Path**: (optional) Path to permission script
   - **Reconnect**: Seconds between reconnect attempts (default: 5)
   - **Heartbeat**: Seconds between heartbeats (default: 30)
4. Click **Save**

### Step 2: Start the Agent

1. **Right-click** the tray icon
2. Select **Start Agent**
3. Wait 5-10 seconds for connection
4. Verify in **Status** window (should show "RUNNING")

---

## Using the Manager

### System Tray Menu

Right-click the tray icon to access:

| Menu Item | Description |
|-----------|-------------|
| **Configuration** | Edit gateway URL, token, and settings |
| **Logs** | View agent logs (last 50 lines or full) |
| **Status** | Show connection status and config summary |
| **Start Agent** | Start the Windows service |
| **Stop Agent** | Stop the Windows service |
| **Restart Agent** | Restart the service (apply config changes) |
| **Open Gateway UI** | Open gateway web interface in browser |
| **Exit** | Close the manager (agent keeps running) |

### Configuration Window

**Fields:**

- **Gateway URL**: WebSocket address of the gateway
  - Format: `wss://hostname:8765` (secure) or `ws://hostname:8765` (insecure)
  - Must match the gateway's WebSocket port
- **Node Name**: Unique identifier for this node
  - Must match a token entry in gateway's `config.json`
  - Default: Windows computer name
- **Token**: Authentication secret
  - Provided by gateway administrator
  - Keep this secure (treat like a password)
- **sexec Path**: (Optional) Path to PowerShell permission script
  - Default: `%USERPROFILE%\.openclaw\skills\sexec\sexec.ps1`
  - Leave blank to allow all commands (not recommended)
- **Reconnect Interval**: Seconds to wait before reconnecting after disconnect
- **Heartbeat Interval**: Seconds between keep-alive pings

**After changing config:**
- Click **Save**
- **Restart Agent** from the tray menu to apply changes

### Log Viewer

View real-time agent logs:

1. Right-click tray icon → **Logs**
2. Click **Refresh** to reload
3. Click **Tail (last 50)** to see recent entries
4. Click **Clear** to empty the view

**Log file location:** `C:\ProgramData\hermes-node\hermes-node-agent.log`

### Status Window

Shows:
- Service status (RUNNING / STOPPED)
- Current configuration summary
- File paths (config, logs, agent)
- Auto-refreshes every 5 seconds

---

## Service Management

The agent runs as a Windows service named **HermesNodeAgent**.

### Via Tray Manager (Recommended)

- **Start**: Right-click tray icon → Start Agent
- **Stop**: Right-click tray icon → Stop Agent
- **Restart**: Right-click tray icon → Restart Agent

### Via Command Line

```cmd
REM Start service
sc start HermesNodeAgent

REM Stop service
sc stop HermesNodeAgent

REM Query status
sc query HermesNodeAgent

REM View service config
sc qc HermesNodeAgent
```

### Via Services.msc

1. Press `Win+R`, type `services.msc`, press Enter
2. Find **HermesNodeAgent** in the list
3. Right-click → Start / Stop / Restart
4. Right-click → Properties to configure startup type

---

## Permissions (sexec)

The Windows agent supports the same permission system as Linux.

### Creating sexec.ps1

Create `%USERPROFILE%\.openclaw\skills\sexec\sexec.ps1`:

```powershell
# Hermes Node Agent — Permission Enforcement Script
param()

$command = $env:SEXEC_COMMAND
if (-not $command) {
    Write-Error "SEXEC_COMMAND not set"
    exit 1
}

# Load permissions from JSON
$permPath = "$env:USERPROFILE\.openclaw\skills\sexec\permissions.json"
if (Test-Path $permPath) {
    $perms = Get-Content $permPath | ConvertFrom-Json

    # Deny list (highest priority)
    foreach ($pattern in $perms.deny) {
        if ($command -match $pattern) {
            Write-Error "Denied by pattern: $pattern"
            exit 1
        }
    }

    # Ask list (requires approval)
    foreach ($pattern in $perms.ask) {
        if ($command -match $pattern) {
            Write-Error "Command requires approval"
            exit 2
        }
    }

    # Allow list (if present, command must match)
    if ($perms.allow -and $perms.allow.Count -gt 0) {
        $allowed = $false
        foreach ($pattern in $perms.allow) {
            if ($command -match $pattern) {
                $allowed = $true
                break
            }
        }
        if (-not $allowed) {
            Write-Error "Not in allow list"
            exit 1
        }
    }
}

# Execute command
Invoke-Expression $command
exit $LASTEXITCODE
```

### Creating permissions.json

Create `%USERPROFILE%\.openclaw\skills\sexec\permissions.json`:

```json
{
  "allow": [
    "^dir\\b",
    "^Get-",
    "^Test-Path",
    "^whoami"
  ],
  "deny": [
    "Remove-Item.*-Recurse",
    "Format-Volume",
    "Stop-Computer",
    "Restart-Computer"
  ],
  "ask": [
    "Install-",
    "Uninstall-",
    "Set-ExecutionPolicy"
  ]
}
```

**Patterns are PowerShell regex:**
- `^` = start of command
- `\\b` = word boundary
- `.*` = any characters
- Case-insensitive by default

---

## Firewall Configuration

The agent makes **outbound connections only** (no inbound ports needed).

### Allow Outbound Connection

If Windows Firewall blocks the agent:

1. Open **Windows Defender Firewall with Advanced Security**
2. Click **Outbound Rules** → **New Rule**
3. Select **Program** → Next
4. Browse to: `C:\Program Files\Hermes Node\hermes-node-agent.exe`
5. Select **Allow the connection** → Next
6. Apply to all profiles (Domain, Private, Public) → Next
7. Name: "Hermes Node Agent" → Finish

### Test Connectivity

```powershell
# Test gateway reachability
Test-NetConnection -ComputerName your-gateway-host -Port 8765

# Should show: TcpTestSucceeded : True
```

---

## Troubleshooting

### Agent won't start

**Check service status:**
```cmd
sc query HermesNodeAgent
```

**View service errors:**
```cmd
Get-EventLog -LogName Application -Source HermesNodeAgent -Newest 10
```

**Common causes:**
- Config file missing or invalid JSON
- Python not installed (embedded version should be bundled)
- Gateway URL unreachable

### Connection refused

1. Verify gateway is running: `curl https://your-gateway:8766/health`
2. Check token matches gateway config
3. Ensure node name matches token entry in gateway
4. Check firewall allows outbound HTTPS/WSS

### Permission denied errors

1. Verify `sexec_path` points to an existing `.ps1` file
2. Check `permissions.json` syntax (valid JSON)
3. Test sexec manually:
   ```powershell
   $env:SEXEC_COMMAND = "whoami"
   & "$env:USERPROFILE\.openclaw\skills\sexec\sexec.ps1"
   ```

### Manager won't start

**Check if already running:**
```powershell
Get-Process hermes-node-manager -ErrorAction SilentlyContinue
```

**Kill and restart:**
```powershell
Stop-Process -Name hermes-node-manager -Force
& "C:\Program Files\Hermes Node\hermes-node-manager.exe"
```

### Logs show "Token invalid"

1. Open config: `notepad C:\ProgramData\hermes-node\config.json`
2. Verify token matches gateway's `config.json` entry for this node
3. Restart agent after fixing

---

## Uninstallation

### Via Control Panel

1. Open **Settings** → **Apps** → **Apps & features**
2. Find **Hermes Node Agent**
3. Click **Uninstall**
4. Follow the wizard

### Via Command Line

```cmd
"C:\Program Files\Hermes Node\unins000.exe" /VERYSILENT /NORESTART
```

**What gets removed:**
- Agent executable and manager
- Windows service registration
- Start menu shortcuts
- Desktop shortcut (if created)

**What stays (manual cleanup required):**
- Config: `C:\ProgramData\hermes-node\config.json`
- Logs: `C:\ProgramData\hermes-node\hermes-node-agent.log`
- sexec scripts: `%USERPROFILE%\.openclaw\skills\sexec\`

---

## Advanced: Running Without Service

For testing or development, run the agent directly:

```cmd
cd "C:\Program Files\Hermes Node"
hermes-node-agent.exe --config "C:\ProgramData\hermes-node\config.json"
```

Press `Ctrl+C` to stop.

---

## Files Installed

| Path | Description |
|------|-------------|
| `C:\Program Files\Hermes Node\hermes-node-agent.exe` | Main agent executable |
| `C:\Program Files\Hermes Node\hermes-node-manager.exe` | System tray manager GUI |
| `C:\Program Files\Hermes Node\nssm.exe` | Service wrapper |
| `C:\ProgramData\hermes-node\config.json` | Configuration file |
| `C:\ProgramData\hermes-node\hermes-node-agent.log` | Log file |
| `%APPDATA%\Microsoft\Windows\Start Menu\Programs\Hermes Node\` | Start menu shortcuts |

---

## Support

For issues:
- Check logs: `C:\ProgramData\hermes-node\hermes-node-agent.log`
- Check gateway logs: `/var/log/hermes-node-gateway.log` (on gateway host)
- Review DEPLOYMENT.md for architecture details
- Contact gateway administrator for token/connectivity issues
