Merge pull request 'Merge dev-2026-03-21 into main' (#3) from dev-2026-03-21 into main
Reviewed-on: #3
This commit was merged in pull request #3.
This commit is contained in:
179
README.md
179
README.md
@@ -1,96 +1,93 @@
|
|||||||
# HarborForge OpenClaw Plugin
|
# HarborForge OpenClaw Plugin
|
||||||
|
|
||||||
OpenClaw 插件,将服务器遥测数据流式传输到 HarborForge Monitor。
|
OpenClaw 插件:向 HarborForge Monitor 暴露 OpenClaw 侧元数据,并提供可选的本地桥接能力;安装时也可顺带安装 `hf` CLI。
|
||||||
|
|
||||||
|
## 当前状态
|
||||||
|
|
||||||
|
- 插件注册名:`harbor-forge`
|
||||||
|
- 旧 sidecar `server/` 架构已移除
|
||||||
|
- 监控桥接走本地 `monitor_port`
|
||||||
|
- 安装脚本支持 `--install-cli`
|
||||||
|
- `skills/hf/` 仅在 `--install-cli` 时一并安装
|
||||||
|
|
||||||
## 项目结构
|
## 项目结构
|
||||||
|
|
||||||
```
|
```text
|
||||||
HarborForge.OpenclawPlugin/
|
HarborForge.OpenclawPlugin/
|
||||||
├── package.json # 根 package.json
|
├── package.json
|
||||||
├── README.md # 本文档
|
├── README.md
|
||||||
├── plugin/ # OpenClaw 插件代码
|
├── plugin/
|
||||||
│ ├── openclaw.plugin.json # 插件定义
|
│ ├── openclaw.plugin.json
|
||||||
│ ├── index.ts # 插件入口
|
│ ├── index.ts
|
||||||
│ ├── package.json # 插件依赖
|
│ ├── core/
|
||||||
│ └── tsconfig.json # TypeScript 配置
|
│ │ ├── live-config.ts
|
||||||
├── server/ # Sidecar 服务器
|
│ │ └── monitor-bridge.ts
|
||||||
│ └── telemetry.mjs # 遥测数据收集和发送
|
│ └── package.json
|
||||||
├── skills/ # OpenClaw 技能
|
├── skills/
|
||||||
│ └── (技能文件)
|
│ └── hf/
|
||||||
|
│ └── SKILL.md
|
||||||
└── scripts/
|
└── scripts/
|
||||||
└── install.mjs # 安装脚本
|
└── install.mjs
|
||||||
```
|
|
||||||
|
|
||||||
## 架构
|
|
||||||
|
|
||||||
```
|
|
||||||
┌─────────────────────────────────────────────────┐
|
|
||||||
│ OpenClaw Gateway │
|
|
||||||
│ ┌───────────────────────────────────────────┐ │
|
|
||||||
│ │ HarborForge.OpenclawPlugin/plugin/ │ │
|
|
||||||
│ │ - 生命周期管理 (启动/停止) │ │
|
|
||||||
│ │ - 配置管理 │ │
|
|
||||||
│ └───────────────────────────────────────────┘ │
|
|
||||||
│ │ │
|
|
||||||
│ ▼ 启动 telemetry server │
|
|
||||||
│ ┌───────────────────────────────────────────┐ │
|
|
||||||
│ │ HarborForge.OpenclawPlugin/server/ │ │
|
|
||||||
│ │ - 独立 Node 进程 │ │
|
|
||||||
│ │ - 收集系统指标 │ │
|
|
||||||
│ │ - 收集 OpenClaw 状态 │ │
|
|
||||||
│ │ - 发送到 HarborForge Monitor │ │
|
|
||||||
│ └───────────────────────────────────────────┘ │
|
|
||||||
└─────────────────────────────────────────────────┘
|
|
||||||
│
|
|
||||||
▼ HTTP
|
|
||||||
┌─────────────────────┐
|
|
||||||
│ HarborForge Monitor │
|
|
||||||
└─────────────────────┘
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## 安装
|
## 安装
|
||||||
|
|
||||||
### 快速安装
|
### 普通安装
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 克隆仓库
|
|
||||||
git clone https://git.hangman-lab.top/zhi/HarborForge.OpenclawPlugin.git
|
|
||||||
cd HarborForge.OpenclawPlugin
|
|
||||||
|
|
||||||
# 运行安装脚本
|
|
||||||
node scripts/install.mjs
|
node scripts/install.mjs
|
||||||
```
|
```
|
||||||
|
|
||||||
### 开发安装
|
这会:
|
||||||
|
- 构建并安装 OpenClaw 插件
|
||||||
|
- 复制常规 skills
|
||||||
|
- **不会**安装 `hf` 二进制
|
||||||
|
- **不会**复制 `skills/hf/`
|
||||||
|
|
||||||
|
### 安装插件 + `hf` CLI
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 仅构建不安装
|
node scripts/install.mjs --install-cli
|
||||||
|
```
|
||||||
|
|
||||||
|
这会额外:
|
||||||
|
- 构建 `HarborForge.Cli`
|
||||||
|
- 安装 `hf` 到 `~/.openclaw/bin/hf`
|
||||||
|
- `chmod +x ~/.openclaw/bin/hf`
|
||||||
|
- 复制 `skills/hf/` 到 OpenClaw profile skills 目录
|
||||||
|
|
||||||
|
### 常用选项
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 仅构建
|
||||||
node scripts/install.mjs --build-only
|
node scripts/install.mjs --build-only
|
||||||
|
|
||||||
# 指定 OpenClaw 路径
|
# 指定 OpenClaw profile
|
||||||
node scripts/install.mjs --openclaw-profile-path /custom/path/.openclaw
|
node scripts/install.mjs --openclaw-profile-path /custom/path/.openclaw
|
||||||
|
|
||||||
# 详细输出
|
# 详细日志
|
||||||
node scripts/install.mjs --verbose
|
node scripts/install.mjs --verbose
|
||||||
|
|
||||||
|
# 卸载
|
||||||
|
node scripts/install.mjs --uninstall
|
||||||
```
|
```
|
||||||
|
|
||||||
## 配置
|
## 配置
|
||||||
|
|
||||||
1. 在 HarborForge Monitor 中注册服务器,并生成 `apiKey`
|
编辑 `~/.openclaw/openclaw.json`:
|
||||||
|
|
||||||
2. 编辑 `~/.openclaw/openclaw.json`:
|
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"plugins": {
|
"plugins": {
|
||||||
"entries": {
|
"entries": {
|
||||||
"harborforge-monitor": {
|
"harbor-forge": {
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
"config": {
|
"config": {
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
"backendUrl": "https://monitor.hangman-lab.top",
|
"backendUrl": "https://monitor.hangman-lab.top",
|
||||||
"identifier": "my-server-01",
|
"identifier": "my-server-01",
|
||||||
"apiKey": "your-api-key-here",
|
"apiKey": "your-api-key-here",
|
||||||
|
"monitor_port": 9100,
|
||||||
"reportIntervalSec": 30,
|
"reportIntervalSec": 30,
|
||||||
"httpFallbackIntervalSec": 60,
|
"httpFallbackIntervalSec": 60,
|
||||||
"logLevel": "info"
|
"logLevel": "info"
|
||||||
@@ -101,72 +98,68 @@ node scripts/install.mjs --verbose
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
3. 重启 OpenClaw Gateway:
|
> 说明:`monitor_port` 是当前主字段;为兼容旧配置,插件仍接受 `monitorPort`。
|
||||||
|
|
||||||
|
然后重启:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
openclaw gateway restart
|
openclaw gateway restart
|
||||||
```
|
```
|
||||||
|
|
||||||
## 配置选项
|
## 配置项
|
||||||
|
|
||||||
| 选项 | 类型 | 默认值 | 说明 |
|
| 选项 | 类型 | 默认值 | 说明 |
|
||||||
|------|------|--------|------|
|
|------|------|--------|------|
|
||||||
| `enabled` | boolean | `true` | 是否启用插件 |
|
| `enabled` | boolean | `true` | 是否启用插件 |
|
||||||
| `backendUrl` | string | `https://monitor.hangman-lab.top` | Monitor 后端地址 |
|
| `backendUrl` | string | `https://monitor.hangman-lab.top` | HarborForge Monitor 后端地址 |
|
||||||
| `identifier` | string | 自动检测 hostname | 服务器标识符 |
|
| `identifier` | string | 主机名 | 服务器标识符 |
|
||||||
| `apiKey` | string | 必填 | HarborForge Monitor 生成的服务器 API Key |
|
| `apiKey` | string | 无 | HarborForge Monitor 生成的服务器 API Key |
|
||||||
|
| `monitor_port` | number | 无 | 本地桥接端口;插件通过 `127.0.0.1:<monitor_port>` 与 HarborForge.Monitor 通信 |
|
||||||
| `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` |
|
||||||
|
|
||||||
## 收集的指标
|
## 本地桥接说明
|
||||||
|
|
||||||
### 系统指标
|
当插件配置了 `monitor_port`,并且 HarborForge.Monitor 也使用相同的 `MONITOR_PORT` 时:
|
||||||
- CPU 使用率 (%)
|
|
||||||
- 内存使用率 (%)、已用/总量 (MB)
|
|
||||||
- 磁盘使用率 (%)、已用/总量 (GB)
|
|
||||||
- 交换分区使用率 (%)
|
|
||||||
- 系统运行时间 (秒)
|
|
||||||
- 1分钟平均负载
|
|
||||||
- 平台 (linux/darwin/win32)
|
|
||||||
- 主机名
|
|
||||||
|
|
||||||
### OpenClaw 指标
|
- Monitor 在 `127.0.0.1:<MONITOR_PORT>` 提供本地桥接服务
|
||||||
- OpenClaw 版本
|
- 插件可探测 `GET /health`
|
||||||
- Agent 数量
|
- 插件工具 `harborforge_monitor_telemetry` 可读取 `GET /telemetry`
|
||||||
- Agent 列表 (id, name, status)
|
- 如果桥接端口未配置或不可达,插件仍可正常运行
|
||||||
|
|
||||||
## 卸载
|
也就是说,这条链路是**可选增强**,不是插件启动或 Monitor 心跳的前置条件。
|
||||||
|
|
||||||
```bash
|
## 插件提供的信息
|
||||||
node scripts/install.mjs --uninstall
|
|
||||||
```
|
### OpenClaw 元数据
|
||||||
|
- OpenClaw version
|
||||||
|
- plugin version
|
||||||
|
- 标识符 / 主机名
|
||||||
|
- 时间戳
|
||||||
|
|
||||||
|
### 系统快照
|
||||||
|
- uptime
|
||||||
|
- memory total/free/used/usagePercent
|
||||||
|
- load avg1/avg5/avg15
|
||||||
|
- platform
|
||||||
|
|
||||||
## 开发
|
## 开发
|
||||||
|
|
||||||
### 构建插件
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd plugin
|
cd plugin
|
||||||
npm install
|
npm install
|
||||||
npm run build
|
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 telemetry.mjs
|
|
||||||
```
|
|
||||||
|
|
||||||
## 依赖
|
## 依赖
|
||||||
|
|
||||||
- Node.js 18+
|
- Node.js 18+
|
||||||
- OpenClaw Gateway
|
- OpenClaw Gateway
|
||||||
|
- Go 1.20+(仅 `--install-cli` 需要)
|
||||||
|
|
||||||
## 文档
|
## 相关提示
|
||||||
|
|
||||||
- [监控连接器规划](./docs/monitor-server-connector-plan.md) - 原始设计文档
|
- 安装 `hf` 后,建议把 `~/.openclaw/bin` 加到 `PATH`
|
||||||
|
- Agent 使用 `hf` 时,优先试 `hf --help-brief`
|
||||||
|
- 完整命令树看 `hf --help`
|
||||||
|
|||||||
@@ -2,46 +2,53 @@
|
|||||||
|
|
||||||
## Current design
|
## Current design
|
||||||
|
|
||||||
The plugin uses:
|
The plugin and Monitor communicate over a local bridge port (`monitor_port` / `MONITOR_PORT`).
|
||||||
|
|
||||||
- **HTTP heartbeat** to `/monitor/server/heartbeat-v2`
|
### Data flow
|
||||||
- **API Key authentication** via `X-API-Key`
|
|
||||||
- **Gateway lifecycle hooks**: `gateway_start` / `gateway_stop`
|
1. **Monitor → Plugin** (GET): Plugin queries `GET /telemetry` on the bridge for host hardware data.
|
||||||
|
2. **Plugin → Monitor** (POST): Plugin pushes OpenClaw metadata via `POST /openclaw` to the bridge.
|
||||||
|
3. **Monitor → Backend**: Monitor heartbeats to `POST /monitor/server/heartbeat-v2` with `X-API-Key`, enriched with any available OpenClaw metadata.
|
||||||
|
|
||||||
|
### Bridge endpoints (on Monitor, 127.0.0.1:MONITOR_PORT)
|
||||||
|
|
||||||
|
| Endpoint | Method | Description |
|
||||||
|
|----------|--------|-------------|
|
||||||
|
| `/health` | GET | Health check, returns monitor version and identifier |
|
||||||
|
| `/telemetry` | GET | Latest hardware telemetry snapshot |
|
||||||
|
| `/openclaw` | POST | Receive OpenClaw metadata from plugin |
|
||||||
|
|
||||||
|
### Plugin behavior
|
||||||
|
|
||||||
|
- On `gateway_start`, plugin begins periodic metadata push (aligned with `reportIntervalSec`).
|
||||||
|
- Initial push is delayed 2s to allow Monitor bridge startup.
|
||||||
|
- If bridge is unreachable, pushes fail silently. Plugin remains fully functional.
|
||||||
|
- On `gateway_stop`, periodic push is stopped.
|
||||||
|
|
||||||
## No longer used
|
## No longer used
|
||||||
|
|
||||||
The following design has been retired:
|
The following design has been retired:
|
||||||
|
|
||||||
- challenge UUID
|
- challenge UUID / RSA handshake / WebSocket telemetry
|
||||||
- RSA public key fetch
|
- Plugin-side `server/` sidecar process
|
||||||
- encrypted handshake payload
|
|
||||||
- WebSocket telemetry
|
|
||||||
|
|
||||||
## Runtime flow
|
## Heartbeat payload
|
||||||
|
|
||||||
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`
|
|
||||||
|
|
||||||
## Payload
|
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"identifier": "vps.t1",
|
"identifier": "vps.t1",
|
||||||
"openclaw_version": "OpenClaw 2026.3.13 (61d171a)",
|
"openclaw_version": "OpenClaw 2026.3.13 (61d171a)",
|
||||||
"plugin_version": "0.1.0",
|
"plugin_version": "0.2.0",
|
||||||
"agents": [],
|
"agents": [],
|
||||||
"cpu_pct": 10.5,
|
"cpu_pct": 10.5,
|
||||||
"mem_pct": 52.1,
|
"mem_pct": 52.1,
|
||||||
"disk_pct": 81.0,
|
"disk_pct": 81.0,
|
||||||
"swap_pct": 0.0,
|
"swap_pct": 0.0,
|
||||||
"load_avg": [0.12, 0.09, 0.03],
|
"load_avg": [0.12, 0.09, 0.03],
|
||||||
"uptime_seconds": 12345
|
"uptime_seconds": 12345,
|
||||||
|
"nginx_installed": true,
|
||||||
|
"nginx_sites": ["default"]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`openclaw_version`, `plugin_version`, and `agents` are optional enrichment from the plugin. If plugin never pushes metadata, these fields are omitted and the heartbeat contains only hardware telemetry.
|
||||||
|
|||||||
@@ -1,14 +1,15 @@
|
|||||||
{
|
{
|
||||||
"name": "harborforge-openclaw-plugin",
|
"name": "harbor-forge-openclaw-plugin",
|
||||||
"version": "0.1.0",
|
"version": "0.2.0",
|
||||||
"description": "OpenClaw plugin for HarborForge Monitor - streams server telemetry",
|
"description": "OpenClaw plugin for HarborForge - project management, monitoring, and CLI integration",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "cd plugin && npm run build",
|
"build": "cd plugin && npm run build",
|
||||||
"install": "node scripts/install.mjs",
|
"install": "node scripts/install.mjs",
|
||||||
|
"install-cli": "node scripts/install.mjs --install-cli",
|
||||||
"uninstall": "node scripts/install.mjs --uninstall"
|
"uninstall": "node scripts/install.mjs --uninstall"
|
||||||
},
|
},
|
||||||
"keywords": ["openclaw", "plugin", "monitoring", "harborforge"],
|
"keywords": ["openclaw", "plugin", "monitoring", "harborforge", "harbor-forge"],
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=18.0.0"
|
"node": ">=18.0.0"
|
||||||
|
|||||||
2
plugin/core/live-config.d.ts
vendored
2
plugin/core/live-config.d.ts
vendored
@@ -3,6 +3,8 @@ export interface HarborForgeMonitorConfig {
|
|||||||
backendUrl?: string;
|
backendUrl?: string;
|
||||||
identifier?: string;
|
identifier?: string;
|
||||||
apiKey?: string;
|
apiKey?: string;
|
||||||
|
monitor_port?: number;
|
||||||
|
monitorPort?: number;
|
||||||
reportIntervalSec?: number;
|
reportIntervalSec?: number;
|
||||||
httpFallbackIntervalSec?: number;
|
httpFallbackIntervalSec?: number;
|
||||||
logLevel?: 'debug' | 'info' | 'warn' | 'error';
|
logLevel?: 'debug' | 'info' | 'warn' | 'error';
|
||||||
|
|||||||
@@ -1 +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"}
|
{"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,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,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,CAgC1B"}
|
||||||
@@ -5,12 +5,21 @@ function getLivePluginConfig(api, fallback) {
|
|||||||
const root = api.config || {};
|
const root = api.config || {};
|
||||||
const plugins = root.plugins || {};
|
const plugins = root.plugins || {};
|
||||||
const entries = plugins.entries || {};
|
const entries = plugins.entries || {};
|
||||||
const entry = entries['harborforge-monitor'] || {};
|
const entry = entries['harbor-forge'] || {};
|
||||||
const cfg = entry.config || {};
|
const cfg = entry.config || {};
|
||||||
if (Object.keys(cfg).length > 0 || Object.keys(entry).length > 0) {
|
if (Object.keys(cfg).length > 0 || Object.keys(entry).length > 0) {
|
||||||
|
const monitorPort = typeof cfg.monitor_port === 'number'
|
||||||
|
? cfg.monitor_port
|
||||||
|
: typeof cfg.monitorPort === 'number'
|
||||||
|
? cfg.monitorPort
|
||||||
|
: typeof fallback.monitor_port === 'number'
|
||||||
|
? fallback.monitor_port
|
||||||
|
: fallback.monitorPort;
|
||||||
return {
|
return {
|
||||||
...fallback,
|
...fallback,
|
||||||
...cfg,
|
...cfg,
|
||||||
|
monitor_port: monitorPort,
|
||||||
|
monitorPort,
|
||||||
enabled: typeof cfg.enabled === 'boolean'
|
enabled: typeof cfg.enabled === 'boolean'
|
||||||
? cfg.enabled
|
? cfg.enabled
|
||||||
: typeof entry.enabled === 'boolean'
|
: typeof entry.enabled === 'boolean'
|
||||||
|
|||||||
@@ -1 +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"}
|
{"version":3,"file":"live-config.js","sourceRoot":"","sources":["live-config.ts"],"names":[],"mappings":";;AAgBA,kDAmCC;AAnCD,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,cAAc,CAA6B,IAAI,EAAE,CAAC;IACzE,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,MAAM,WAAW,GACf,OAAO,GAAG,CAAC,YAAY,KAAK,QAAQ;YAClC,CAAC,CAAC,GAAG,CAAC,YAAY;YAClB,CAAC,CAAC,OAAO,GAAG,CAAC,WAAW,KAAK,QAAQ;gBACnC,CAAC,CAAC,GAAG,CAAC,WAAW;gBACjB,CAAC,CAAC,OAAO,QAAQ,CAAC,YAAY,KAAK,QAAQ;oBACzC,CAAC,CAAC,QAAQ,CAAC,YAAY;oBACvB,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC;QAE/B,OAAO;YACL,GAAG,QAAQ;YACX,GAAG,GAAG;YACN,YAAY,EAAE,WAAW;YACzB,WAAW;YACX,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"}
|
||||||
@@ -3,6 +3,8 @@ export interface HarborForgeMonitorConfig {
|
|||||||
backendUrl?: string;
|
backendUrl?: string;
|
||||||
identifier?: string;
|
identifier?: string;
|
||||||
apiKey?: string;
|
apiKey?: string;
|
||||||
|
monitor_port?: number;
|
||||||
|
monitorPort?: number;
|
||||||
reportIntervalSec?: number;
|
reportIntervalSec?: number;
|
||||||
httpFallbackIntervalSec?: number;
|
httpFallbackIntervalSec?: number;
|
||||||
logLevel?: 'debug' | 'info' | 'warn' | 'error';
|
logLevel?: 'debug' | 'info' | 'warn' | 'error';
|
||||||
@@ -19,13 +21,24 @@ export function getLivePluginConfig(
|
|||||||
const root = (api.config as Record<string, unknown>) || {};
|
const root = (api.config as Record<string, unknown>) || {};
|
||||||
const plugins = (root.plugins as Record<string, unknown>) || {};
|
const plugins = (root.plugins as Record<string, unknown>) || {};
|
||||||
const entries = (plugins.entries as Record<string, unknown>) || {};
|
const entries = (plugins.entries as Record<string, unknown>) || {};
|
||||||
const entry = (entries['harborforge-monitor'] as Record<string, unknown>) || {};
|
const entry = (entries['harbor-forge'] as Record<string, unknown>) || {};
|
||||||
const cfg = (entry.config as Record<string, unknown>) || {};
|
const cfg = (entry.config as Record<string, unknown>) || {};
|
||||||
|
|
||||||
if (Object.keys(cfg).length > 0 || Object.keys(entry).length > 0) {
|
if (Object.keys(cfg).length > 0 || Object.keys(entry).length > 0) {
|
||||||
|
const monitorPort =
|
||||||
|
typeof cfg.monitor_port === 'number'
|
||||||
|
? cfg.monitor_port
|
||||||
|
: typeof cfg.monitorPort === 'number'
|
||||||
|
? cfg.monitorPort
|
||||||
|
: typeof fallback.monitor_port === 'number'
|
||||||
|
? fallback.monitor_port
|
||||||
|
: fallback.monitorPort;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...fallback,
|
...fallback,
|
||||||
...cfg,
|
...cfg,
|
||||||
|
monitor_port: monitorPort,
|
||||||
|
monitorPort,
|
||||||
enabled:
|
enabled:
|
||||||
typeof cfg.enabled === 'boolean'
|
typeof cfg.enabled === 'boolean'
|
||||||
? cfg.enabled
|
? cfg.enabled
|
||||||
|
|||||||
55
plugin/core/monitor-bridge.d.ts
vendored
Normal file
55
plugin/core/monitor-bridge.d.ts
vendored
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
/**
|
||||||
|
* Monitor Bridge Client
|
||||||
|
*
|
||||||
|
* Queries the local HarborForge.Monitor bridge endpoint on MONITOR_PORT
|
||||||
|
* to enrich plugin telemetry with host/hardware data.
|
||||||
|
*
|
||||||
|
* If the bridge is unreachable, all methods return null gracefully —
|
||||||
|
* the plugin continues to function without Monitor data.
|
||||||
|
*/
|
||||||
|
export interface MonitorHealth {
|
||||||
|
status: string;
|
||||||
|
monitor_version: string;
|
||||||
|
identifier: string;
|
||||||
|
}
|
||||||
|
export interface MonitorTelemetryResponse {
|
||||||
|
status: string;
|
||||||
|
monitor_version: string;
|
||||||
|
identifier: string;
|
||||||
|
telemetry?: {
|
||||||
|
identifier: string;
|
||||||
|
plugin_version: string;
|
||||||
|
cpu_pct: number;
|
||||||
|
mem_pct: number;
|
||||||
|
disk_pct: number;
|
||||||
|
swap_pct: number;
|
||||||
|
load_avg: number[];
|
||||||
|
uptime_seconds: number;
|
||||||
|
nginx_installed: boolean;
|
||||||
|
nginx_sites: string[];
|
||||||
|
};
|
||||||
|
last_updated?: string;
|
||||||
|
}
|
||||||
|
export declare class MonitorBridgeClient {
|
||||||
|
private baseUrl;
|
||||||
|
private timeoutMs;
|
||||||
|
constructor(port: number, timeoutMs?: number);
|
||||||
|
health(): Promise<MonitorHealth | null>;
|
||||||
|
telemetry(): Promise<MonitorTelemetryResponse | null>;
|
||||||
|
/**
|
||||||
|
* POST OpenClaw metadata to the Monitor bridge so it can enrich
|
||||||
|
* its heartbeat uploads with OpenClaw version, plugin version,
|
||||||
|
* and agent information.
|
||||||
|
*/
|
||||||
|
pushOpenClawMeta(meta: OpenClawMeta): Promise<boolean>;
|
||||||
|
private fetchJson;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* OpenClaw metadata payload sent to the Monitor bridge.
|
||||||
|
*/
|
||||||
|
export interface OpenClawMeta {
|
||||||
|
version: string;
|
||||||
|
plugin_version: string;
|
||||||
|
agents?: any[];
|
||||||
|
}
|
||||||
|
//# sourceMappingURL=monitor-bridge.d.ts.map
|
||||||
1
plugin/core/monitor-bridge.d.ts.map
Normal file
1
plugin/core/monitor-bridge.d.ts.map
Normal file
@@ -0,0 +1 @@
|
|||||||
|
{"version":3,"file":"monitor-bridge.d.ts","sourceRoot":"","sources":["monitor-bridge.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,MAAM,WAAW,aAAa;IAC5B,MAAM,EAAE,MAAM,CAAC;IACf,eAAe,EAAE,MAAM,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,wBAAwB;IACvC,MAAM,EAAE,MAAM,CAAC;IACf,eAAe,EAAE,MAAM,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE;QACV,UAAU,EAAE,MAAM,CAAC;QACnB,cAAc,EAAE,MAAM,CAAC;QACvB,OAAO,EAAE,MAAM,CAAC;QAChB,OAAO,EAAE,MAAM,CAAC;QAChB,QAAQ,EAAE,MAAM,CAAC;QACjB,QAAQ,EAAE,MAAM,CAAC;QACjB,QAAQ,EAAE,MAAM,EAAE,CAAC;QACnB,cAAc,EAAE,MAAM,CAAC;QACvB,eAAe,EAAE,OAAO,CAAC;QACzB,WAAW,EAAE,MAAM,EAAE,CAAC;KACvB,CAAC;IACF,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,SAAS,CAAS;gBAEd,IAAI,EAAE,MAAM,EAAE,SAAS,SAAO;IAKpC,MAAM,IAAI,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC;IAIvC,SAAS,IAAI,OAAO,CAAC,wBAAwB,GAAG,IAAI,CAAC;IAI3D;;;;OAIG;IACG,gBAAgB,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,OAAO,CAAC;YAmB9C,SAAS;CAgBxB;AAED;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B,OAAO,EAAE,MAAM,CAAC;IAChB,cAAc,EAAE,MAAM,CAAC;IACvB,MAAM,CAAC,EAAE,GAAG,EAAE,CAAC;CAChB"}
|
||||||
66
plugin/core/monitor-bridge.js
Normal file
66
plugin/core/monitor-bridge.js
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
"use strict";
|
||||||
|
/**
|
||||||
|
* Monitor Bridge Client
|
||||||
|
*
|
||||||
|
* Queries the local HarborForge.Monitor bridge endpoint on MONITOR_PORT
|
||||||
|
* to enrich plugin telemetry with host/hardware data.
|
||||||
|
*
|
||||||
|
* If the bridge is unreachable, all methods return null gracefully —
|
||||||
|
* the plugin continues to function without Monitor data.
|
||||||
|
*/
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.MonitorBridgeClient = void 0;
|
||||||
|
class MonitorBridgeClient {
|
||||||
|
baseUrl;
|
||||||
|
timeoutMs;
|
||||||
|
constructor(port, timeoutMs = 3000) {
|
||||||
|
this.baseUrl = `http://127.0.0.1:${port}`;
|
||||||
|
this.timeoutMs = timeoutMs;
|
||||||
|
}
|
||||||
|
async health() {
|
||||||
|
return this.fetchJson('/health');
|
||||||
|
}
|
||||||
|
async telemetry() {
|
||||||
|
return this.fetchJson('/telemetry');
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* POST OpenClaw metadata to the Monitor bridge so it can enrich
|
||||||
|
* its heartbeat uploads with OpenClaw version, plugin version,
|
||||||
|
* and agent information.
|
||||||
|
*/
|
||||||
|
async pushOpenClawMeta(meta) {
|
||||||
|
try {
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
|
||||||
|
const response = await fetch(`${this.baseUrl}/openclaw`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(meta),
|
||||||
|
signal: controller.signal,
|
||||||
|
});
|
||||||
|
clearTimeout(timeout);
|
||||||
|
return response.ok;
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async fetchJson(path) {
|
||||||
|
try {
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
|
||||||
|
const response = await fetch(`${this.baseUrl}${path}`, {
|
||||||
|
signal: controller.signal,
|
||||||
|
});
|
||||||
|
clearTimeout(timeout);
|
||||||
|
if (!response.ok)
|
||||||
|
return null;
|
||||||
|
return (await response.json());
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
exports.MonitorBridgeClient = MonitorBridgeClient;
|
||||||
|
//# sourceMappingURL=monitor-bridge.js.map
|
||||||
1
plugin/core/monitor-bridge.js.map
Normal file
1
plugin/core/monitor-bridge.js.map
Normal file
@@ -0,0 +1 @@
|
|||||||
|
{"version":3,"file":"monitor-bridge.js","sourceRoot":"","sources":["monitor-bridge.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;;AA2BH,MAAa,mBAAmB;IACtB,OAAO,CAAS;IAChB,SAAS,CAAS;IAE1B,YAAY,IAAY,EAAE,SAAS,GAAG,IAAI;QACxC,IAAI,CAAC,OAAO,GAAG,oBAAoB,IAAI,EAAE,CAAC;QAC1C,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC7B,CAAC;IAED,KAAK,CAAC,MAAM;QACV,OAAO,IAAI,CAAC,SAAS,CAAgB,SAAS,CAAC,CAAC;IAClD,CAAC;IAED,KAAK,CAAC,SAAS;QACb,OAAO,IAAI,CAAC,SAAS,CAA2B,YAAY,CAAC,CAAC;IAChE,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,gBAAgB,CAAC,IAAkB;QACvC,IAAI,CAAC;YACH,MAAM,UAAU,GAAG,IAAI,eAAe,EAAE,CAAC;YACzC,MAAM,OAAO,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,UAAU,CAAC,KAAK,EAAE,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;YAErE,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,IAAI,CAAC,OAAO,WAAW,EAAE;gBACvD,MAAM,EAAE,MAAM;gBACd,OAAO,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE;gBAC/C,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC;gBAC1B,MAAM,EAAE,UAAU,CAAC,MAAM;aAC1B,CAAC,CAAC;YACH,YAAY,CAAC,OAAO,CAAC,CAAC;YAEtB,OAAO,QAAQ,CAAC,EAAE,CAAC;QACrB,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;IAEO,KAAK,CAAC,SAAS,CAAI,IAAY;QACrC,IAAI,CAAC;YACH,MAAM,UAAU,GAAG,IAAI,eAAe,EAAE,CAAC;YACzC,MAAM,OAAO,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,UAAU,CAAC,KAAK,EAAE,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;YAErE,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,IAAI,CAAC,OAAO,GAAG,IAAI,EAAE,EAAE;gBACrD,MAAM,EAAE,UAAU,CAAC,MAAM;aAC1B,CAAC,CAAC;YACH,YAAY,CAAC,OAAO,CAAC,CAAC;YAEtB,IAAI,CAAC,QAAQ,CAAC,EAAE;gBAAE,OAAO,IAAI,CAAC;YAC9B,OAAO,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAM,CAAC;QACtC,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;CACF;AAzDD,kDAyDC"}
|
||||||
102
plugin/core/monitor-bridge.ts
Normal file
102
plugin/core/monitor-bridge.ts
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
/**
|
||||||
|
* Monitor Bridge Client
|
||||||
|
*
|
||||||
|
* Queries the local HarborForge.Monitor bridge endpoint on MONITOR_PORT
|
||||||
|
* to enrich plugin telemetry with host/hardware data.
|
||||||
|
*
|
||||||
|
* If the bridge is unreachable, all methods return null gracefully —
|
||||||
|
* the plugin continues to function without Monitor data.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export interface MonitorHealth {
|
||||||
|
status: string;
|
||||||
|
monitor_version: string;
|
||||||
|
identifier: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MonitorTelemetryResponse {
|
||||||
|
status: string;
|
||||||
|
monitor_version: string;
|
||||||
|
identifier: string;
|
||||||
|
telemetry?: {
|
||||||
|
identifier: string;
|
||||||
|
plugin_version: string;
|
||||||
|
cpu_pct: number;
|
||||||
|
mem_pct: number;
|
||||||
|
disk_pct: number;
|
||||||
|
swap_pct: number;
|
||||||
|
load_avg: number[];
|
||||||
|
uptime_seconds: number;
|
||||||
|
nginx_installed: boolean;
|
||||||
|
nginx_sites: string[];
|
||||||
|
};
|
||||||
|
last_updated?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class MonitorBridgeClient {
|
||||||
|
private baseUrl: string;
|
||||||
|
private timeoutMs: number;
|
||||||
|
|
||||||
|
constructor(port: number, timeoutMs = 3000) {
|
||||||
|
this.baseUrl = `http://127.0.0.1:${port}`;
|
||||||
|
this.timeoutMs = timeoutMs;
|
||||||
|
}
|
||||||
|
|
||||||
|
async health(): Promise<MonitorHealth | null> {
|
||||||
|
return this.fetchJson<MonitorHealth>('/health');
|
||||||
|
}
|
||||||
|
|
||||||
|
async telemetry(): Promise<MonitorTelemetryResponse | null> {
|
||||||
|
return this.fetchJson<MonitorTelemetryResponse>('/telemetry');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST OpenClaw metadata to the Monitor bridge so it can enrich
|
||||||
|
* its heartbeat uploads with OpenClaw version, plugin version,
|
||||||
|
* and agent information.
|
||||||
|
*/
|
||||||
|
async pushOpenClawMeta(meta: OpenClawMeta): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
|
||||||
|
|
||||||
|
const response = await fetch(`${this.baseUrl}/openclaw`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(meta),
|
||||||
|
signal: controller.signal,
|
||||||
|
});
|
||||||
|
clearTimeout(timeout);
|
||||||
|
|
||||||
|
return response.ok;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async fetchJson<T>(path: string): Promise<T | null> {
|
||||||
|
try {
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
|
||||||
|
|
||||||
|
const response = await fetch(`${this.baseUrl}${path}`, {
|
||||||
|
signal: controller.signal,
|
||||||
|
});
|
||||||
|
clearTimeout(timeout);
|
||||||
|
|
||||||
|
if (!response.ok) return null;
|
||||||
|
return (await response.json()) as T;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* OpenClaw metadata payload sent to the Monitor bridge.
|
||||||
|
*/
|
||||||
|
export interface OpenClawMeta {
|
||||||
|
version: string;
|
||||||
|
plugin_version: string;
|
||||||
|
agents?: any[];
|
||||||
|
}
|
||||||
271
plugin/index.ts
271
plugin/index.ts
@@ -1,12 +1,16 @@
|
|||||||
/**
|
/**
|
||||||
* HarborForge Monitor Plugin for OpenClaw
|
* HarborForge Plugin for OpenClaw
|
||||||
*
|
*
|
||||||
* Manages sidecar lifecycle and provides monitor-related tools.
|
* Provides monitor-related tools and exposes OpenClaw metadata
|
||||||
|
* for the HarborForge Monitor bridge (via monitor_port).
|
||||||
|
*
|
||||||
|
* Sidecar architecture has been removed. Telemetry data is now
|
||||||
|
* served directly by the plugin when Monitor queries via the
|
||||||
|
* local monitor_port communication path.
|
||||||
*/
|
*/
|
||||||
import { spawn } from 'child_process';
|
import { hostname, freemem, totalmem, uptime, loadavg, platform } from 'os';
|
||||||
import { join } from 'path';
|
|
||||||
import { existsSync } from 'fs';
|
|
||||||
import { getLivePluginConfig, type HarborForgeMonitorConfig } from './core/live-config';
|
import { getLivePluginConfig, type HarborForgeMonitorConfig } from './core/live-config';
|
||||||
|
import { MonitorBridgeClient, type OpenClawMeta } from './core/monitor-bridge';
|
||||||
|
|
||||||
interface PluginAPI {
|
interface PluginAPI {
|
||||||
logger: {
|
logger: {
|
||||||
@@ -23,14 +27,14 @@ interface PluginAPI {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
id: 'harborforge-monitor',
|
id: 'harbor-forge',
|
||||||
name: 'HarborForge Monitor',
|
name: 'HarborForge',
|
||||||
register(api: PluginAPI) {
|
register(api: PluginAPI) {
|
||||||
const logger = api.logger || {
|
const logger = api.logger || {
|
||||||
info: (...args: any[]) => console.log('[HF-Monitor]', ...args),
|
info: (...args: any[]) => console.log('[HarborForge]', ...args),
|
||||||
error: (...args: any[]) => console.error('[HF-Monitor]', ...args),
|
error: (...args: any[]) => console.error('[HarborForge]', ...args),
|
||||||
debug: (...args: any[]) => console.debug('[HF-Monitor]', ...args),
|
debug: (...args: any[]) => console.debug('[HarborForge]', ...args),
|
||||||
warn: (...args: any[]) => console.warn('[HF-Monitor]', ...args),
|
warn: (...args: any[]) => console.warn('[HarborForge]', ...args),
|
||||||
};
|
};
|
||||||
|
|
||||||
const baseConfig: HarborForgeMonitorConfig = {
|
const baseConfig: HarborForgeMonitorConfig = {
|
||||||
@@ -43,142 +47,179 @@ export default {
|
|||||||
...(api.pluginConfig || {}),
|
...(api.pluginConfig || {}),
|
||||||
};
|
};
|
||||||
|
|
||||||
const serverPath = join(__dirname, 'server', 'telemetry.mjs');
|
|
||||||
let sidecar: ReturnType<typeof spawn> | null = null;
|
|
||||||
|
|
||||||
function resolveConfig() {
|
function resolveConfig() {
|
||||||
return getLivePluginConfig(api, baseConfig);
|
return getLivePluginConfig(api, baseConfig);
|
||||||
}
|
}
|
||||||
|
|
||||||
function startSidecar() {
|
/**
|
||||||
const live = resolveConfig();
|
* Get the monitor bridge client if monitor_port is configured.
|
||||||
const enabled = live.enabled !== false;
|
* Legacy alias monitorPort is still accepted.
|
||||||
|
*/
|
||||||
logger.info('HarborForge Monitor plugin config resolved', {
|
function getBridgeClient(): MonitorBridgeClient | null {
|
||||||
enabled,
|
const live = resolveConfig() as any;
|
||||||
hasApiKey: Boolean(live.apiKey),
|
const port = live.monitor_port ?? live.monitorPort;
|
||||||
backendUrl: live.backendUrl ?? null,
|
if (!port || port <= 0) return null;
|
||||||
identifier: live.identifier ?? null,
|
return new MonitorBridgeClient(port);
|
||||||
});
|
|
||||||
|
|
||||||
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) {
|
* Collect current system telemetry snapshot.
|
||||||
logger.debug('Telemetry server not running');
|
* This data is exposed to the Monitor bridge when it queries the plugin.
|
||||||
return;
|
*/
|
||||||
|
function collectTelemetry() {
|
||||||
|
const live = resolveConfig();
|
||||||
|
const load = loadavg();
|
||||||
|
return {
|
||||||
|
identifier: live.identifier || hostname(),
|
||||||
|
platform: platform(),
|
||||||
|
hostname: hostname(),
|
||||||
|
uptime: uptime(),
|
||||||
|
memory: {
|
||||||
|
total: totalmem(),
|
||||||
|
free: freemem(),
|
||||||
|
used: totalmem() - freemem(),
|
||||||
|
usagePercent: ((totalmem() - freemem()) / totalmem()) * 100,
|
||||||
|
},
|
||||||
|
load: {
|
||||||
|
avg1: load[0],
|
||||||
|
avg5: load[1],
|
||||||
|
avg15: load[2],
|
||||||
|
},
|
||||||
|
openclaw: {
|
||||||
|
version: api.version || 'unknown',
|
||||||
|
pluginVersion: '0.2.0',
|
||||||
|
},
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Periodic metadata push interval handle
|
||||||
|
let metaPushInterval: ReturnType<typeof setInterval> | null = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Push OpenClaw metadata to the Monitor bridge.
|
||||||
|
* This enriches Monitor heartbeats with OpenClaw version/plugin/agent info.
|
||||||
|
* Failures are non-fatal — Monitor continues to work without this data.
|
||||||
|
*/
|
||||||
|
async function pushMetaToMonitor() {
|
||||||
|
const bridgeClient = getBridgeClient();
|
||||||
|
if (!bridgeClient) return;
|
||||||
|
|
||||||
|
const meta: OpenClawMeta = {
|
||||||
|
version: api.version || 'unknown',
|
||||||
|
plugin_version: '0.2.0',
|
||||||
|
agents: [], // TODO: populate from api agent list when available
|
||||||
|
};
|
||||||
|
|
||||||
|
const ok = await bridgeClient.pushOpenClawMeta(meta);
|
||||||
|
if (ok) {
|
||||||
|
logger.debug('pushed OpenClaw metadata to Monitor bridge');
|
||||||
|
} else {
|
||||||
|
logger.debug('Monitor bridge unreachable for metadata push (non-fatal)');
|
||||||
}
|
}
|
||||||
|
|
||||||
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', () => {
|
api.on('gateway_start', () => {
|
||||||
logger.info('gateway_start received, starting telemetry server...');
|
logger.info('HarborForge plugin active');
|
||||||
startSidecar();
|
|
||||||
|
// Push metadata to Monitor bridge on startup and periodically.
|
||||||
|
// Interval aligns with typical Monitor heartbeat cycle (30s).
|
||||||
|
// If Monitor bridge is unreachable, pushes silently fail.
|
||||||
|
const live = resolveConfig();
|
||||||
|
const intervalSec = live.reportIntervalSec || 30;
|
||||||
|
|
||||||
|
// Initial push (delayed 2s to let Monitor bridge start)
|
||||||
|
setTimeout(() => pushMetaToMonitor(), 2000);
|
||||||
|
|
||||||
|
metaPushInterval = setInterval(
|
||||||
|
() => pushMetaToMonitor(),
|
||||||
|
intervalSec * 1000,
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
api.on('gateway_stop', () => {
|
api.on('gateway_stop', () => {
|
||||||
logger.info('gateway_stop received, stopping telemetry server...');
|
logger.info('HarborForge plugin stopping');
|
||||||
stopSidecar();
|
if (metaPushInterval) {
|
||||||
|
clearInterval(metaPushInterval);
|
||||||
|
metaPushInterval = null;
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
process.on('SIGTERM', stopSidecar);
|
// Tool: plugin status
|
||||||
process.on('SIGINT', stopSidecar);
|
|
||||||
|
|
||||||
api.registerTool(() => ({
|
api.registerTool(() => ({
|
||||||
name: 'harborforge_monitor_status',
|
name: 'harborforge_status',
|
||||||
description: 'Get HarborForge Monitor plugin status',
|
description: 'Get HarborForge plugin status and current telemetry snapshot',
|
||||||
parameters: {
|
parameters: {
|
||||||
type: 'object',
|
type: 'object',
|
||||||
properties: {},
|
properties: {},
|
||||||
},
|
},
|
||||||
async execute() {
|
async execute() {
|
||||||
const live = resolveConfig();
|
const live = resolveConfig();
|
||||||
|
const bridgeClient = getBridgeClient();
|
||||||
|
let monitorBridge = null;
|
||||||
|
|
||||||
|
if (bridgeClient) {
|
||||||
|
const health = await bridgeClient.health();
|
||||||
|
monitorBridge = health
|
||||||
|
? { connected: true, ...health }
|
||||||
|
: { connected: false, error: 'Monitor bridge unreachable' };
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
enabled: live.enabled !== false,
|
enabled: live.enabled !== false,
|
||||||
sidecarRunning: sidecar !== null && sidecar.exitCode === null,
|
|
||||||
pid: sidecar?.pid || null,
|
|
||||||
config: {
|
config: {
|
||||||
backendUrl: live.backendUrl,
|
backendUrl: live.backendUrl,
|
||||||
identifier: live.identifier || 'auto-detected',
|
identifier: live.identifier || hostname(),
|
||||||
|
monitorPort: (live as any).monitor_port ?? (live as any).monitorPort ?? null,
|
||||||
reportIntervalSec: live.reportIntervalSec,
|
reportIntervalSec: live.reportIntervalSec,
|
||||||
hasApiKey: Boolean(live.apiKey),
|
hasApiKey: Boolean(live.apiKey),
|
||||||
},
|
},
|
||||||
|
monitorBridge,
|
||||||
|
telemetry: collectTelemetry(),
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
logger.info('HarborForge Monitor plugin registered');
|
// Tool: telemetry snapshot (for Monitor bridge queries)
|
||||||
|
api.registerTool(() => ({
|
||||||
|
name: 'harborforge_telemetry',
|
||||||
|
description: 'Get current system telemetry data for HarborForge Monitor',
|
||||||
|
parameters: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {},
|
||||||
|
},
|
||||||
|
async execute() {
|
||||||
|
return collectTelemetry();
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Tool: query Monitor bridge for host hardware telemetry
|
||||||
|
api.registerTool(() => ({
|
||||||
|
name: 'harborforge_monitor_telemetry',
|
||||||
|
description: 'Query HarborForge Monitor bridge for host hardware telemetry (CPU, memory, disk, etc.)',
|
||||||
|
parameters: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {},
|
||||||
|
},
|
||||||
|
async execute() {
|
||||||
|
const bridgeClient = getBridgeClient();
|
||||||
|
if (!bridgeClient) {
|
||||||
|
return {
|
||||||
|
error: 'Monitor bridge not configured (monitor_port not set or 0)',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await bridgeClient.telemetry();
|
||||||
|
if (!data) {
|
||||||
|
return {
|
||||||
|
error: 'Monitor bridge unreachable',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
logger.info('HarborForge plugin registered (id: harbor-forge)');
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
{
|
{
|
||||||
"id": "harborforge-monitor",
|
"id": "harbor-forge",
|
||||||
"name": "HarborForge Monitor",
|
"name": "HarborForge",
|
||||||
"version": "0.1.0",
|
"version": "0.2.0",
|
||||||
"description": "Server monitoring plugin for HarborForge - streams telemetry to Monitor",
|
"description": "HarborForge plugin for OpenClaw - project management, monitoring, and CLI integration",
|
||||||
"entry": "./index.js",
|
"entry": "./index.js",
|
||||||
"configSchema": {
|
"configSchema": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
@@ -11,7 +11,7 @@
|
|||||||
"enabled": {
|
"enabled": {
|
||||||
"type": "boolean",
|
"type": "boolean",
|
||||||
"default": true,
|
"default": true,
|
||||||
"description": "Enable the monitor plugin"
|
"description": "Enable the HarborForge plugin"
|
||||||
},
|
},
|
||||||
"backendUrl": {
|
"backendUrl": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
@@ -26,6 +26,10 @@
|
|||||||
"type": "string",
|
"type": "string",
|
||||||
"description": "API Key from HarborForge Monitor admin panel (optional but required for authentication)"
|
"description": "API Key from HarborForge Monitor admin panel (optional but required for authentication)"
|
||||||
},
|
},
|
||||||
|
"monitor_port": {
|
||||||
|
"type": "number",
|
||||||
|
"description": "Local port for communication between HarborForge Monitor and this plugin"
|
||||||
|
},
|
||||||
"reportIntervalSec": {
|
"reportIntervalSec": {
|
||||||
"type": "number",
|
"type": "number",
|
||||||
"default": 30,
|
"default": 30,
|
||||||
|
|||||||
8
plugin/package-lock.json
generated
8
plugin/package-lock.json
generated
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "harborforge-monitor-plugin",
|
"name": "harbor-forge-plugin",
|
||||||
"version": "0.1.0",
|
"version": "0.2.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "harborforge-monitor-plugin",
|
"name": "harbor-forge-plugin",
|
||||||
"version": "0.1.0",
|
"version": "0.2.0",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/node": "^20.0.0",
|
"@types/node": "^20.0.0",
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "harborforge-monitor-plugin",
|
"name": "harbor-forge-plugin",
|
||||||
"version": "0.1.0",
|
"version": "0.2.0",
|
||||||
"description": "OpenClaw plugin for HarborForge Monitor",
|
"description": "OpenClaw plugin for HarborForge monitor bridge and CLI integration",
|
||||||
"main": "index.js",
|
"main": "index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsc",
|
"build": "tsc",
|
||||||
|
|||||||
@@ -1,7 +1,13 @@
|
|||||||
#!/usr/bin/env node
|
#!/usr/bin/env node
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* HarborForge Monitor Plugin Installer v0.1.0
|
* HarborForge Plugin Installer v0.2.0
|
||||||
|
*
|
||||||
|
* Changes from v0.1.0:
|
||||||
|
* - Plugin renamed from harborforge-monitor to harbor-forge
|
||||||
|
* - Sidecar server removed (telemetry served directly by plugin)
|
||||||
|
* - Added --install-cli flag for building and installing the hf CLI
|
||||||
|
* - skills/hf/ only installed when --install-cli is present
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { execSync } from 'child_process';
|
import { execSync } from 'child_process';
|
||||||
@@ -11,8 +17,7 @@ import {
|
|||||||
copyFileSync,
|
copyFileSync,
|
||||||
readdirSync,
|
readdirSync,
|
||||||
rmSync,
|
rmSync,
|
||||||
readFileSync,
|
chmodSync,
|
||||||
writeFileSync,
|
|
||||||
} from 'fs';
|
} from 'fs';
|
||||||
import { dirname, join, resolve } from 'path';
|
import { dirname, join, resolve } from 'path';
|
||||||
import { fileURLToPath } from 'url';
|
import { fileURLToPath } from 'url';
|
||||||
@@ -21,9 +26,9 @@ import { homedir, platform } from 'os';
|
|||||||
const __filename = fileURLToPath(import.meta.url);
|
const __filename = fileURLToPath(import.meta.url);
|
||||||
const __dirname = resolve(dirname(__filename), '..');
|
const __dirname = resolve(dirname(__filename), '..');
|
||||||
|
|
||||||
const PLUGIN_NAME = 'harborforge-monitor';
|
const PLUGIN_NAME = 'harbor-forge';
|
||||||
|
const OLD_PLUGIN_NAME = 'harborforge-monitor';
|
||||||
const PLUGIN_SRC_DIR = join(__dirname, 'plugin');
|
const PLUGIN_SRC_DIR = join(__dirname, 'plugin');
|
||||||
const SERVER_SRC_DIR = join(__dirname, 'server');
|
|
||||||
const SKILLS_SRC_DIR = join(__dirname, 'skills');
|
const SKILLS_SRC_DIR = join(__dirname, 'skills');
|
||||||
|
|
||||||
const args = process.argv.slice(2);
|
const args = process.argv.slice(2);
|
||||||
@@ -34,6 +39,7 @@ const options = {
|
|||||||
verbose: args.includes('--verbose') || args.includes('-v'),
|
verbose: args.includes('--verbose') || args.includes('-v'),
|
||||||
uninstall: args.includes('--uninstall'),
|
uninstall: args.includes('--uninstall'),
|
||||||
installOnly: args.includes('--install'),
|
installOnly: args.includes('--install'),
|
||||||
|
installCli: args.includes('--install-cli'),
|
||||||
};
|
};
|
||||||
|
|
||||||
const profileIdx = args.indexOf('--openclaw-profile-path');
|
const profileIdx = args.indexOf('--openclaw-profile-path');
|
||||||
@@ -83,19 +89,21 @@ function unsetOpenclawConfig(key) {
|
|||||||
try { exec(`openclaw config unset ${key}`, { silent: true }); } catch {}
|
try { exec(`openclaw config unset ${key}`, { silent: true }); } catch {}
|
||||||
}
|
}
|
||||||
|
|
||||||
function copyDir(src, dest) {
|
function copyDir(src, dest, { exclude = [] } = {}) {
|
||||||
mkdirSync(dest, { recursive: true });
|
mkdirSync(dest, { recursive: true });
|
||||||
for (const entry of readdirSync(src, { withFileTypes: true })) {
|
for (const entry of readdirSync(src, { withFileTypes: true })) {
|
||||||
const s = join(src, entry.name);
|
const s = join(src, entry.name);
|
||||||
const d = join(dest, entry.name);
|
const d = join(dest, entry.name);
|
||||||
if (entry.name === 'node_modules') continue;
|
if (entry.name === 'node_modules') continue;
|
||||||
entry.isDirectory() ? copyDir(s, d) : copyFileSync(s, d);
|
if (exclude.includes(entry.name)) continue;
|
||||||
|
entry.isDirectory() ? copyDir(s, d, { exclude }) : copyFileSync(s, d);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function detectEnvironment() {
|
function detectEnvironment() {
|
||||||
logStep(1, 5, 'Detecting environment...');
|
const totalSteps = options.installCli ? 6 : 5;
|
||||||
const env = { platform: platform(), nodeVersion: null };
|
logStep(1, totalSteps, 'Detecting environment...');
|
||||||
|
const env = { platform: platform(), nodeVersion: null, goVersion: null };
|
||||||
|
|
||||||
try {
|
try {
|
||||||
env.nodeVersion = exec('node --version', { silent: true }).trim();
|
env.nodeVersion = exec('node --version', { silent: true }).trim();
|
||||||
@@ -109,19 +117,34 @@ function detectEnvironment() {
|
|||||||
} catch {
|
} catch {
|
||||||
logWarn('openclaw CLI not in PATH');
|
logWarn('openclaw CLI not in PATH');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (options.installCli) {
|
||||||
|
try {
|
||||||
|
env.goVersion = exec('go version', { silent: true }).trim();
|
||||||
|
logOk(env.goVersion);
|
||||||
|
} catch {
|
||||||
|
logWarn('Go not found (needed for --install-cli)');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return env;
|
return env;
|
||||||
}
|
}
|
||||||
|
|
||||||
function checkDeps(env) {
|
function checkDeps(env) {
|
||||||
if (options.skipCheck) { logStep(2, 5, 'Skipping dep checks'); return; }
|
const totalSteps = options.installCli ? 6 : 5;
|
||||||
logStep(2, 5, 'Checking dependencies...');
|
if (options.skipCheck) { logStep(2, totalSteps, 'Skipping dep checks'); return; }
|
||||||
|
logStep(2, totalSteps, 'Checking dependencies...');
|
||||||
|
|
||||||
let fail = false;
|
let fail = false;
|
||||||
if (!env.nodeVersion || parseInt(env.nodeVersion.slice(1)) < 18) {
|
if (!env.nodeVersion || parseInt(env.nodeVersion.slice(1)) < 18) {
|
||||||
logErr('Node.js 18+ required');
|
logErr('Node.js 18+ required');
|
||||||
fail = true;
|
fail = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (options.installCli && !env.goVersion) {
|
||||||
|
logErr('Go is required for --install-cli');
|
||||||
|
fail = true;
|
||||||
|
}
|
||||||
|
|
||||||
if (fail) {
|
if (fail) {
|
||||||
log('\nInstall missing deps and retry.', 'red');
|
log('\nInstall missing deps and retry.', 'red');
|
||||||
@@ -132,7 +155,8 @@ function checkDeps(env) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function build() {
|
async function build() {
|
||||||
logStep(3, 5, 'Building plugin...');
|
const totalSteps = options.installCli ? 6 : 5;
|
||||||
|
logStep(3, totalSteps, 'Building plugin...');
|
||||||
|
|
||||||
log(' Building TypeScript plugin...', 'blue');
|
log(' Building TypeScript plugin...', 'blue');
|
||||||
exec('npm install', { cwd: PLUGIN_SRC_DIR, silent: !options.verbose });
|
exec('npm install', { cwd: PLUGIN_SRC_DIR, silent: !options.verbose });
|
||||||
@@ -141,11 +165,18 @@ async function build() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function clearInstallTargets(openclawPath) {
|
function clearInstallTargets(openclawPath) {
|
||||||
|
// Remove new plugin dir
|
||||||
const destDir = join(openclawPath, 'plugins', PLUGIN_NAME);
|
const destDir = join(openclawPath, 'plugins', PLUGIN_NAME);
|
||||||
if (existsSync(destDir)) {
|
if (existsSync(destDir)) {
|
||||||
rmSync(destDir, { recursive: true, force: true });
|
rmSync(destDir, { recursive: true, force: true });
|
||||||
logOk(`Removed ${destDir}`);
|
logOk(`Removed ${destDir}`);
|
||||||
}
|
}
|
||||||
|
// Remove old plugin dir if it exists
|
||||||
|
const oldDestDir = join(openclawPath, 'plugins', OLD_PLUGIN_NAME);
|
||||||
|
if (existsSync(oldDestDir)) {
|
||||||
|
rmSync(oldDestDir, { recursive: true, force: true });
|
||||||
|
logOk(`Removed old plugin dir ${oldDestDir}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function cleanupConfig(openclawPath) {
|
function cleanupConfig(openclawPath) {
|
||||||
@@ -153,20 +184,31 @@ function cleanupConfig(openclawPath) {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const allow = getOpenclawConfig('plugins.allow', []);
|
const allow = getOpenclawConfig('plugins.allow', []);
|
||||||
const idx = allow.indexOf(PLUGIN_NAME);
|
// Remove both old and new names
|
||||||
if (idx !== -1) {
|
for (const name of [PLUGIN_NAME, OLD_PLUGIN_NAME]) {
|
||||||
allow.splice(idx, 1);
|
const idx = allow.indexOf(name);
|
||||||
setOpenclawConfig('plugins.allow', allow);
|
if (idx !== -1) {
|
||||||
logOk('Removed from allow list');
|
allow.splice(idx, 1);
|
||||||
|
logOk(`Removed ${name} from allow list`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
setOpenclawConfig('plugins.allow', allow);
|
||||||
|
|
||||||
unsetOpenclawConfig(`plugins.entries.${PLUGIN_NAME}`);
|
unsetOpenclawConfig(`plugins.entries.${PLUGIN_NAME}`);
|
||||||
logOk('Removed plugin entry');
|
unsetOpenclawConfig(`plugins.entries.${OLD_PLUGIN_NAME}`);
|
||||||
|
logOk('Removed plugin entries');
|
||||||
|
|
||||||
const paths = getOpenclawConfig('plugins.load.paths', []);
|
const paths = getOpenclawConfig('plugins.load.paths', []);
|
||||||
const pidx = paths.indexOf(destDir);
|
const oldDestDir = join(openclawPath, 'plugins', OLD_PLUGIN_NAME);
|
||||||
if (pidx !== -1) {
|
let changed = false;
|
||||||
paths.splice(pidx, 1);
|
for (const p of [destDir, oldDestDir]) {
|
||||||
|
const pidx = paths.indexOf(p);
|
||||||
|
if (pidx !== -1) {
|
||||||
|
paths.splice(pidx, 1);
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (changed) {
|
||||||
setOpenclawConfig('plugins.load.paths', paths);
|
setOpenclawConfig('plugins.load.paths', paths);
|
||||||
logOk('Removed from load paths');
|
logOk('Removed from load paths');
|
||||||
}
|
}
|
||||||
@@ -176,8 +218,9 @@ function cleanupConfig(openclawPath) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function install() {
|
async function install() {
|
||||||
if (options.buildOnly) { logStep(4, 5, 'Skipping install (--build-only)'); return null; }
|
const totalSteps = options.installCli ? 6 : 5;
|
||||||
logStep(4, 5, 'Installing...');
|
if (options.buildOnly) { logStep(4, totalSteps, 'Skipping install (--build-only)'); return null; }
|
||||||
|
logStep(4, totalSteps, 'Installing...');
|
||||||
|
|
||||||
const openclawPath = resolveOpenclawPath();
|
const openclawPath = resolveOpenclawPath();
|
||||||
const pluginsDir = join(openclawPath, 'plugins');
|
const pluginsDir = join(openclawPath, 'plugins');
|
||||||
@@ -186,29 +229,34 @@ async function install() {
|
|||||||
log(` OpenClaw path: ${openclawPath}`, 'blue');
|
log(` OpenClaw path: ${openclawPath}`, 'blue');
|
||||||
|
|
||||||
if (existsSync(destDir)) {
|
if (existsSync(destDir)) {
|
||||||
logWarn('Existing install detected, uninstalling before install...');
|
logWarn('Existing install detected, cleaning up...');
|
||||||
clearInstallTargets(openclawPath);
|
clearInstallTargets(openclawPath);
|
||||||
cleanupConfig(openclawPath);
|
cleanupConfig(openclawPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (existsSync(destDir)) rmSync(destDir, { recursive: true, force: true });
|
// Clean up old plugin name if present
|
||||||
|
const oldDestDir = join(pluginsDir, OLD_PLUGIN_NAME);
|
||||||
|
if (existsSync(oldDestDir)) {
|
||||||
|
logWarn('Old plugin (harborforge-monitor) detected, removing...');
|
||||||
|
rmSync(oldDestDir, { recursive: true, force: true });
|
||||||
|
cleanupConfig(openclawPath);
|
||||||
|
}
|
||||||
|
|
||||||
// Copy compiled plugin
|
// Copy compiled plugin (no server directory — sidecar removed)
|
||||||
mkdirSync(destDir, { recursive: true });
|
mkdirSync(destDir, { recursive: true });
|
||||||
copyDir(PLUGIN_SRC_DIR, destDir);
|
copyDir(PLUGIN_SRC_DIR, destDir);
|
||||||
|
logOk(`Plugin files → ${destDir}`);
|
||||||
|
|
||||||
// Copy telemetry server
|
// Copy skills (exclude hf/ unless --install-cli)
|
||||||
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)) {
|
if (existsSync(SKILLS_SRC_DIR)) {
|
||||||
const skillsDestDir = join(openclawPath, 'skills');
|
const skillsDestDir = join(openclawPath, 'skills');
|
||||||
mkdirSync(skillsDestDir, { recursive: true });
|
const excludeSkills = options.installCli ? [] : ['hf'];
|
||||||
copyDir(SKILLS_SRC_DIR, skillsDestDir);
|
copyDir(SKILLS_SRC_DIR, skillsDestDir, { exclude: excludeSkills });
|
||||||
logOk(`Skills → ${skillsDestDir}`);
|
if (options.installCli) {
|
||||||
|
logOk(`Skills (including hf) → ${skillsDestDir}`);
|
||||||
|
} else {
|
||||||
|
logOk(`Skills (hf skipped, use --install-cli) → ${skillsDestDir}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Install runtime deps
|
// Install runtime deps
|
||||||
@@ -218,9 +266,51 @@ async function install() {
|
|||||||
return { destDir };
|
return { destDir };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function installCli() {
|
||||||
|
if (!options.installCli) return;
|
||||||
|
const totalSteps = 6;
|
||||||
|
logStep(5, totalSteps, 'Building and installing hf CLI...');
|
||||||
|
|
||||||
|
const openclawPath = resolveOpenclawPath();
|
||||||
|
const binDir = join(openclawPath, 'bin');
|
||||||
|
mkdirSync(binDir, { recursive: true });
|
||||||
|
|
||||||
|
// Find CLI source — look for HarborForge.Cli relative to project root
|
||||||
|
const projectRoot = resolve(__dirname, '..');
|
||||||
|
const cliDir = join(projectRoot, 'HarborForge.Cli');
|
||||||
|
|
||||||
|
if (!existsSync(cliDir)) {
|
||||||
|
// Try parent directory (monorepo layout)
|
||||||
|
const monoCliDir = resolve(projectRoot, '..', 'HarborForge.Cli');
|
||||||
|
if (!existsSync(monoCliDir)) {
|
||||||
|
logErr(`Cannot find HarborForge.Cli at ${cliDir} or ${monoCliDir}`);
|
||||||
|
logWarn('Skipping CLI installation');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const effectiveCliDir = existsSync(cliDir)
|
||||||
|
? cliDir
|
||||||
|
: resolve(projectRoot, '..', 'HarborForge.Cli');
|
||||||
|
|
||||||
|
log(` Building hf from ${effectiveCliDir}...`, 'blue');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const hfBinary = join(binDir, 'hf');
|
||||||
|
exec(`go build -o ${hfBinary} ./cmd/hf`, { cwd: effectiveCliDir, silent: !options.verbose });
|
||||||
|
chmodSync(hfBinary, 0o755);
|
||||||
|
logOk(`hf binary → ${hfBinary}`);
|
||||||
|
} catch (err) {
|
||||||
|
logErr(`Failed to build hf CLI: ${err.message}`);
|
||||||
|
logWarn('CLI installation failed, plugin still installed');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function configure() {
|
async function configure() {
|
||||||
if (options.buildOnly) { logStep(5, 5, 'Skipping config'); return; }
|
const totalSteps = options.installCli ? 6 : 5;
|
||||||
logStep(5, 5, 'Configuring OpenClaw...');
|
const step = options.installCli ? 6 : 5;
|
||||||
|
if (options.buildOnly) { logStep(step, totalSteps, 'Skipping config'); return; }
|
||||||
|
logStep(step, totalSteps, 'Configuring OpenClaw...');
|
||||||
|
|
||||||
const openclawPath = resolveOpenclawPath();
|
const openclawPath = resolveOpenclawPath();
|
||||||
const destDir = join(openclawPath, 'plugins', PLUGIN_NAME);
|
const destDir = join(openclawPath, 'plugins', PLUGIN_NAME);
|
||||||
@@ -240,8 +330,7 @@ async function configure() {
|
|||||||
}
|
}
|
||||||
logOk(`plugins.allow includes ${PLUGIN_NAME}`);
|
logOk(`plugins.allow includes ${PLUGIN_NAME}`);
|
||||||
|
|
||||||
// Note: apiKey must be configured manually by user
|
logOk('Plugin configured (remember to set apiKey in plugins.entries.harbor-forge.config)');
|
||||||
logOk('Plugin configured (remember to set apiKey in plugins.entries.harborforge-monitor.config)');
|
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logWarn(`Config failed: ${err.message}`);
|
logWarn(`Config failed: ${err.message}`);
|
||||||
@@ -249,11 +338,12 @@ async function configure() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function summary() {
|
function summary() {
|
||||||
logStep(5, 5, 'Done!');
|
const totalSteps = options.installCli ? 6 : 5;
|
||||||
|
logStep(totalSteps, totalSteps, 'Done!');
|
||||||
console.log('');
|
console.log('');
|
||||||
log('╔══════════════════════════════════════════════╗', 'cyan');
|
log('╔════════════════════════════════════════════╗', 'cyan');
|
||||||
log('║ HarborForge Monitor v0.1.0 Install Complete ║', 'cyan');
|
log('║ HarborForge v0.2.0 Install Complete ║', 'cyan');
|
||||||
log('╚══════════════════════════════════════════════╝', 'cyan');
|
log('╚════════════════════════════════════════════╝', 'cyan');
|
||||||
|
|
||||||
if (options.buildOnly) {
|
if (options.buildOnly) {
|
||||||
log('\nBuild-only — plugin not installed.', 'yellow');
|
log('\nBuild-only — plugin not installed.', 'yellow');
|
||||||
@@ -263,11 +353,12 @@ function summary() {
|
|||||||
console.log('');
|
console.log('');
|
||||||
log('Next steps:', 'blue');
|
log('Next steps:', 'blue');
|
||||||
log(' 1. Register server in HarborForge Monitor to get apiKey', 'cyan');
|
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(' 2. Edit ~/.openclaw/openclaw.json under plugins.entries.harbor-forge.config:', 'cyan');
|
||||||
|
log(' (prefer monitor_port; legacy monitorPort is still accepted)', 'cyan');
|
||||||
log(' {', 'cyan');
|
log(' {', 'cyan');
|
||||||
log(' "plugins": {', 'cyan');
|
log(' "plugins": {', 'cyan');
|
||||||
log(' "entries": {', 'cyan');
|
log(' "entries": {', 'cyan');
|
||||||
log(' "harborforge-monitor": {', 'cyan');
|
log(' "harbor-forge": {', 'cyan');
|
||||||
log(' "enabled": true,', 'cyan');
|
log(' "enabled": true,', 'cyan');
|
||||||
log(' "config": {', 'cyan');
|
log(' "config": {', 'cyan');
|
||||||
log(' "enabled": true,', 'cyan');
|
log(' "enabled": true,', 'cyan');
|
||||||
@@ -278,22 +369,36 @@ function summary() {
|
|||||||
log(' }', 'cyan');
|
log(' }', 'cyan');
|
||||||
log(' }', 'cyan');
|
log(' }', 'cyan');
|
||||||
log(' 3. openclaw gateway restart', 'cyan');
|
log(' 3. openclaw gateway restart', 'cyan');
|
||||||
|
|
||||||
|
if (options.installCli) {
|
||||||
|
console.log('');
|
||||||
|
log(' hf CLI installed to ~/.openclaw/bin/hf', 'green');
|
||||||
|
log(' Ensure ~/.openclaw/bin is in your PATH', 'cyan');
|
||||||
|
}
|
||||||
console.log('');
|
console.log('');
|
||||||
}
|
}
|
||||||
|
|
||||||
async function uninstall() {
|
async function uninstall() {
|
||||||
log('Uninstalling HarborForge Monitor...', 'cyan');
|
log('Uninstalling HarborForge...', 'cyan');
|
||||||
const openclawPath = resolveOpenclawPath();
|
const openclawPath = resolveOpenclawPath();
|
||||||
clearInstallTargets(openclawPath);
|
clearInstallTargets(openclawPath);
|
||||||
cleanupConfig(openclawPath);
|
cleanupConfig(openclawPath);
|
||||||
|
|
||||||
|
// Remove CLI binary if present
|
||||||
|
const hfBinary = join(openclawPath, 'bin', 'hf');
|
||||||
|
if (existsSync(hfBinary)) {
|
||||||
|
rmSync(hfBinary, { force: true });
|
||||||
|
logOk('Removed hf CLI binary');
|
||||||
|
}
|
||||||
|
|
||||||
log('\nRun: openclaw gateway restart', 'yellow');
|
log('\nRun: openclaw gateway restart', 'yellow');
|
||||||
}
|
}
|
||||||
|
|
||||||
async function main() {
|
async function main() {
|
||||||
console.log('');
|
console.log('');
|
||||||
log('╔══════════════════════════════════════════════╗', 'cyan');
|
log('╔════════════════════════════════════════════╗', 'cyan');
|
||||||
log('║ HarborForge Monitor Plugin Installer v0.1.0 ║', 'cyan');
|
log('║ HarborForge Plugin Installer v0.2.0 ║', 'cyan');
|
||||||
log('╚══════════════════════════════════════════════╝', 'cyan');
|
log('╚════════════════════════════════════════════╝', 'cyan');
|
||||||
console.log('');
|
console.log('');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -309,6 +414,9 @@ async function main() {
|
|||||||
|
|
||||||
if (!options.buildOnly) {
|
if (!options.buildOnly) {
|
||||||
await install();
|
await install();
|
||||||
|
if (options.installCli) {
|
||||||
|
await installCli();
|
||||||
|
}
|
||||||
await configure();
|
await configure();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,380 +0,0 @@
|
|||||||
/**
|
|
||||||
* HarborForge Monitor Telemetry Server
|
|
||||||
*
|
|
||||||
* Runs as separate process from Gateway.
|
|
||||||
* Collects system metrics and OpenClaw status, sends to Monitor.
|
|
||||||
*/
|
|
||||||
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, 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(),
|
|
||||||
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,
|
|
||||||
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
|
|
||||||
const log = {
|
|
||||||
debug: (...args) => CONFIG.logLevel === 'debug' && console.log('[DEBUG]', ...args),
|
|
||||||
info: (...args) => ['debug', 'info'].includes(CONFIG.logLevel) && console.log('[INFO]', ...args),
|
|
||||||
warn: (...args) => console.log('[WARN]', ...args),
|
|
||||||
error: (...args) => console.error('[ERROR]', ...args),
|
|
||||||
};
|
|
||||||
|
|
||||||
// State
|
|
||||||
let wsConnection = null;
|
|
||||||
let lastSuccessfulSend = null;
|
|
||||||
let consecutiveFailures = 0;
|
|
||||||
let isShuttingDown = false;
|
|
||||||
let cachedOpenclawVersion = null;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Collect system metrics
|
|
||||||
*/
|
|
||||||
async function collectSystemMetrics() {
|
|
||||||
try {
|
|
||||||
const cpuUsage = await getCpuUsage();
|
|
||||||
const memTotal = totalmem();
|
|
||||||
const memFree = freemem();
|
|
||||||
const memUsed = memTotal - memFree;
|
|
||||||
const diskInfo = await getDiskUsage();
|
|
||||||
const loadAvg = platform() !== 'win32' ? loadavg() : [0, 0, 0];
|
|
||||||
|
|
||||||
return {
|
|
||||||
cpu_pct: cpuUsage,
|
|
||||||
mem_pct: Math.round((memUsed / memTotal) * 100 * 10) / 10,
|
|
||||||
mem_used_mb: Math.round(memUsed / 1024 / 1024),
|
|
||||||
mem_total_mb: Math.round(memTotal / 1024 / 1024),
|
|
||||||
disk_pct: diskInfo.usedPct,
|
|
||||||
disk_used_gb: Math.round(diskInfo.usedGB * 10) / 10,
|
|
||||||
disk_total_gb: Math.round(diskInfo.totalGB * 10) / 10,
|
|
||||||
swap_pct: diskInfo.swapUsedPct || 0,
|
|
||||||
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(),
|
|
||||||
};
|
|
||||||
} catch (err) {
|
|
||||||
log.error('Failed to collect system metrics:', err.message);
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get CPU usage percentage
|
|
||||||
*/
|
|
||||||
async function getCpuUsage() {
|
|
||||||
try {
|
|
||||||
if (platform() === 'linux') {
|
|
||||||
const { stdout } = await execAsync("top -bn1 | grep 'Cpu(s)' | awk '{print $2}' | cut -d'%' -f1");
|
|
||||||
const usage = parseFloat(stdout.trim());
|
|
||||||
return isNaN(usage) ? 0 : Math.round(usage * 10) / 10;
|
|
||||||
} else if (platform() === 'darwin') {
|
|
||||||
const { stdout } = await execAsync("top -l 1 | grep 'CPU usage' | awk '{print $3}' | cut -d'%' -f1");
|
|
||||||
const usage = parseFloat(stdout.trim());
|
|
||||||
return isNaN(usage) ? 0 : Math.round(usage * 10) / 10;
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
try {
|
|
||||||
const stat = await readFile('/proc/stat', 'utf8');
|
|
||||||
const cpuLine = stat.split('\n')[0];
|
|
||||||
const parts = cpuLine.split(/\s+/).slice(1).map(Number);
|
|
||||||
const idle = parts[3];
|
|
||||||
const total = parts.reduce((a, b) => a + b, 0);
|
|
||||||
const usage = ((total - idle) / total) * 100;
|
|
||||||
return Math.round(usage * 10) / 10;
|
|
||||||
} catch {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get disk usage
|
|
||||||
*/
|
|
||||||
async function getDiskUsage() {
|
|
||||||
try {
|
|
||||||
if (platform() === 'linux' || platform() === 'darwin') {
|
|
||||||
const { stdout } = await execAsync("df -h / | tail -1 | awk '{print $2,$3,$5}'");
|
|
||||||
const [total, used, pct] = stdout.trim().split(/\s+/);
|
|
||||||
return {
|
|
||||||
totalGB: parseSizeToGB(total),
|
|
||||||
usedGB: parseSizeToGB(used),
|
|
||||||
usedPct: parseInt(pct.replace('%', ''), 10),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
log.debug('Failed to get disk usage:', err.message);
|
|
||||||
}
|
|
||||||
return { totalGB: 0, usedGB: 0, usedPct: 0 };
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseSizeToGB(size) {
|
|
||||||
const num = parseFloat(size);
|
|
||||||
if (size.includes('T')) return num * 1024;
|
|
||||||
if (size.includes('G')) return num;
|
|
||||||
if (size.includes('M')) return num / 1024;
|
|
||||||
if (size.includes('K')) return num / 1024 / 1024;
|
|
||||||
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, openclawVersion] = await Promise.all([
|
|
||||||
getOpenclawAgents(),
|
|
||||||
resolveOpenclawVersion(),
|
|
||||||
]);
|
|
||||||
return {
|
|
||||||
openclawVersion,
|
|
||||||
pluginVersion: CONFIG.pluginVersion,
|
|
||||||
agent_count: agents.length,
|
|
||||||
agents: agents.map(a => ({
|
|
||||||
id: a.id,
|
|
||||||
name: a.name,
|
|
||||||
status: a.status,
|
|
||||||
})),
|
|
||||||
};
|
|
||||||
} catch (err) {
|
|
||||||
log.debug('Failed to collect OpenClaw status:', err.message);
|
|
||||||
return {
|
|
||||||
openclawVersion: await resolveOpenclawVersion(),
|
|
||||||
pluginVersion: CONFIG.pluginVersion,
|
|
||||||
agent_count: 0,
|
|
||||||
agents: [],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get list of OpenClaw agents from local state
|
|
||||||
*/
|
|
||||||
function extractJsonPrefix(text) {
|
|
||||||
const trimmed = text.trim();
|
|
||||||
if (!trimmed) return null;
|
|
||||||
|
|
||||||
const startsWith = trimmed[0];
|
|
||||||
if (startsWith !== '[' && startsWith !== '{') return null;
|
|
||||||
|
|
||||||
let depth = 0;
|
|
||||||
let inString = false;
|
|
||||||
let escape = false;
|
|
||||||
for (let i = 0; i < trimmed.length; i += 1) {
|
|
||||||
const ch = trimmed[i];
|
|
||||||
if (escape) {
|
|
||||||
escape = false;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (ch === '\\') {
|
|
||||||
escape = true;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (ch === '"') {
|
|
||||||
inString = !inString;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (inString) continue;
|
|
||||||
if (ch === '[' || ch === '{') depth += 1;
|
|
||||||
if (ch === ']' || ch === '}') depth -= 1;
|
|
||||||
if (depth === 0) {
|
|
||||||
return trimmed.slice(0, i + 1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function getOpenclawAgents() {
|
|
||||||
try {
|
|
||||||
try {
|
|
||||||
const { stdout } = await execAsync('openclaw agents list --json 2>/dev/null');
|
|
||||||
const jsonPrefix = extractJsonPrefix(stdout);
|
|
||||||
if (jsonPrefix) {
|
|
||||||
const agents = JSON.parse(jsonPrefix);
|
|
||||||
if (Array.isArray(agents)) {
|
|
||||||
return agents.map((agent) => ({
|
|
||||||
id: agent.id,
|
|
||||||
name: agent.name || agent.id,
|
|
||||||
status: agent.isDefault ? 'default' : 'configured',
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
log.debug('Failed to get agents from `openclaw agents list --json`:', err.message);
|
|
||||||
}
|
|
||||||
|
|
||||||
const agentConfigPath = `${CONFIG.openclawPath}/agents.json`;
|
|
||||||
try {
|
|
||||||
await access(agentConfigPath, constants.R_OK);
|
|
||||||
const data = JSON.parse(await readFile(agentConfigPath, 'utf8'));
|
|
||||||
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 [];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Build telemetry payload
|
|
||||||
*/
|
|
||||||
async function buildPayload() {
|
|
||||||
const system = await collectSystemMetrics();
|
|
||||||
const openclaw = await collectOpenclawStatus();
|
|
||||||
|
|
||||||
return {
|
|
||||||
identifier: CONFIG.identifier,
|
|
||||||
timestamp: new Date().toISOString(),
|
|
||||||
...system,
|
|
||||||
openclaw_version: openclaw.openclawVersion,
|
|
||||||
plugin_version: openclaw.pluginVersion,
|
|
||||||
agents: openclaw.agents,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Send telemetry via HTTP
|
|
||||||
*/
|
|
||||||
async function sendHttpHeartbeat() {
|
|
||||||
try {
|
|
||||||
const payload = await buildPayload();
|
|
||||||
log.debug('Sending HTTP 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',
|
|
||||||
headers,
|
|
||||||
body: JSON.stringify(payload),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (response.ok) {
|
|
||||||
log.debug('HTTP heartbeat sent successfully');
|
|
||||||
lastSuccessfulSend = Date.now();
|
|
||||||
consecutiveFailures = 0;
|
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
throw new Error(`HTTP ${response.status}: ${await response.text()}`);
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
log.error('HTTP heartbeat failed:', err.message);
|
|
||||||
consecutiveFailures++;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Main reporting loop
|
|
||||||
*/
|
|
||||||
async function reportingLoop() {
|
|
||||||
while (!isShuttingDown) {
|
|
||||||
try {
|
|
||||||
const success = await sendHttpHeartbeat();
|
|
||||||
|
|
||||||
let interval = CONFIG.reportIntervalSec * 1000;
|
|
||||||
if (!success) {
|
|
||||||
const backoff = Math.min(consecutiveFailures * 10000, 300000);
|
|
||||||
interval = Math.max(interval, backoff);
|
|
||||||
log.info(`Retry in ${interval}ms (backoff)`);
|
|
||||||
}
|
|
||||||
|
|
||||||
await new Promise(resolve => setTimeout(resolve, interval));
|
|
||||||
} catch (err) {
|
|
||||||
log.error('Reporting loop error:', err.message);
|
|
||||||
await new Promise(resolve => setTimeout(resolve, 30000));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Graceful shutdown
|
|
||||||
*/
|
|
||||||
function shutdown() {
|
|
||||||
log.info('Shutting down telemetry server...');
|
|
||||||
isShuttingDown = true;
|
|
||||||
|
|
||||||
if (wsConnection) {
|
|
||||||
wsConnection.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
sendHttpHeartbeat().finally(() => {
|
|
||||||
process.exit(0);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Handle signals
|
|
||||||
process.on('SIGTERM', shutdown);
|
|
||||||
process.on('SIGINT', shutdown);
|
|
||||||
|
|
||||||
// Start
|
|
||||||
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,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!CONFIG.apiKey) {
|
|
||||||
log.warn('Missing HF_MONITOR_API_KEY environment variable - API authentication will fail');
|
|
||||||
}
|
|
||||||
|
|
||||||
reportingLoop();
|
|
||||||
59
skills/hf/SKILL.md
Normal file
59
skills/hf/SKILL.md
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
# hf - HarborForge CLI
|
||||||
|
|
||||||
|
`hf` is the Go-based CLI for HarborForge. It manages users, projects, tasks, milestones, meetings, support tickets, proposals, and server monitoring.
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# See all available commands (including those you may not have permission for)
|
||||||
|
hf --help
|
||||||
|
|
||||||
|
# See only the commands you're permitted to use
|
||||||
|
hf --help-brief
|
||||||
|
|
||||||
|
# Check API health
|
||||||
|
hf health
|
||||||
|
|
||||||
|
# Show CLI version
|
||||||
|
hf version
|
||||||
|
```
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Set the HarborForge API URL
|
||||||
|
hf config --url https://your-harborforge.example.com
|
||||||
|
|
||||||
|
# View current config
|
||||||
|
hf config
|
||||||
|
```
|
||||||
|
|
||||||
|
## Usage Tips
|
||||||
|
|
||||||
|
- Use `hf --help-brief` to quickly see what you can do — it hides commands you don't have permission for.
|
||||||
|
- Use `hf <group> --help` for the full subcommand list of any group (e.g. `hf task --help`).
|
||||||
|
- Add `--json` to any command for machine-readable JSON output.
|
||||||
|
- Resources use **codes** (not numeric IDs) — e.g. `hf task get TASK-42`.
|
||||||
|
|
||||||
|
## Authentication
|
||||||
|
|
||||||
|
If `pass_mgr` is available (padded-cell mode), authentication is automatic — no flags needed.
|
||||||
|
|
||||||
|
Without `pass_mgr` (manual mode), pass `--token <token>` to authenticated commands.
|
||||||
|
|
||||||
|
## Command Groups
|
||||||
|
|
||||||
|
| Group | Description |
|
||||||
|
|-------------|------------------------------------|
|
||||||
|
| `user` | Manage user accounts |
|
||||||
|
| `role` | Manage roles and permissions |
|
||||||
|
| `project` | Manage projects and members |
|
||||||
|
| `milestone` | Manage project milestones |
|
||||||
|
| `task` | Manage and track tasks |
|
||||||
|
| `meeting` | Manage meetings and attendance |
|
||||||
|
| `support` | Manage support tickets |
|
||||||
|
| `propose` | Manage proposals |
|
||||||
|
| `monitor` | Monitor servers and API keys |
|
||||||
|
| `config` | CLI configuration |
|
||||||
|
| `health` | API health check |
|
||||||
|
| `version` | Show CLI version |
|
||||||
Reference in New Issue
Block a user