Compare commits

..

10 Commits

Author SHA1 Message Date
zhi
ab42936408 fix(telemetry): discover agents from ~/.openclaw/agents and clean docs
- Fallback to agent directory discovery when agents.json is absent
- Count configured agent workspaces (excluding main)
- Rewrite plugin docs to API key-only flow
2026-03-20 08:02:19 +00:00
zhi
040cde8cad feat(telemetry): report openclaw and plugin versions separately
- Report remote OpenClaw CLI version as openclaw_version
- Report harborforge-monitor plugin version as plugin_version
- Pass plugin version from plugin runtime to sidecar
- Read live config via api.pluginConfig/api.config helper
2026-03-20 07:23:18 +00:00
zhi
006784db63 refactor(plugin): read config via api.pluginConfig and api.config
- Mirror dirigent plugin registration pattern
- Read base config from api.pluginConfig
- Read live config from api.config.plugins.entries.harborforge-monitor.config
- Support gateway_start/gateway_stop lifecycle only
- Compile nested plugin/core files
2026-03-20 07:13:12 +00:00
zhi
de4ef87491 refactor(plugin): remove fallback sidecar autostart 2026-03-20 06:42:45 +00:00
zhi
55b17e35ea fix(plugin): use OpenClaw gateway_start/gateway_stop hooks 2026-03-20 06:36:20 +00:00
zhi
8ebc76931f fix(plugin): normalize OpenClaw plugin config shapes
- Accept flat config, nested entry.config, or missing config
- Treat plugin as enabled unless explicitly disabled
- Log resolved runtime config for gateway diagnostics
2026-03-20 06:27:46 +00:00
zhi
eb43434e48 fix(plugin): correct telemetry server path for installed plugin
- Resolve telemetry.mjs relative to installed plugin root
- Update installer messaging from challengeUuid to apiKey
- Document correct OpenClaw plugin entry config structure
2026-03-20 06:24:40 +00:00
zhi
6d6d00437d chore: add .gitignore for build artifacts 2026-03-19 18:20:43 +00:00
zhi
0dc824549a feat: fix API Key authentication and payload alignment
- Update openclaw.plugin.json: replace challengeUuid with apiKey (optional)
- Fix tsconfig: use CommonJS module to avoid import.meta.url issues
- Fix plugin/index.ts: remove ESM-specific code, use __dirname
- Fix telemetry.mjs:
  - Add loadavg to os imports, remove require() call
  - Replace challengeUuid with apiKey in config
  - Update endpoint to heartbeat-v2
  - Add X-API-Key header when apiKey is configured
  - Fix payload field names: agents, load_avg (array), uptime_seconds
  - Change missing apiKey from error to warning
2026-03-19 18:20:29 +00:00
zhi
0debe835b4 feat: reorganize to standard OpenClaw plugin structure
New structure:
├── package.json                 # Root package
├── README.md                    # Documentation
├── plugin/                      # OpenClaw plugin
│   ├── openclaw.plugin.json     # Plugin manifest
│   ├── index.ts                 # Plugin entry (TypeScript)
│   ├── package.json
│   └── tsconfig.json
├── server/                      # Telemetry sidecar
│   └── telemetry.mjs
├── skills/                      # OpenClaw skills
└── scripts/
    └── install.mjs              # Installation script

Matches PaddedCell project structure.
Provides install.mjs with build/install/configure/uninstall commands.
2026-03-19 13:51:19 +00:00
17 changed files with 871 additions and 400 deletions

5
.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
plugin/node_modules/
plugin/*.js
plugin/*.js.map
plugin/*.d.ts
plugin/*.d.ts.map

126
README.md
View File

@@ -2,20 +2,39 @@
OpenClaw 插件,将服务器遥测数据流式传输到 HarborForge Monitor。
## 项目结构
```
HarborForge.OpenclawPlugin/
├── package.json # 根 package.json
├── README.md # 本文档
├── plugin/ # OpenClaw 插件代码
│ ├── openclaw.plugin.json # 插件定义
│ ├── index.ts # 插件入口
│ ├── package.json # 插件依赖
│ └── tsconfig.json # TypeScript 配置
├── server/ # Sidecar 服务器
│ └── telemetry.mjs # 遥测数据收集和发送
├── skills/ # OpenClaw 技能
│ └── (技能文件)
└── scripts/
└── install.mjs # 安装脚本
```
## 架构
```
┌─────────────────────────────────────────────────┐
│ OpenClaw Gateway │
│ ┌───────────────────────────────────────────┐ │
│ │ HarborForge.OpenclawPlugin (index.mjs) │ │
│ │ HarborForge.OpenclawPlugin/plugin/ │ │
│ │ - 生命周期管理 (启动/停止) │ │
│ │ - 配置管理 │ │
│ └───────────────────────────────────────────┘ │
│ │ │
│ ▼ 启动 sidecar
│ ▼ 启动 telemetry server
│ ┌───────────────────────────────────────────┐ │
│ │ Sidecar (sidecar/server.mjs) │ │
│ │ HarborForge.OpenclawPlugin/server/ │ │
│ │ - 独立 Node 进程 │ │
│ │ - 收集系统指标 │ │
│ │ - 收集 OpenClaw 状态 │ │
@@ -23,7 +42,7 @@ OpenClaw 插件,将服务器遥测数据流式传输到 HarborForge Monitor。
│ └───────────────────────────────────────────┘ │
└─────────────────────────────────────────────────┘
▼ HTTP/WebSocket
▼ HTTP
┌─────────────────────┐
│ HarborForge Monitor │
└─────────────────────┘
@@ -31,44 +50,58 @@ OpenClaw 插件,将服务器遥测数据流式传输到 HarborForge Monitor。
## 安装
### 1. 复制插件到 OpenClaw 插件目录
### 快速安装
```bash
# 找到 OpenClaw 插件目录
# 通常是 ~/.openclaw/plugins/ 或 /usr/lib/node_modules/openclaw/plugins/
# 克隆仓库
git clone https://git.hangman-lab.top/zhi/HarborForge.OpenclawPlugin.git
cd HarborForge.OpenclawPlugin
# 复制插件
cp -r HarborForge.OpenclawPlugin ~/.openclaw/plugins/harborforge-monitor
# 运行安装脚本
node scripts/install.mjs
```
### 2. 在 HarborForge Monitor 中注册服务器
### 开发安装
1. 登录 HarborForge Monitor
2. 进入 Server Management
3. 点击 "Register New Server"
4. 获取 `challengeUuid`
```bash
# 仅构建不安装
node scripts/install.mjs --build-only
### 3. 配置 OpenClaw
# 指定 OpenClaw 路径
node scripts/install.mjs --openclaw-profile-path /custom/path/.openclaw
编辑 `~/.openclaw/openclaw.json`:
# 详细输出
node scripts/install.mjs --verbose
```
## 配置
1. 在 HarborForge Monitor 中注册服务器,并生成 `apiKey`
2. 编辑 `~/.openclaw/openclaw.json`:
```json
{
"plugins": {
"entries": {
"harborforge-monitor": {
"enabled": true,
"config": {
"enabled": true,
"backendUrl": "https://monitor.hangman-lab.top",
"identifier": "my-server-01",
"challengeUuid": "your-challenge-uuid-here",
"apiKey": "your-api-key-here",
"reportIntervalSec": 30,
"httpFallbackIntervalSec": 60,
"logLevel": "info"
}
}
}
}
}
```
### 4. 重启 OpenClaw Gateway
3. 重启 OpenClaw Gateway:
```bash
openclaw gateway restart
@@ -79,9 +112,9 @@ openclaw gateway restart
| 选项 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| `enabled` | boolean | `true` | 是否启用插件 |
| `backendUrl` | string | `"https://monitor.hangman-lab.top"` | Monitor 后端地址 |
| `backendUrl` | string | `https://monitor.hangman-lab.top` | Monitor 后端地址 |
| `identifier` | string | 自动检测 hostname | 服务器标识符 |
| `challengeUuid` | string | 必填 | 注册挑战 UUID |
| `apiKey` | string | 必填 | HarborForge Monitor 生成的服务器 API Key |
| `reportIntervalSec` | number | `30` | 报告间隔(秒) |
| `httpFallbackIntervalSec` | number | `60` | HTTP 回退间隔(秒) |
| `logLevel` | string | `"info"` | 日志级别: debug/info/warn/error |
@@ -103,52 +136,37 @@ openclaw gateway restart
- Agent 数量
- Agent 列表 (id, name, status)
## 故障排查
### 查看日志
## 卸载
```bash
# 查看 Gateway 日志
openclaw gateway logs | grep HF-Monitor
# 或者直接查看 sidecar 输出(如果独立运行)
node sidecar/server.mjs 2>&1 | tee monitor.log
node scripts/install.mjs --uninstall
```
### 检查状态
在 OpenClaw 对话中:
```
使用 harborforge_monitor_status 工具检查插件状态
```
### 常见问题
1. **challengeUuid 未设置**
- 错误: `Missing required config: challengeUuid`
- 解决: 在 Monitor 中注册服务器并配置 challengeUuid
2. **Sidecar 无法启动**
- 检查 Node.js 版本 (>=18)
- 检查 `sidecar/server.mjs` 是否存在
3. **无法连接到 Monitor**
- 检查 `backendUrl` 配置
- 检查网络连接和防火墙
## 开发
### 本地测试 sidecar
### 构建插件
```bash
cd sidecar
HF_MONITOR_CHALLENGE_UUID=test-uuid \
cd plugin
npm install
npm run build
```
### 本地测试 telemetry server
```bash
cd server
HF_MONITOR_API_KEY=test-api-key \
HF_MONITOR_BACKEND_URL=http://localhost:8000 \
HF_MONITOR_LOG_LEVEL=debug \
node server.mjs
node telemetry.mjs
```
## 依赖
- Node.js 18+
- OpenClaw Gateway
## 文档
- [监控连接器规划](./docs/monitor-server-connector-plan.md) - 原始设计文档

View File

@@ -1,112 +1,47 @@
# HarborForge OpenClaw Server Connector Plugin — Project Plan
# Monitor Server Connector Plan
## 1) Goal
Provide a secure, lightweight plugin/agent that connects servers to HarborForge Monitor, streams telemetry in real time, and falls back to HTTP heartbeat when WebSocket is unavailable.
## Current design
## 2) Scope
- **Handshake + auth** using backend-issued challenge + RSA-OAEP encrypted payload.
- **WebSocket telemetry** to `/monitor/server/ws`.
- **HTTP heartbeat** to `/monitor/server/heartbeat` as fallback.
- **System metrics**: CPU/Mem/Disk/Swap/Uptime/OpenClaw version/Agents list.
- **Retry & backoff**, offline handling, and minimal local state.
The plugin uses:
## 3) Non-Goals
- No UI in the plugin.
- No provider billing calls from plugin.
- No multi-tenant auth beyond challenge + server identifier.
- **HTTP heartbeat** to `/monitor/server/heartbeat-v2`
- **API Key authentication** via `X-API-Key`
- **Gateway lifecycle hooks**: `gateway_start` / `gateway_stop`
## 4) Architecture
```
plugin/
config/ # load config & secrets
crypto/ # RSA-OAEP encrypt/decrypt helpers
collector/ # system + openclaw metrics
transport/ # ws + http heartbeat
state/ # retry/backoff, last sent, cache
main.ts|py # entry
```
## No longer used
### 4.1 Config
- `backend_url`
- `identifier`
- `challenge_uuid`
- `report_interval_sec` (default: 20-30s)
- `http_fallback_interval_sec` (default: 60s)
- `log_level`
The following design has been retired:
### 4.2 Security
- Fetch public key: `GET /monitor/public/server-public-key`
- Encrypt payload with RSA-OAEP
- Include `nonce` + `ts` (UTC) to prevent replay
- **Challenge valid**: 10 minutes
- **Offline threshold**: 7 minutes
- challenge UUID
- RSA public key fetch
- encrypted handshake payload
- WebSocket telemetry
## 5) Communication Flow
### 5.1 Handshake (WS)
1. Plugin reads `identifier + challenge_uuid`.
2. Fetch RSA public key.
3. Encrypt payload: `{identifier, challenge_uuid, nonce, ts}`.
4. Connect WS `/monitor/server/ws` and send `encrypted_payload`.
5. On success: begin periodic telemetry push.
## Runtime flow
### 5.2 Fallback (HTTP)
If WS fails:
- POST telemetry to `/monitor/server/heartbeat` with same payload fields.
- Retry with exponential backoff (cap 510 min).
1. Gateway loads `harborforge-monitor`
2. Plugin reads config from OpenClaw plugin config
3. On `gateway_start`, plugin launches `server/telemetry.mjs`
4. Sidecar collects:
- system metrics
- OpenClaw version
- plugin version
- configured agents
5. Sidecar posts telemetry to backend with `X-API-Key`
## 6) Telemetry Schema (example)
```
## Payload
```json
{
identifier: "vps.t1",
openclaw_version: "x.y.z",
cpu_pct: 12.5,
mem_pct: 41.2,
disk_pct: 62.0,
swap_pct: 0.0,
agents: [ { id: "a1", name: "agent", status: "running" } ],
last_seen_at: "2026-03-11T21:00:00Z"
"identifier": "vps.t1",
"openclaw_version": "OpenClaw 2026.3.13 (61d171a)",
"plugin_version": "0.1.0",
"agents": [],
"cpu_pct": 10.5,
"mem_pct": 52.1,
"disk_pct": 81.0,
"swap_pct": 0.0,
"load_avg": [0.12, 0.09, 0.03],
"uptime_seconds": 12345
}
```
## 7) Reliability
- Automatic reconnect on WS drop
- HTTP fallback if WS unavailable > 2 intervals
- Exponential backoff on failures
- Local cache for last successful payload
## 8) Deployment Options
- **Systemd service** (preferred for VPS)
- **Docker container** (optional)
- Single-binary build if using Go/Rust
## 9) Milestones
**M1 POC (23 days)**
- CLI config loader + HTTP heartbeat
- See online + metrics in Monitor
**M2 WS realtime (23 days)**
- Full handshake + WS streaming
- Reconnect & fallback logic
**M3 Packaging (12 days)**
- systemd unit + sample config
- installation script
**M4 Hardening & Docs (12 days)**
- logging, metrics, docs
- troubleshooting guide
## 10) Deliverables
- Plugin source
- Config template + systemd unit
- Integration docs
- Test script + example payloads
## 11) Open Questions
- Preferred language (Go/Python/Node/Rust)?
- How to read OpenClaw agent list (API vs local state)?
- Required log format / retention?
---
**Next step:** confirm preferred runtime (Go/Python/Node) and I will scaffold the project structure + first heartbeat implementation.

178
index.mjs
View File

@@ -1,178 +0,0 @@
/**
* HarborForge Monitor Plugin for OpenClaw
*
* Registers with OpenClaw Gateway and manages sidecar lifecycle.
* Sidecar runs as separate Node process to avoid blocking Gateway.
*/
import { spawn } from 'child_process';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { existsSync } from 'fs';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
/** @type {import('openclaw').Plugin} */
export default function register(api, config) {
const logger = api.logger || {
info: (...args) => console.log('[HF-Monitor]', ...args),
error: (...args) => console.error('[HF-Monitor]', ...args),
debug: (...args) => console.debug('[HF-Monitor]', ...args)
};
if (!config?.enabled) {
logger.info('HarborForge Monitor plugin disabled');
return;
}
// Validate required config
if (!config.challengeUuid) {
logger.error('Missing required config: challengeUuid');
logger.error('Please register server in HarborForge Monitor first');
return;
}
const sidecarPath = join(__dirname, 'sidecar', 'server.mjs');
if (!existsSync(sidecarPath)) {
logger.error('Sidecar not found:', sidecarPath);
return;
}
/** @type {import('child_process').ChildProcess|null} */
let sidecar = null;
/**
* Start the sidecar server
*/
function startSidecar() {
if (sidecar) {
logger.debug('Sidecar already running');
return;
}
logger.info('Starting HarborForge Monitor sidecar...');
// Prepare environment for sidecar
const env = {
...process.env,
HF_MONITOR_BACKEND_URL: config.backendUrl || 'https://monitor.hangman-lab.top',
HF_MONITOR_IDENTIFIER: config.identifier || '',
HF_MONITOR_CHALLENGE_UUID: config.challengeUuid,
HF_MONITOR_REPORT_INTERVAL: String(config.reportIntervalSec || 30),
HF_MONITOR_HTTP_FALLBACK_INTERVAL: String(config.httpFallbackIntervalSec || 60),
HF_MONITOR_LOG_LEVEL: config.logLevel || 'info',
// Pass OpenClaw info for metrics
OPENCLAW_PATH: process.env.OPENCLAW_PATH || join(process.env.HOME || '/root', '.openclaw'),
OPENCLAW_VERSION: api.version || 'unknown',
};
// Spawn sidecar as detached process so it survives Gateway briefly during restart
sidecar = spawn('node', [sidecarPath], {
env,
detached: false, // Keep attached for logging, but could be true for full detachment
stdio: ['ignore', 'pipe', 'pipe']
});
sidecar.stdout?.on('data', (data) => {
logger.info('[sidecar]', data.toString().trim());
});
sidecar.stderr?.on('data', (data) => {
logger.error('[sidecar]', data.toString().trim());
});
sidecar.on('exit', (code, signal) => {
logger.info(`Sidecar exited (code: ${code}, signal: ${signal})`);
sidecar = null;
});
sidecar.on('error', (err) => {
logger.error('Failed to start sidecar:', err.message);
sidecar = null;
});
logger.info('Sidecar started with PID:', sidecar.pid);
}
/**
* Stop the sidecar server
*/
function stopSidecar() {
if (!sidecar) {
logger.debug('Sidecar not running');
return;
}
logger.info('Stopping HarborForge Monitor sidecar...');
// Graceful shutdown
sidecar.kill('SIGTERM');
// Force kill after timeout
const timeout = setTimeout(() => {
if (sidecar && !sidecar.killed) {
logger.warn('Sidecar did not exit gracefully, forcing kill');
sidecar.kill('SIGKILL');
}
}, 5000);
sidecar.on('exit', () => {
clearTimeout(timeout);
});
}
// Hook into Gateway lifecycle
api.on('gateway:start', () => {
logger.info('Gateway starting, starting monitor sidecar...');
startSidecar();
});
api.on('gateway:stop', () => {
logger.info('Gateway stopping, stopping monitor sidecar...');
stopSidecar();
});
// Also handle process signals directly
process.on('SIGTERM', () => {
stopSidecar();
});
process.on('SIGINT', () => {
stopSidecar();
});
// Start immediately if Gateway is already running
if (api.isRunning?.()) {
startSidecar();
} else {
// Delay start slightly to ensure Gateway is fully up
setTimeout(() => {
startSidecar();
}, 1000);
}
// Register status tool
api.registerTool(() => ({
name: 'harborforge_monitor_status',
description: 'Get HarborForge Monitor plugin status',
parameters: {
type: 'object',
properties: {}
},
async execute() {
return {
enabled: true,
sidecarRunning: sidecar !== null && sidecar.exitCode === null,
pid: sidecar?.pid || null,
config: {
backendUrl: config.backendUrl,
identifier: config.identifier || 'auto-detected',
reportIntervalSec: config.reportIntervalSec
}
};
}
}));
logger.info('HarborForge Monitor plugin registered');
}

View File

@@ -3,10 +3,10 @@
"version": "0.1.0",
"description": "OpenClaw plugin for HarborForge Monitor - streams server telemetry",
"type": "module",
"main": "index.mjs",
"scripts": {
"start": "node index.mjs",
"sidecar": "node sidecar/server.mjs"
"build": "cd plugin && npm run build",
"install": "node scripts/install.mjs",
"uninstall": "node scripts/install.mjs --uninstall"
},
"keywords": ["openclaw", "plugin", "monitoring", "harborforge"],
"license": "MIT",

15
plugin/core/live-config.d.ts vendored Normal file
View File

@@ -0,0 +1,15 @@
export interface HarborForgeMonitorConfig {
enabled?: boolean;
backendUrl?: string;
identifier?: string;
apiKey?: string;
reportIntervalSec?: number;
httpFallbackIntervalSec?: number;
logLevel?: 'debug' | 'info' | 'warn' | 'error';
}
interface OpenClawPluginApiLike {
config?: Record<string, unknown>;
}
export declare function getLivePluginConfig(api: OpenClawPluginApiLike, fallback: HarborForgeMonitorConfig): HarborForgeMonitorConfig;
export {};
//# sourceMappingURL=live-config.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"live-config.d.ts","sourceRoot":"","sources":["live-config.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,wBAAwB;IACvC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,uBAAuB,CAAC,EAAE,MAAM,CAAC;IACjC,QAAQ,CAAC,EAAE,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC;CAChD;AAED,UAAU,qBAAqB;IAC7B,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAClC;AAED,wBAAgB,mBAAmB,CACjC,GAAG,EAAE,qBAAqB,EAC1B,QAAQ,EAAE,wBAAwB,GACjC,wBAAwB,CAqB1B"}

View File

@@ -0,0 +1,23 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getLivePluginConfig = getLivePluginConfig;
function getLivePluginConfig(api, fallback) {
const root = api.config || {};
const plugins = root.plugins || {};
const entries = plugins.entries || {};
const entry = entries['harborforge-monitor'] || {};
const cfg = entry.config || {};
if (Object.keys(cfg).length > 0 || Object.keys(entry).length > 0) {
return {
...fallback,
...cfg,
enabled: typeof cfg.enabled === 'boolean'
? cfg.enabled
: typeof entry.enabled === 'boolean'
? entry.enabled
: fallback.enabled,
};
}
return fallback;
}
//# sourceMappingURL=live-config.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"live-config.js","sourceRoot":"","sources":["live-config.ts"],"names":[],"mappings":";;AAcA,kDAwBC;AAxBD,SAAgB,mBAAmB,CACjC,GAA0B,EAC1B,QAAkC;IAElC,MAAM,IAAI,GAAI,GAAG,CAAC,MAAkC,IAAI,EAAE,CAAC;IAC3D,MAAM,OAAO,GAAI,IAAI,CAAC,OAAmC,IAAI,EAAE,CAAC;IAChE,MAAM,OAAO,GAAI,OAAO,CAAC,OAAmC,IAAI,EAAE,CAAC;IACnE,MAAM,KAAK,GAAI,OAAO,CAAC,qBAAqB,CAA6B,IAAI,EAAE,CAAC;IAChF,MAAM,GAAG,GAAI,KAAK,CAAC,MAAkC,IAAI,EAAE,CAAC;IAE5D,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,MAAM,GAAG,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACjE,OAAO;YACL,GAAG,QAAQ;YACX,GAAG,GAAG;YACN,OAAO,EACL,OAAO,GAAG,CAAC,OAAO,KAAK,SAAS;gBAC9B,CAAC,CAAC,GAAG,CAAC,OAAO;gBACb,CAAC,CAAC,OAAO,KAAK,CAAC,OAAO,KAAK,SAAS;oBAClC,CAAC,CAAC,KAAK,CAAC,OAAO;oBACf,CAAC,CAAC,QAAQ,CAAC,OAAO;SACG,CAAC;IAChC,CAAC;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC"}

View File

@@ -0,0 +1,39 @@
export interface HarborForgeMonitorConfig {
enabled?: boolean;
backendUrl?: string;
identifier?: string;
apiKey?: string;
reportIntervalSec?: number;
httpFallbackIntervalSec?: number;
logLevel?: 'debug' | 'info' | 'warn' | 'error';
}
interface OpenClawPluginApiLike {
config?: Record<string, unknown>;
}
export function getLivePluginConfig(
api: OpenClawPluginApiLike,
fallback: HarborForgeMonitorConfig
): HarborForgeMonitorConfig {
const root = (api.config as Record<string, unknown>) || {};
const plugins = (root.plugins as Record<string, unknown>) || {};
const entries = (plugins.entries as Record<string, unknown>) || {};
const entry = (entries['harborforge-monitor'] as Record<string, unknown>) || {};
const cfg = (entry.config as Record<string, unknown>) || {};
if (Object.keys(cfg).length > 0 || Object.keys(entry).length > 0) {
return {
...fallback,
...cfg,
enabled:
typeof cfg.enabled === 'boolean'
? cfg.enabled
: typeof entry.enabled === 'boolean'
? entry.enabled
: fallback.enabled,
} as HarborForgeMonitorConfig;
}
return fallback;
}

184
plugin/index.ts Normal file
View File

@@ -0,0 +1,184 @@
/**
* HarborForge Monitor Plugin for OpenClaw
*
* Manages sidecar lifecycle and provides monitor-related tools.
*/
import { spawn } from 'child_process';
import { join } from 'path';
import { existsSync } from 'fs';
import { getLivePluginConfig, type HarborForgeMonitorConfig } from './core/live-config';
interface PluginAPI {
logger: {
info: (...args: any[]) => void;
error: (...args: any[]) => void;
debug: (...args: any[]) => void;
warn: (...args: any[]) => void;
};
version?: string;
config?: Record<string, unknown>;
pluginConfig?: Record<string, unknown>;
on: (event: string, handler: () => void) => void;
registerTool: (factory: (ctx: any) => any) => void;
}
export default {
id: 'harborforge-monitor',
name: 'HarborForge Monitor',
register(api: PluginAPI) {
const logger = api.logger || {
info: (...args: any[]) => console.log('[HF-Monitor]', ...args),
error: (...args: any[]) => console.error('[HF-Monitor]', ...args),
debug: (...args: any[]) => console.debug('[HF-Monitor]', ...args),
warn: (...args: any[]) => console.warn('[HF-Monitor]', ...args),
};
const baseConfig: HarborForgeMonitorConfig = {
enabled: true,
backendUrl: 'https://monitor.hangman-lab.top',
identifier: '',
reportIntervalSec: 30,
httpFallbackIntervalSec: 60,
logLevel: 'info',
...(api.pluginConfig || {}),
};
const serverPath = join(__dirname, 'server', 'telemetry.mjs');
let sidecar: ReturnType<typeof spawn> | null = null;
function resolveConfig() {
return getLivePluginConfig(api, baseConfig);
}
function startSidecar() {
const live = resolveConfig();
const enabled = live.enabled !== false;
logger.info('HarborForge Monitor plugin config resolved', {
enabled,
hasApiKey: Boolean(live.apiKey),
backendUrl: live.backendUrl ?? null,
identifier: live.identifier ?? null,
});
if (!enabled) {
logger.info('HarborForge Monitor plugin disabled');
return;
}
if (sidecar) {
logger.debug('Sidecar already running');
return;
}
if (!live.apiKey) {
logger.warn('Missing config: apiKey');
logger.warn('API authentication will fail. Generate apiKey from HarborForge Monitor admin.');
}
if (!existsSync(serverPath)) {
logger.error('Telemetry server not found:', serverPath);
return;
}
logger.info('Starting HarborForge Monitor telemetry server...');
const env = {
...process.env,
HF_MONITOR_BACKEND_URL: live.backendUrl || 'https://monitor.hangman-lab.top',
HF_MONITOR_IDENTIFIER: live.identifier || '',
HF_MONITOR_API_KEY: live.apiKey || '',
HF_MONITOR_REPORT_INTERVAL: String(live.reportIntervalSec || 30),
HF_MONITOR_HTTP_FALLBACK_INTERVAL: String(live.httpFallbackIntervalSec || 60),
HF_MONITOR_LOG_LEVEL: live.logLevel || 'info',
OPENCLAW_PATH: process.env.OPENCLAW_PATH || join(process.env.HOME || '/root', '.openclaw'),
HF_MONITOR_PLUGIN_VERSION: api.version || 'unknown',
};
sidecar = spawn('node', [serverPath], {
env,
detached: false,
stdio: ['ignore', 'pipe', 'pipe'],
});
sidecar.stdout?.on('data', (data: Buffer) => {
logger.info('[telemetry]', data.toString().trim());
});
sidecar.stderr?.on('data', (data: Buffer) => {
logger.error('[telemetry]', data.toString().trim());
});
sidecar.on('exit', (code, signal) => {
logger.info(`Telemetry server exited (code: ${code}, signal: ${signal})`);
sidecar = null;
});
sidecar.on('error', (err: Error) => {
logger.error('Failed to start telemetry server:', err.message);
sidecar = null;
});
logger.info('Telemetry server started with PID:', sidecar.pid);
}
function stopSidecar() {
if (!sidecar) {
logger.debug('Telemetry server not running');
return;
}
logger.info('Stopping HarborForge Monitor telemetry server...');
sidecar.kill('SIGTERM');
const timeout = setTimeout(() => {
if (sidecar && !sidecar.killed) {
logger.warn('Telemetry server did not exit gracefully, forcing kill');
sidecar.kill('SIGKILL');
}
}, 5000);
sidecar.on('exit', () => {
clearTimeout(timeout);
});
}
api.on('gateway_start', () => {
logger.info('gateway_start received, starting telemetry server...');
startSidecar();
});
api.on('gateway_stop', () => {
logger.info('gateway_stop received, stopping telemetry server...');
stopSidecar();
});
process.on('SIGTERM', stopSidecar);
process.on('SIGINT', stopSidecar);
api.registerTool(() => ({
name: 'harborforge_monitor_status',
description: 'Get HarborForge Monitor plugin status',
parameters: {
type: 'object',
properties: {},
},
async execute() {
const live = resolveConfig();
return {
enabled: live.enabled !== false,
sidecarRunning: sidecar !== null && sidecar.exitCode === null,
pid: sidecar?.pid || null,
config: {
backendUrl: live.backendUrl,
identifier: live.identifier || 'auto-detected',
reportIntervalSec: live.reportIntervalSec,
hasApiKey: Boolean(live.apiKey),
},
};
},
}));
logger.info('HarborForge Monitor plugin registered');
},
};

View File

@@ -3,7 +3,7 @@
"name": "HarborForge Monitor",
"version": "0.1.0",
"description": "Server monitoring plugin for HarborForge - streams telemetry to Monitor",
"entry": "./index.mjs",
"entry": "./index.js",
"configSchema": {
"type": "object",
"additionalProperties": false,
@@ -22,9 +22,9 @@
"type": "string",
"description": "Server identifier (auto-detected from hostname if not set)"
},
"challengeUuid": {
"apiKey": {
"type": "string",
"description": "Registration challenge UUID from Monitor"
"description": "API Key from HarborForge Monitor admin panel (optional but required for authentication)"
},
"reportIntervalSec": {
"type": "number",
@@ -42,7 +42,6 @@
"default": "info",
"description": "Logging level"
}
},
"required": ["challengeUuid"]
}
}
}

48
plugin/package-lock.json generated Normal file
View File

@@ -0,0 +1,48 @@
{
"name": "harborforge-monitor-plugin",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "harborforge-monitor-plugin",
"version": "0.1.0",
"license": "MIT",
"devDependencies": {
"@types/node": "^20.0.0",
"typescript": "^5.0.0"
}
},
"node_modules/@types/node": {
"version": "20.19.37",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.37.tgz",
"integrity": "sha512-8kzdPJ3FsNsVIurqBs7oodNnCEVbni9yUEkaHbgptDACOPW04jimGagZ51E6+lXUwJjgnBw+hyko/lkFWCldqw==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
},
"node_modules/undici-types": {
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
"dev": true,
"license": "MIT"
}
}
}

15
plugin/package.json Normal file
View File

@@ -0,0 +1,15 @@
{
"name": "harborforge-monitor-plugin",
"version": "0.1.0",
"description": "OpenClaw plugin for HarborForge Monitor",
"main": "index.js",
"scripts": {
"build": "tsc",
"watch": "tsc --watch"
},
"devDependencies": {
"@types/node": "^20.0.0",
"typescript": "^5.0.0"
},
"license": "MIT"
}

17
plugin/tsconfig.json Normal file
View File

@@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "CommonJS",
"moduleResolution": "node",
"esModuleInterop": true,
"strict": true,
"skipLibCheck": true,
"outDir": "./",
"rootDir": "./",
"declaration": true,
"declarationMap": true,
"sourceMap": true
},
"include": ["**/*.ts"],
"exclude": ["node_modules"]
}

322
scripts/install.mjs Normal file
View File

@@ -0,0 +1,322 @@
#!/usr/bin/env node
/**
* HarborForge Monitor Plugin Installer v0.1.0
*/
import { execSync } from 'child_process';
import {
existsSync,
mkdirSync,
copyFileSync,
readdirSync,
rmSync,
readFileSync,
writeFileSync,
} from 'fs';
import { dirname, join, resolve } from 'path';
import { fileURLToPath } from 'url';
import { homedir, platform } from 'os';
const __filename = fileURLToPath(import.meta.url);
const __dirname = resolve(dirname(__filename), '..');
const PLUGIN_NAME = 'harborforge-monitor';
const PLUGIN_SRC_DIR = join(__dirname, 'plugin');
const SERVER_SRC_DIR = join(__dirname, 'server');
const SKILLS_SRC_DIR = join(__dirname, 'skills');
const args = process.argv.slice(2);
const options = {
openclawProfilePath: null,
buildOnly: args.includes('--build-only'),
skipCheck: args.includes('--skip-check'),
verbose: args.includes('--verbose') || args.includes('-v'),
uninstall: args.includes('--uninstall'),
installOnly: args.includes('--install'),
};
const profileIdx = args.indexOf('--openclaw-profile-path');
if (profileIdx !== -1 && args[profileIdx + 1]) {
options.openclawProfilePath = resolve(args[profileIdx + 1]);
}
function resolveOpenclawPath() {
if (options.openclawProfilePath) return options.openclawProfilePath;
if (process.env.OPENCLAW_PATH) return resolve(process.env.OPENCLAW_PATH);
return join(homedir(), '.openclaw');
}
const c = {
reset: '\x1b[0m', red: '\x1b[31m', green: '\x1b[32m',
yellow: '\x1b[33m', blue: '\x1b[34m', cyan: '\x1b[36m',
};
function log(msg, color = 'reset') { console.log(`${c[color]}${msg}${c.reset}`); }
function logStep(n, total, msg) { log(`[${n}/${total}] ${msg}`, 'cyan'); }
function logOk(msg) { log(`${msg}`, 'green'); }
function logWarn(msg) { log(`${msg}`, 'yellow'); }
function logErr(msg) { log(`${msg}`, 'red'); }
function exec(command, opts = {}) {
return execSync(command, {
cwd: __dirname,
stdio: opts.silent ? 'pipe' : 'inherit',
encoding: 'utf8',
...opts,
});
}
function getOpenclawConfig(key, def = undefined) {
try {
const out = exec(`openclaw config get ${key} --json 2>/dev/null || echo "undefined"`, { silent: true }).trim();
if (out === 'undefined' || out === '') return def;
return JSON.parse(out);
} catch { return def; }
}
function setOpenclawConfig(key, value) {
exec(`openclaw config set ${key} '${JSON.stringify(value)}' --json`, { silent: true });
}
function unsetOpenclawConfig(key) {
try { exec(`openclaw config unset ${key}`, { silent: true }); } catch {}
}
function copyDir(src, dest) {
mkdirSync(dest, { recursive: true });
for (const entry of readdirSync(src, { withFileTypes: true })) {
const s = join(src, entry.name);
const d = join(dest, entry.name);
if (entry.name === 'node_modules') continue;
entry.isDirectory() ? copyDir(s, d) : copyFileSync(s, d);
}
}
function detectEnvironment() {
logStep(1, 5, 'Detecting environment...');
const env = { platform: platform(), nodeVersion: null };
try {
env.nodeVersion = exec('node --version', { silent: true }).trim();
logOk(`Node.js ${env.nodeVersion}`);
} catch {
logErr('Node.js not found');
}
try {
logOk(`openclaw at ${exec('which openclaw', { silent: true }).trim()}`);
} catch {
logWarn('openclaw CLI not in PATH');
}
return env;
}
function checkDeps(env) {
if (options.skipCheck) { logStep(2, 5, 'Skipping dep checks'); return; }
logStep(2, 5, 'Checking dependencies...');
let fail = false;
if (!env.nodeVersion || parseInt(env.nodeVersion.slice(1)) < 18) {
logErr('Node.js 18+ required');
fail = true;
}
if (fail) {
log('\nInstall missing deps and retry.', 'red');
process.exit(1);
}
logOk('All deps OK');
}
async function build() {
logStep(3, 5, 'Building plugin...');
log(' Building TypeScript plugin...', 'blue');
exec('npm install', { cwd: PLUGIN_SRC_DIR, silent: !options.verbose });
exec('npm run build', { cwd: PLUGIN_SRC_DIR, silent: !options.verbose });
logOk('plugin compiled');
}
function clearInstallTargets(openclawPath) {
const destDir = join(openclawPath, 'plugins', PLUGIN_NAME);
if (existsSync(destDir)) {
rmSync(destDir, { recursive: true, force: true });
logOk(`Removed ${destDir}`);
}
}
function cleanupConfig(openclawPath) {
const destDir = join(openclawPath, 'plugins', PLUGIN_NAME);
try {
const allow = getOpenclawConfig('plugins.allow', []);
const idx = allow.indexOf(PLUGIN_NAME);
if (idx !== -1) {
allow.splice(idx, 1);
setOpenclawConfig('plugins.allow', allow);
logOk('Removed from allow list');
}
unsetOpenclawConfig(`plugins.entries.${PLUGIN_NAME}`);
logOk('Removed plugin entry');
const paths = getOpenclawConfig('plugins.load.paths', []);
const pidx = paths.indexOf(destDir);
if (pidx !== -1) {
paths.splice(pidx, 1);
setOpenclawConfig('plugins.load.paths', paths);
logOk('Removed from load paths');
}
} catch (err) {
logWarn(`Config cleanup: ${err.message}`);
}
}
async function install() {
if (options.buildOnly) { logStep(4, 5, 'Skipping install (--build-only)'); return null; }
logStep(4, 5, 'Installing...');
const openclawPath = resolveOpenclawPath();
const pluginsDir = join(openclawPath, 'plugins');
const destDir = join(pluginsDir, PLUGIN_NAME);
log(` OpenClaw path: ${openclawPath}`, 'blue');
if (existsSync(destDir)) {
logWarn('Existing install detected, uninstalling before install...');
clearInstallTargets(openclawPath);
cleanupConfig(openclawPath);
}
if (existsSync(destDir)) rmSync(destDir, { recursive: true, force: true });
// Copy compiled plugin
mkdirSync(destDir, { recursive: true });
copyDir(PLUGIN_SRC_DIR, destDir);
// Copy telemetry server
const serverDestDir = join(destDir, 'server');
mkdirSync(serverDestDir, { recursive: true });
copyDir(SERVER_SRC_DIR, serverDestDir);
logOk(`Server files → ${serverDestDir}`);
// Copy skills
if (existsSync(SKILLS_SRC_DIR)) {
const skillsDestDir = join(openclawPath, 'skills');
mkdirSync(skillsDestDir, { recursive: true });
copyDir(SKILLS_SRC_DIR, skillsDestDir);
logOk(`Skills → ${skillsDestDir}`);
}
// Install runtime deps
exec('npm install --omit=dev', { cwd: destDir, silent: !options.verbose });
logOk('Runtime deps installed');
return { destDir };
}
async function configure() {
if (options.buildOnly) { logStep(5, 5, 'Skipping config'); return; }
logStep(5, 5, 'Configuring OpenClaw...');
const openclawPath = resolveOpenclawPath();
const destDir = join(openclawPath, 'plugins', PLUGIN_NAME);
try {
const paths = getOpenclawConfig('plugins.load.paths', []);
if (!paths.includes(destDir)) {
paths.push(destDir);
setOpenclawConfig('plugins.load.paths', paths);
}
logOk(`plugins.load.paths includes ${destDir}`);
const allow = getOpenclawConfig('plugins.allow', []);
if (!allow.includes(PLUGIN_NAME)) {
allow.push(PLUGIN_NAME);
setOpenclawConfig('plugins.allow', allow);
}
logOk(`plugins.allow includes ${PLUGIN_NAME}`);
// Note: apiKey must be configured manually by user
logOk('Plugin configured (remember to set apiKey in plugins.entries.harborforge-monitor.config)');
} catch (err) {
logWarn(`Config failed: ${err.message}`);
}
}
function summary() {
logStep(5, 5, 'Done!');
console.log('');
log('╔══════════════════════════════════════════════╗', 'cyan');
log('║ HarborForge Monitor v0.1.0 Install Complete ║', 'cyan');
log('╚══════════════════════════════════════════════╝', 'cyan');
if (options.buildOnly) {
log('\nBuild-only — plugin not installed.', 'yellow');
return;
}
console.log('');
log('Next steps:', 'blue');
log(' 1. Register server in HarborForge Monitor to get apiKey', 'cyan');
log(' 2. Edit ~/.openclaw/openclaw.json under plugins.entries.harborforge-monitor.config:', 'cyan');
log(' {', 'cyan');
log(' "plugins": {', 'cyan');
log(' "entries": {', 'cyan');
log(' "harborforge-monitor": {', 'cyan');
log(' "enabled": true,', 'cyan');
log(' "config": {', 'cyan');
log(' "enabled": true,', 'cyan');
log(' "apiKey": "your-api-key"', 'cyan');
log(' }', 'cyan');
log(' }', 'cyan');
log(' }', 'cyan');
log(' }', 'cyan');
log(' }', 'cyan');
log(' 3. openclaw gateway restart', 'cyan');
console.log('');
}
async function uninstall() {
log('Uninstalling HarborForge Monitor...', 'cyan');
const openclawPath = resolveOpenclawPath();
clearInstallTargets(openclawPath);
cleanupConfig(openclawPath);
log('\nRun: openclaw gateway restart', 'yellow');
}
async function main() {
console.log('');
log('╔══════════════════════════════════════════════╗', 'cyan');
log('║ HarborForge Monitor Plugin Installer v0.1.0 ║', 'cyan');
log('╚══════════════════════════════════════════════╝', 'cyan');
console.log('');
try {
const env = detectEnvironment();
if (options.uninstall) {
await uninstall();
process.exit(0);
}
checkDeps(env);
await build();
if (!options.buildOnly) {
await install();
await configure();
}
summary();
} catch (err) {
log(`\nInstallation failed: ${err.message}`, 'red');
process.exit(1);
}
}
main();

View File

@@ -1,28 +1,30 @@
/**
* HarborForge Monitor Sidecar Server
* HarborForge Monitor Telemetry Server
*
* Runs as separate process from Gateway.
* Collects system metrics and OpenClaw status, sends to Monitor.
*/
import { createServer } from 'http';
import { readFile, access } from 'fs/promises';
import { readFile, access, readdir } from 'fs/promises';
import { constants } from 'fs';
import { exec } from 'child_process';
import { promisify } from 'util';
import { platform, hostname, freemem, totalmem, uptime } from 'os';
import { platform, hostname, freemem, totalmem, uptime, loadavg } from 'os';
const execAsync = promisify(exec);
// Config from environment (set by plugin)
const openclawPath = process.env.OPENCLAW_PATH || `${process.env.HOME}/.openclaw`;
const CONFIG = {
backendUrl: process.env.HF_MONITOR_BACKEND_URL || 'https://monitor.hangman-lab.top',
identifier: process.env.HF_MONITOR_IDENTIFIER || hostname(),
challengeUuid: process.env.HF_MONITOR_CHALLENGE_UUID,
apiKey: process.env.HF_MONITOR_API_KEY,
reportIntervalSec: parseInt(process.env.HF_MONITOR_REPORT_INTERVAL || '30', 10),
httpFallbackIntervalSec: parseInt(process.env.HF_MONITOR_HTTP_FALLBACK_INTERVAL || '60', 10),
logLevel: process.env.HF_MONITOR_LOG_LEVEL || 'info',
openclawPath: process.env.OPENCLAW_PATH || `${process.env.HOME}/.openclaw`,
openclawVersion: process.env.OPENCLAW_VERSION || 'unknown',
openclawPath,
pluginVersion: process.env.HF_MONITOR_PLUGIN_VERSION || 'unknown',
cachePath: process.env.HF_MONITOR_CACHE_PATH || `${openclawPath}/telemetry_cache.json`,
maxCacheSize: parseInt(process.env.HF_MONITOR_MAX_CACHE_SIZE || '100', 10),
};
// Logging
@@ -38,25 +40,19 @@ let wsConnection = null;
let lastSuccessfulSend = null;
let consecutiveFailures = 0;
let isShuttingDown = false;
let cachedOpenclawVersion = null;
/**
* Collect system metrics
*/
async function collectSystemMetrics() {
try {
// CPU usage (average over 1 second)
const cpuUsage = await getCpuUsage();
// Memory
const memTotal = totalmem();
const memFree = freemem();
const memUsed = memTotal - memFree;
// Disk usage
const diskInfo = await getDiskUsage();
// Load average
const loadAvg = platform() !== 'win32' ? require('os').loadavg() : [0, 0, 0];
const loadAvg = platform() !== 'win32' ? loadavg() : [0, 0, 0];
return {
cpu_pct: cpuUsage,
@@ -67,8 +63,12 @@ async function collectSystemMetrics() {
disk_used_gb: Math.round(diskInfo.usedGB * 10) / 10,
disk_total_gb: Math.round(diskInfo.totalGB * 10) / 10,
swap_pct: diskInfo.swapUsedPct || 0,
uptime_sec: Math.floor(uptime()),
load_avg_1m: Math.round(loadAvg[0] * 100) / 100,
uptime_seconds: Math.floor(uptime()),
load_avg: [
Math.round(loadAvg[0] * 100) / 100,
Math.round(loadAvg[1] * 100) / 100,
Math.round(loadAvg[2] * 100) / 100,
],
platform: platform(),
hostname: hostname(),
};
@@ -93,7 +93,6 @@ async function getCpuUsage() {
return isNaN(usage) ? 0 : Math.round(usage * 10) / 10;
}
} catch {
// Fallback: calculate from /proc/stat on Linux
try {
const stat = await readFile('/proc/stat', 'utf8');
const cpuLine = stat.split('\n')[0];
@@ -129,9 +128,6 @@ async function getDiskUsage() {
return { totalGB: 0, usedGB: 0, usedPct: 0 };
}
/**
* Parse size string (like '50G' or '100M') to GB
*/
function parseSizeToGB(size) {
const num = parseFloat(size);
if (size.includes('T')) return num * 1024;
@@ -141,15 +137,33 @@ function parseSizeToGB(size) {
return num;
}
async function resolveOpenclawVersion() {
if (cachedOpenclawVersion) return cachedOpenclawVersion;
try {
const { stdout } = await execAsync('openclaw --version');
const version = stdout.trim();
cachedOpenclawVersion = version || 'unknown';
return cachedOpenclawVersion;
} catch (err) {
log.debug('Failed to resolve OpenClaw version:', err.message);
cachedOpenclawVersion = 'unknown';
return cachedOpenclawVersion;
}
}
/**
* Collect OpenClaw status
*/
async function collectOpenclawStatus() {
try {
const agents = await getOpenclawAgents();
const [agents, openclawVersion] = await Promise.all([
getOpenclawAgents(),
resolveOpenclawVersion(),
]);
return {
version: CONFIG.openclawVersion,
openclawVersion,
pluginVersion: CONFIG.pluginVersion,
agent_count: agents.length,
agents: agents.map(a => ({
id: a.id,
@@ -159,7 +173,12 @@ async function collectOpenclawStatus() {
};
} catch (err) {
log.debug('Failed to collect OpenClaw status:', err.message);
return { version: CONFIG.openclawVersion, agent_count: 0, agents: [] };
return {
openclawVersion: await resolveOpenclawVersion(),
pluginVersion: CONFIG.pluginVersion,
agent_count: 0,
agents: [],
};
}
}
@@ -168,16 +187,28 @@ async function collectOpenclawStatus() {
*/
async function getOpenclawAgents() {
try {
// Try to read agent config/state from OpenClaw directory
const agentConfigPath = `${CONFIG.openclawPath}/agents.json`;
try {
await access(agentConfigPath, constants.R_OK);
const data = JSON.parse(await readFile(agentConfigPath, 'utf8'));
return data.agents || [];
} catch {
// Fallback: return empty list
return [];
if (Array.isArray(data.agents) && data.agents.length > 0) {
return data.agents;
}
} catch {
// fall through to directory-based discovery
}
const agentsDir = `${CONFIG.openclawPath}/agents`;
await access(agentsDir, constants.R_OK);
const entries = await readdir(agentsDir, { withFileTypes: true });
return entries
.filter((entry) => entry.isDirectory())
.filter((entry) => entry.name !== 'main')
.map((entry) => ({
id: entry.name,
name: entry.name,
status: 'configured',
}));
} catch {
return [];
}
@@ -192,12 +223,11 @@ async function buildPayload() {
return {
identifier: CONFIG.identifier,
challenge_uuid: CONFIG.challengeUuid,
timestamp: new Date().toISOString(),
...system,
openclaw_version: openclaw.version,
openclaw_agents: openclaw.agents,
openclaw_agent_count: openclaw.agent_count,
openclaw_version: openclaw.openclawVersion,
plugin_version: openclaw.pluginVersion,
agents: openclaw.agents,
};
}
@@ -207,16 +237,20 @@ async function buildPayload() {
async function sendHttpHeartbeat() {
try {
const payload = await buildPayload();
log.debug('Sending HTTP heartbeat...');
const response = await fetch(`${CONFIG.backendUrl}/monitor/server/heartbeat`, {
method: 'POST',
headers: {
const headers = {
'Content-Type': 'application/json',
'X-Server-Identifier': CONFIG.identifier,
'X-Challenge-UUID': CONFIG.challengeUuid,
},
};
if (CONFIG.apiKey) {
headers['X-API-Key'] = CONFIG.apiKey;
}
const response = await fetch(`${CONFIG.backendUrl}/monitor/server/heartbeat-v2`, {
method: 'POST',
headers,
body: JSON.stringify(payload),
});
@@ -241,21 +275,16 @@ async function sendHttpHeartbeat() {
async function reportingLoop() {
while (!isShuttingDown) {
try {
// Try HTTP (WebSocket can be added later)
const success = await sendHttpHeartbeat();
// Calculate next interval with backoff on failure
let interval = CONFIG.reportIntervalSec * 1000;
if (!success) {
// Exponential backoff: max 5 minutes
const backoff = Math.min(consecutiveFailures * 10000, 300000);
interval = Math.max(interval, backoff);
log.info(`Retry in ${interval}ms (backoff)`);
}
// Sleep until next report
await new Promise(resolve => setTimeout(resolve, interval));
} catch (err) {
log.error('Reporting loop error:', err.message);
await new Promise(resolve => setTimeout(resolve, 30000));
@@ -267,14 +296,13 @@ async function reportingLoop() {
* Graceful shutdown
*/
function shutdown() {
log.info('Shutting down sidecar...');
log.info('Shutting down telemetry server...');
isShuttingDown = true;
if (wsConnection) {
wsConnection.close();
}
// Send final heartbeat
sendHttpHeartbeat().finally(() => {
process.exit(0);
});
@@ -285,18 +313,17 @@ process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);
// Start
log.info('HarborForge Monitor Sidecar starting...');
log.info('HarborForge Monitor Telemetry Server starting...');
log.info('Config:', {
identifier: CONFIG.identifier,
backendUrl: CONFIG.backendUrl,
reportIntervalSec: CONFIG.reportIntervalSec,
hasApiKey: !!CONFIG.apiKey,
pluginVersion: CONFIG.pluginVersion,
});
// Validate config
if (!CONFIG.challengeUuid) {
log.error('Missing HF_MONITOR_CHALLENGE_UUID environment variable');
process.exit(1);
if (!CONFIG.apiKey) {
log.warn('Missing HF_MONITOR_API_KEY environment variable - API authentication will fail');
}
// Start reporting loop
reportingLoop();