Compare commits
10 Commits
a148c11e50
...
ab42936408
| Author | SHA1 | Date | |
|---|---|---|---|
| ab42936408 | |||
| 040cde8cad | |||
| 006784db63 | |||
| de4ef87491 | |||
| 55b17e35ea | |||
| 8ebc76931f | |||
| eb43434e48 | |||
| 6d6d00437d | |||
| 0dc824549a | |||
| 0debe835b4 |
5
.gitignore
vendored
Normal file
5
.gitignore
vendored
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
plugin/node_modules/
|
||||||
|
plugin/*.js
|
||||||
|
plugin/*.js.map
|
||||||
|
plugin/*.d.ts
|
||||||
|
plugin/*.d.ts.map
|
||||||
140
README.md
140
README.md
@@ -2,20 +2,39 @@
|
|||||||
|
|
||||||
OpenClaw 插件,将服务器遥测数据流式传输到 HarborForge Monitor。
|
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 │
|
│ OpenClaw Gateway │
|
||||||
│ ┌───────────────────────────────────────────┐ │
|
│ ┌───────────────────────────────────────────┐ │
|
||||||
│ │ HarborForge.OpenclawPlugin (index.mjs) │ │
|
│ │ HarborForge.OpenclawPlugin/plugin/ │ │
|
||||||
│ │ - 生命周期管理 (启动/停止) │ │
|
│ │ - 生命周期管理 (启动/停止) │ │
|
||||||
│ │ - 配置管理 │ │
|
│ │ - 配置管理 │ │
|
||||||
│ └───────────────────────────────────────────┘ │
|
│ └───────────────────────────────────────────┘ │
|
||||||
│ │ │
|
│ │ │
|
||||||
│ ▼ 启动 sidecar │
|
│ ▼ 启动 telemetry server │
|
||||||
│ ┌───────────────────────────────────────────┐ │
|
│ ┌───────────────────────────────────────────┐ │
|
||||||
│ │ Sidecar (sidecar/server.mjs) │ │
|
│ │ HarborForge.OpenclawPlugin/server/ │ │
|
||||||
│ │ - 独立 Node 进程 │ │
|
│ │ - 独立 Node 进程 │ │
|
||||||
│ │ - 收集系统指标 │ │
|
│ │ - 收集系统指标 │ │
|
||||||
│ │ - 收集 OpenClaw 状态 │ │
|
│ │ - 收集 OpenClaw 状态 │ │
|
||||||
@@ -23,7 +42,7 @@ OpenClaw 插件,将服务器遥测数据流式传输到 HarborForge Monitor。
|
|||||||
│ └───────────────────────────────────────────┘ │
|
│ └───────────────────────────────────────────┘ │
|
||||||
└─────────────────────────────────────────────────┘
|
└─────────────────────────────────────────────────┘
|
||||||
│
|
│
|
||||||
▼ HTTP/WebSocket
|
▼ HTTP
|
||||||
┌─────────────────────┐
|
┌─────────────────────┐
|
||||||
│ HarborForge Monitor │
|
│ HarborForge Monitor │
|
||||||
└─────────────────────┘
|
└─────────────────────┘
|
||||||
@@ -31,44 +50,58 @@ OpenClaw 插件,将服务器遥测数据流式传输到 HarborForge Monitor。
|
|||||||
|
|
||||||
## 安装
|
## 安装
|
||||||
|
|
||||||
### 1. 复制插件到 OpenClaw 插件目录
|
### 快速安装
|
||||||
|
|
||||||
```bash
|
```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
|
```bash
|
||||||
2. 进入 Server Management
|
# 仅构建不安装
|
||||||
3. 点击 "Register New Server"
|
node scripts/install.mjs --build-only
|
||||||
4. 获取 `challengeUuid`
|
|
||||||
|
|
||||||
### 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
|
```json
|
||||||
{
|
{
|
||||||
"plugins": {
|
"plugins": {
|
||||||
"harborforge-monitor": {
|
"entries": {
|
||||||
"enabled": true,
|
"harborforge-monitor": {
|
||||||
"backendUrl": "https://monitor.hangman-lab.top",
|
"enabled": true,
|
||||||
"identifier": "my-server-01",
|
"config": {
|
||||||
"challengeUuid": "your-challenge-uuid-here",
|
"enabled": true,
|
||||||
"reportIntervalSec": 30,
|
"backendUrl": "https://monitor.hangman-lab.top",
|
||||||
"httpFallbackIntervalSec": 60,
|
"identifier": "my-server-01",
|
||||||
"logLevel": "info"
|
"apiKey": "your-api-key-here",
|
||||||
|
"reportIntervalSec": 30,
|
||||||
|
"httpFallbackIntervalSec": 60,
|
||||||
|
"logLevel": "info"
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### 4. 重启 OpenClaw Gateway
|
3. 重启 OpenClaw Gateway:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
openclaw gateway restart
|
openclaw gateway restart
|
||||||
@@ -79,9 +112,9 @@ openclaw gateway restart
|
|||||||
| 选项 | 类型 | 默认值 | 说明 |
|
| 选项 | 类型 | 默认值 | 说明 |
|
||||||
|------|------|--------|------|
|
|------|------|--------|------|
|
||||||
| `enabled` | boolean | `true` | 是否启用插件 |
|
| `enabled` | boolean | `true` | 是否启用插件 |
|
||||||
| `backendUrl` | string | `"https://monitor.hangman-lab.top"` | Monitor 后端地址 |
|
| `backendUrl` | string | `https://monitor.hangman-lab.top` | Monitor 后端地址 |
|
||||||
| `identifier` | string | 自动检测 hostname | 服务器标识符 |
|
| `identifier` | string | 自动检测 hostname | 服务器标识符 |
|
||||||
| `challengeUuid` | string | 必填 | 注册挑战 UUID |
|
| `apiKey` | string | 必填 | HarborForge Monitor 生成的服务器 API Key |
|
||||||
| `reportIntervalSec` | number | `30` | 报告间隔(秒) |
|
| `reportIntervalSec` | number | `30` | 报告间隔(秒) |
|
||||||
| `httpFallbackIntervalSec` | number | `60` | HTTP 回退间隔(秒) |
|
| `httpFallbackIntervalSec` | number | `60` | HTTP 回退间隔(秒) |
|
||||||
| `logLevel` | string | `"info"` | 日志级别: debug/info/warn/error |
|
| `logLevel` | string | `"info"` | 日志级别: debug/info/warn/error |
|
||||||
@@ -103,52 +136,37 @@ openclaw gateway restart
|
|||||||
- Agent 数量
|
- Agent 数量
|
||||||
- Agent 列表 (id, name, status)
|
- Agent 列表 (id, name, status)
|
||||||
|
|
||||||
## 故障排查
|
## 卸载
|
||||||
|
|
||||||
### 查看日志
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 查看 Gateway 日志
|
node scripts/install.mjs --uninstall
|
||||||
openclaw gateway logs | grep HF-Monitor
|
|
||||||
|
|
||||||
# 或者直接查看 sidecar 输出(如果独立运行)
|
|
||||||
node sidecar/server.mjs 2>&1 | tee monitor.log
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### 检查状态
|
|
||||||
|
|
||||||
在 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
|
```bash
|
||||||
cd sidecar
|
cd plugin
|
||||||
HF_MONITOR_CHALLENGE_UUID=test-uuid \
|
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_BACKEND_URL=http://localhost:8000 \
|
||||||
HF_MONITOR_LOG_LEVEL=debug \
|
HF_MONITOR_LOG_LEVEL=debug \
|
||||||
node server.mjs
|
node telemetry.mjs
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## 依赖
|
||||||
|
|
||||||
|
- Node.js 18+
|
||||||
|
- OpenClaw Gateway
|
||||||
|
|
||||||
## 文档
|
## 文档
|
||||||
|
|
||||||
- [监控连接器规划](./docs/monitor-server-connector-plan.md) - 原始设计文档
|
- [监控连接器规划](./docs/monitor-server-connector-plan.md) - 原始设计文档
|
||||||
|
|||||||
@@ -1,112 +1,47 @@
|
|||||||
# HarborForge OpenClaw Server Connector Plugin — Project Plan
|
# Monitor Server Connector Plan
|
||||||
|
|
||||||
## 1) Goal
|
## Current design
|
||||||
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.
|
|
||||||
|
|
||||||
## 2) Scope
|
The plugin uses:
|
||||||
- **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.
|
|
||||||
|
|
||||||
## 3) Non-Goals
|
- **HTTP heartbeat** to `/monitor/server/heartbeat-v2`
|
||||||
- No UI in the plugin.
|
- **API Key authentication** via `X-API-Key`
|
||||||
- No provider billing calls from plugin.
|
- **Gateway lifecycle hooks**: `gateway_start` / `gateway_stop`
|
||||||
- No multi-tenant auth beyond challenge + server identifier.
|
|
||||||
|
|
||||||
## 4) Architecture
|
## No longer used
|
||||||
```
|
|
||||||
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
|
|
||||||
```
|
|
||||||
|
|
||||||
### 4.1 Config
|
The following design has been retired:
|
||||||
- `backend_url`
|
|
||||||
- `identifier`
|
|
||||||
- `challenge_uuid`
|
|
||||||
- `report_interval_sec` (default: 20-30s)
|
|
||||||
- `http_fallback_interval_sec` (default: 60s)
|
|
||||||
- `log_level`
|
|
||||||
|
|
||||||
### 4.2 Security
|
- challenge UUID
|
||||||
- Fetch public key: `GET /monitor/public/server-public-key`
|
- RSA public key fetch
|
||||||
- Encrypt payload with RSA-OAEP
|
- encrypted handshake payload
|
||||||
- Include `nonce` + `ts` (UTC) to prevent replay
|
- WebSocket telemetry
|
||||||
- **Challenge valid**: 10 minutes
|
|
||||||
- **Offline threshold**: 7 minutes
|
|
||||||
|
|
||||||
## 5) Communication Flow
|
## Runtime 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.
|
|
||||||
|
|
||||||
### 5.2 Fallback (HTTP)
|
1. Gateway loads `harborforge-monitor`
|
||||||
If WS fails:
|
2. Plugin reads config from OpenClaw plugin config
|
||||||
- POST telemetry to `/monitor/server/heartbeat` with same payload fields.
|
3. On `gateway_start`, plugin launches `server/telemetry.mjs`
|
||||||
- Retry with exponential backoff (cap 5–10 min).
|
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",
|
"identifier": "vps.t1",
|
||||||
openclaw_version: "x.y.z",
|
"openclaw_version": "OpenClaw 2026.3.13 (61d171a)",
|
||||||
cpu_pct: 12.5,
|
"plugin_version": "0.1.0",
|
||||||
mem_pct: 41.2,
|
"agents": [],
|
||||||
disk_pct: 62.0,
|
"cpu_pct": 10.5,
|
||||||
swap_pct: 0.0,
|
"mem_pct": 52.1,
|
||||||
agents: [ { id: "a1", name: "agent", status: "running" } ],
|
"disk_pct": 81.0,
|
||||||
last_seen_at: "2026-03-11T21:00:00Z"
|
"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 (2–3 days)**
|
|
||||||
- CLI config loader + HTTP heartbeat
|
|
||||||
- See online + metrics in Monitor
|
|
||||||
|
|
||||||
**M2 – WS realtime (2–3 days)**
|
|
||||||
- Full handshake + WS streaming
|
|
||||||
- Reconnect & fallback logic
|
|
||||||
|
|
||||||
**M3 – Packaging (1–2 days)**
|
|
||||||
- systemd unit + sample config
|
|
||||||
- installation script
|
|
||||||
|
|
||||||
**M4 – Hardening & Docs (1–2 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
178
index.mjs
@@ -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');
|
|
||||||
}
|
|
||||||
@@ -3,10 +3,10 @@
|
|||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"description": "OpenClaw plugin for HarborForge Monitor - streams server telemetry",
|
"description": "OpenClaw plugin for HarborForge Monitor - streams server telemetry",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "index.mjs",
|
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "node index.mjs",
|
"build": "cd plugin && npm run build",
|
||||||
"sidecar": "node sidecar/server.mjs"
|
"install": "node scripts/install.mjs",
|
||||||
|
"uninstall": "node scripts/install.mjs --uninstall"
|
||||||
},
|
},
|
||||||
"keywords": ["openclaw", "plugin", "monitoring", "harborforge"],
|
"keywords": ["openclaw", "plugin", "monitoring", "harborforge"],
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
|||||||
15
plugin/core/live-config.d.ts
vendored
Normal file
15
plugin/core/live-config.d.ts
vendored
Normal 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
|
||||||
1
plugin/core/live-config.d.ts.map
Normal file
1
plugin/core/live-config.d.ts.map
Normal 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"}
|
||||||
23
plugin/core/live-config.js
Normal file
23
plugin/core/live-config.js
Normal 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
|
||||||
1
plugin/core/live-config.js.map
Normal file
1
plugin/core/live-config.js.map
Normal 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"}
|
||||||
39
plugin/core/live-config.ts
Normal file
39
plugin/core/live-config.ts
Normal 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
184
plugin/index.ts
Normal 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');
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
"name": "HarborForge Monitor",
|
"name": "HarborForge Monitor",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"description": "Server monitoring plugin for HarborForge - streams telemetry to Monitor",
|
"description": "Server monitoring plugin for HarborForge - streams telemetry to Monitor",
|
||||||
"entry": "./index.mjs",
|
"entry": "./index.js",
|
||||||
"configSchema": {
|
"configSchema": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"additionalProperties": false,
|
"additionalProperties": false,
|
||||||
@@ -22,9 +22,9 @@
|
|||||||
"type": "string",
|
"type": "string",
|
||||||
"description": "Server identifier (auto-detected from hostname if not set)"
|
"description": "Server identifier (auto-detected from hostname if not set)"
|
||||||
},
|
},
|
||||||
"challengeUuid": {
|
"apiKey": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": "Registration challenge UUID from Monitor"
|
"description": "API Key from HarborForge Monitor admin panel (optional but required for authentication)"
|
||||||
},
|
},
|
||||||
"reportIntervalSec": {
|
"reportIntervalSec": {
|
||||||
"type": "number",
|
"type": "number",
|
||||||
@@ -42,7 +42,6 @@
|
|||||||
"default": "info",
|
"default": "info",
|
||||||
"description": "Logging level"
|
"description": "Logging level"
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
"required": ["challengeUuid"]
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
48
plugin/package-lock.json
generated
Normal file
48
plugin/package-lock.json
generated
Normal 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
15
plugin/package.json
Normal 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
17
plugin/tsconfig.json
Normal 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
322
scripts/install.mjs
Normal 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();
|
||||||
@@ -1,28 +1,30 @@
|
|||||||
/**
|
/**
|
||||||
* HarborForge Monitor Sidecar Server
|
* HarborForge Monitor Telemetry Server
|
||||||
*
|
*
|
||||||
* Runs as separate process from Gateway.
|
* Runs as separate process from Gateway.
|
||||||
* Collects system metrics and OpenClaw status, sends to Monitor.
|
* Collects system metrics and OpenClaw status, sends to Monitor.
|
||||||
*/
|
*/
|
||||||
import { createServer } from 'http';
|
import { readFile, access, readdir } from 'fs/promises';
|
||||||
import { readFile, access } from 'fs/promises';
|
|
||||||
import { constants } from 'fs';
|
import { constants } from 'fs';
|
||||||
import { exec } from 'child_process';
|
import { exec } from 'child_process';
|
||||||
import { promisify } from 'util';
|
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);
|
const execAsync = promisify(exec);
|
||||||
|
|
||||||
// Config from environment (set by plugin)
|
// Config from environment (set by plugin)
|
||||||
|
const openclawPath = process.env.OPENCLAW_PATH || `${process.env.HOME}/.openclaw`;
|
||||||
const CONFIG = {
|
const CONFIG = {
|
||||||
backendUrl: process.env.HF_MONITOR_BACKEND_URL || 'https://monitor.hangman-lab.top',
|
backendUrl: process.env.HF_MONITOR_BACKEND_URL || 'https://monitor.hangman-lab.top',
|
||||||
identifier: process.env.HF_MONITOR_IDENTIFIER || hostname(),
|
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),
|
reportIntervalSec: parseInt(process.env.HF_MONITOR_REPORT_INTERVAL || '30', 10),
|
||||||
httpFallbackIntervalSec: parseInt(process.env.HF_MONITOR_HTTP_FALLBACK_INTERVAL || '60', 10),
|
httpFallbackIntervalSec: parseInt(process.env.HF_MONITOR_HTTP_FALLBACK_INTERVAL || '60', 10),
|
||||||
logLevel: process.env.HF_MONITOR_LOG_LEVEL || 'info',
|
logLevel: process.env.HF_MONITOR_LOG_LEVEL || 'info',
|
||||||
openclawPath: process.env.OPENCLAW_PATH || `${process.env.HOME}/.openclaw`,
|
openclawPath,
|
||||||
openclawVersion: process.env.OPENCLAW_VERSION || 'unknown',
|
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
|
// Logging
|
||||||
@@ -38,25 +40,19 @@ let wsConnection = null;
|
|||||||
let lastSuccessfulSend = null;
|
let lastSuccessfulSend = null;
|
||||||
let consecutiveFailures = 0;
|
let consecutiveFailures = 0;
|
||||||
let isShuttingDown = false;
|
let isShuttingDown = false;
|
||||||
|
let cachedOpenclawVersion = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Collect system metrics
|
* Collect system metrics
|
||||||
*/
|
*/
|
||||||
async function collectSystemMetrics() {
|
async function collectSystemMetrics() {
|
||||||
try {
|
try {
|
||||||
// CPU usage (average over 1 second)
|
|
||||||
const cpuUsage = await getCpuUsage();
|
const cpuUsage = await getCpuUsage();
|
||||||
|
|
||||||
// Memory
|
|
||||||
const memTotal = totalmem();
|
const memTotal = totalmem();
|
||||||
const memFree = freemem();
|
const memFree = freemem();
|
||||||
const memUsed = memTotal - memFree;
|
const memUsed = memTotal - memFree;
|
||||||
|
|
||||||
// Disk usage
|
|
||||||
const diskInfo = await getDiskUsage();
|
const diskInfo = await getDiskUsage();
|
||||||
|
const loadAvg = platform() !== 'win32' ? loadavg() : [0, 0, 0];
|
||||||
// Load average
|
|
||||||
const loadAvg = platform() !== 'win32' ? require('os').loadavg() : [0, 0, 0];
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
cpu_pct: cpuUsage,
|
cpu_pct: cpuUsage,
|
||||||
@@ -67,8 +63,12 @@ async function collectSystemMetrics() {
|
|||||||
disk_used_gb: Math.round(diskInfo.usedGB * 10) / 10,
|
disk_used_gb: Math.round(diskInfo.usedGB * 10) / 10,
|
||||||
disk_total_gb: Math.round(diskInfo.totalGB * 10) / 10,
|
disk_total_gb: Math.round(diskInfo.totalGB * 10) / 10,
|
||||||
swap_pct: diskInfo.swapUsedPct || 0,
|
swap_pct: diskInfo.swapUsedPct || 0,
|
||||||
uptime_sec: Math.floor(uptime()),
|
uptime_seconds: Math.floor(uptime()),
|
||||||
load_avg_1m: Math.round(loadAvg[0] * 100) / 100,
|
load_avg: [
|
||||||
|
Math.round(loadAvg[0] * 100) / 100,
|
||||||
|
Math.round(loadAvg[1] * 100) / 100,
|
||||||
|
Math.round(loadAvg[2] * 100) / 100,
|
||||||
|
],
|
||||||
platform: platform(),
|
platform: platform(),
|
||||||
hostname: hostname(),
|
hostname: hostname(),
|
||||||
};
|
};
|
||||||
@@ -93,7 +93,6 @@ async function getCpuUsage() {
|
|||||||
return isNaN(usage) ? 0 : Math.round(usage * 10) / 10;
|
return isNaN(usage) ? 0 : Math.round(usage * 10) / 10;
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// Fallback: calculate from /proc/stat on Linux
|
|
||||||
try {
|
try {
|
||||||
const stat = await readFile('/proc/stat', 'utf8');
|
const stat = await readFile('/proc/stat', 'utf8');
|
||||||
const cpuLine = stat.split('\n')[0];
|
const cpuLine = stat.split('\n')[0];
|
||||||
@@ -129,9 +128,6 @@ async function getDiskUsage() {
|
|||||||
return { totalGB: 0, usedGB: 0, usedPct: 0 };
|
return { totalGB: 0, usedGB: 0, usedPct: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse size string (like '50G' or '100M') to GB
|
|
||||||
*/
|
|
||||||
function parseSizeToGB(size) {
|
function parseSizeToGB(size) {
|
||||||
const num = parseFloat(size);
|
const num = parseFloat(size);
|
||||||
if (size.includes('T')) return num * 1024;
|
if (size.includes('T')) return num * 1024;
|
||||||
@@ -141,15 +137,33 @@ function parseSizeToGB(size) {
|
|||||||
return num;
|
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
|
* Collect OpenClaw status
|
||||||
*/
|
*/
|
||||||
async function collectOpenclawStatus() {
|
async function collectOpenclawStatus() {
|
||||||
try {
|
try {
|
||||||
const agents = await getOpenclawAgents();
|
const [agents, openclawVersion] = await Promise.all([
|
||||||
|
getOpenclawAgents(),
|
||||||
|
resolveOpenclawVersion(),
|
||||||
|
]);
|
||||||
return {
|
return {
|
||||||
version: CONFIG.openclawVersion,
|
openclawVersion,
|
||||||
|
pluginVersion: CONFIG.pluginVersion,
|
||||||
agent_count: agents.length,
|
agent_count: agents.length,
|
||||||
agents: agents.map(a => ({
|
agents: agents.map(a => ({
|
||||||
id: a.id,
|
id: a.id,
|
||||||
@@ -159,7 +173,12 @@ async function collectOpenclawStatus() {
|
|||||||
};
|
};
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
log.debug('Failed to collect OpenClaw status:', err.message);
|
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() {
|
async function getOpenclawAgents() {
|
||||||
try {
|
try {
|
||||||
// Try to read agent config/state from OpenClaw directory
|
|
||||||
const agentConfigPath = `${CONFIG.openclawPath}/agents.json`;
|
const agentConfigPath = `${CONFIG.openclawPath}/agents.json`;
|
||||||
try {
|
try {
|
||||||
await access(agentConfigPath, constants.R_OK);
|
await access(agentConfigPath, constants.R_OK);
|
||||||
const data = JSON.parse(await readFile(agentConfigPath, 'utf8'));
|
const data = JSON.parse(await readFile(agentConfigPath, 'utf8'));
|
||||||
return data.agents || [];
|
if (Array.isArray(data.agents) && data.agents.length > 0) {
|
||||||
|
return data.agents;
|
||||||
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// Fallback: return empty list
|
// fall through to directory-based discovery
|
||||||
return [];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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 {
|
} catch {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
@@ -192,12 +223,11 @@ async function buildPayload() {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
identifier: CONFIG.identifier,
|
identifier: CONFIG.identifier,
|
||||||
challenge_uuid: CONFIG.challengeUuid,
|
|
||||||
timestamp: new Date().toISOString(),
|
timestamp: new Date().toISOString(),
|
||||||
...system,
|
...system,
|
||||||
openclaw_version: openclaw.version,
|
openclaw_version: openclaw.openclawVersion,
|
||||||
openclaw_agents: openclaw.agents,
|
plugin_version: openclaw.pluginVersion,
|
||||||
openclaw_agent_count: openclaw.agent_count,
|
agents: openclaw.agents,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -207,16 +237,20 @@ async function buildPayload() {
|
|||||||
async function sendHttpHeartbeat() {
|
async function sendHttpHeartbeat() {
|
||||||
try {
|
try {
|
||||||
const payload = await buildPayload();
|
const payload = await buildPayload();
|
||||||
|
|
||||||
log.debug('Sending HTTP heartbeat...');
|
log.debug('Sending HTTP heartbeat...');
|
||||||
|
|
||||||
const response = await fetch(`${CONFIG.backendUrl}/monitor/server/heartbeat`, {
|
const headers = {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'X-Server-Identifier': CONFIG.identifier,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (CONFIG.apiKey) {
|
||||||
|
headers['X-API-Key'] = CONFIG.apiKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await fetch(`${CONFIG.backendUrl}/monitor/server/heartbeat-v2`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers,
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Server-Identifier': CONFIG.identifier,
|
|
||||||
'X-Challenge-UUID': CONFIG.challengeUuid,
|
|
||||||
},
|
|
||||||
body: JSON.stringify(payload),
|
body: JSON.stringify(payload),
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -241,21 +275,16 @@ async function sendHttpHeartbeat() {
|
|||||||
async function reportingLoop() {
|
async function reportingLoop() {
|
||||||
while (!isShuttingDown) {
|
while (!isShuttingDown) {
|
||||||
try {
|
try {
|
||||||
// Try HTTP (WebSocket can be added later)
|
|
||||||
const success = await sendHttpHeartbeat();
|
const success = await sendHttpHeartbeat();
|
||||||
|
|
||||||
// Calculate next interval with backoff on failure
|
|
||||||
let interval = CONFIG.reportIntervalSec * 1000;
|
let interval = CONFIG.reportIntervalSec * 1000;
|
||||||
if (!success) {
|
if (!success) {
|
||||||
// Exponential backoff: max 5 minutes
|
|
||||||
const backoff = Math.min(consecutiveFailures * 10000, 300000);
|
const backoff = Math.min(consecutiveFailures * 10000, 300000);
|
||||||
interval = Math.max(interval, backoff);
|
interval = Math.max(interval, backoff);
|
||||||
log.info(`Retry in ${interval}ms (backoff)`);
|
log.info(`Retry in ${interval}ms (backoff)`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sleep until next report
|
|
||||||
await new Promise(resolve => setTimeout(resolve, interval));
|
await new Promise(resolve => setTimeout(resolve, interval));
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
log.error('Reporting loop error:', err.message);
|
log.error('Reporting loop error:', err.message);
|
||||||
await new Promise(resolve => setTimeout(resolve, 30000));
|
await new Promise(resolve => setTimeout(resolve, 30000));
|
||||||
@@ -267,14 +296,13 @@ async function reportingLoop() {
|
|||||||
* Graceful shutdown
|
* Graceful shutdown
|
||||||
*/
|
*/
|
||||||
function shutdown() {
|
function shutdown() {
|
||||||
log.info('Shutting down sidecar...');
|
log.info('Shutting down telemetry server...');
|
||||||
isShuttingDown = true;
|
isShuttingDown = true;
|
||||||
|
|
||||||
if (wsConnection) {
|
if (wsConnection) {
|
||||||
wsConnection.close();
|
wsConnection.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Send final heartbeat
|
|
||||||
sendHttpHeartbeat().finally(() => {
|
sendHttpHeartbeat().finally(() => {
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
});
|
});
|
||||||
@@ -285,18 +313,17 @@ process.on('SIGTERM', shutdown);
|
|||||||
process.on('SIGINT', shutdown);
|
process.on('SIGINT', shutdown);
|
||||||
|
|
||||||
// Start
|
// Start
|
||||||
log.info('HarborForge Monitor Sidecar starting...');
|
log.info('HarborForge Monitor Telemetry Server starting...');
|
||||||
log.info('Config:', {
|
log.info('Config:', {
|
||||||
identifier: CONFIG.identifier,
|
identifier: CONFIG.identifier,
|
||||||
backendUrl: CONFIG.backendUrl,
|
backendUrl: CONFIG.backendUrl,
|
||||||
reportIntervalSec: CONFIG.reportIntervalSec,
|
reportIntervalSec: CONFIG.reportIntervalSec,
|
||||||
|
hasApiKey: !!CONFIG.apiKey,
|
||||||
|
pluginVersion: CONFIG.pluginVersion,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Validate config
|
if (!CONFIG.apiKey) {
|
||||||
if (!CONFIG.challengeUuid) {
|
log.warn('Missing HF_MONITOR_API_KEY environment variable - API authentication will fail');
|
||||||
log.error('Missing HF_MONITOR_CHALLENGE_UUID environment variable');
|
|
||||||
process.exit(1);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Start reporting loop
|
|
||||||
reportingLoop();
|
reportingLoop();
|
||||||
Reference in New Issue
Block a user