refactor(plugin): read config via api.pluginConfig and api.config

- Mirror dirigent plugin registration pattern
- Read base config from api.pluginConfig
- Read live config from api.config.plugins.entries.harborforge-monitor.config
- Support gateway_start/gateway_stop lifecycle only
- Compile nested plugin/core files
This commit is contained in:
zhi
2026-03-20 07:13:12 +00:00
parent de4ef87491
commit 006784db63
3 changed files with 188 additions and 153 deletions

View File

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

View File

@@ -6,21 +6,7 @@
import { spawn } from 'child_process'; import { spawn } from 'child_process';
import { join } from 'path'; import { join } from 'path';
import { existsSync } from 'fs'; import { existsSync } from 'fs';
import { getLivePluginConfig, type HarborForgeMonitorConfig } from './core/live-config';
interface PluginConfig {
enabled?: boolean;
backendUrl?: string;
identifier?: string;
apiKey?: string;
reportIntervalSec?: number;
httpFallbackIntervalSec?: number;
logLevel?: 'debug' | 'info' | 'warn' | 'error';
}
interface PluginEntryLike {
enabled?: boolean;
config?: PluginConfig;
}
interface PluginAPI { interface PluginAPI {
logger: { logger: {
@@ -30,12 +16,16 @@ interface PluginAPI {
warn: (...args: any[]) => void; warn: (...args: any[]) => void;
}; };
version?: string; version?: string;
isRunning?: () => boolean; config?: Record<string, unknown>;
pluginConfig?: Record<string, unknown>;
on: (event: string, handler: () => void) => void; on: (event: string, handler: () => void) => void;
registerTool: (factory: (ctx: any) => any) => void; registerTool: (factory: (ctx: any) => any) => void;
} }
export default function register(api: PluginAPI, rawConfig: PluginConfig | PluginEntryLike | undefined) { export default {
id: 'harborforge-monitor',
name: 'HarborForge Monitor',
register(api: PluginAPI) {
const logger = api.logger || { const logger = api.logger || {
info: (...args: any[]) => console.log('[HF-Monitor]', ...args), info: (...args: any[]) => console.log('[HF-Monitor]', ...args),
error: (...args: any[]) => console.error('[HF-Monitor]', ...args), error: (...args: any[]) => console.error('[HF-Monitor]', ...args),
@@ -43,21 +33,32 @@ export default function register(api: PluginAPI, rawConfig: PluginConfig | Plugi
warn: (...args: any[]) => console.warn('[HF-Monitor]', ...args), warn: (...args: any[]) => console.warn('[HF-Monitor]', ...args),
}; };
const entryLike = rawConfig as PluginEntryLike | undefined; const baseConfig: HarborForgeMonitorConfig = {
const config: PluginConfig = entryLike?.config enabled: true,
? { backendUrl: 'https://monitor.hangman-lab.top',
...entryLike.config, identifier: '',
enabled: entryLike.config.enabled ?? entryLike.enabled, reportIntervalSec: 30,
} httpFallbackIntervalSec: 60,
: ((rawConfig as PluginConfig | undefined) ?? {}); logLevel: 'info',
...(api.pluginConfig || {}),
};
const enabled = config.enabled !== false; 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', { logger.info('HarborForge Monitor plugin config resolved', {
enabled, enabled,
hasApiKey: Boolean(config.apiKey), hasApiKey: Boolean(live.apiKey),
backendUrl: config.backendUrl ?? null, backendUrl: live.backendUrl ?? null,
identifier: config.identifier ?? null, identifier: live.identifier ?? null,
}); });
if (!enabled) { if (!enabled) {
@@ -65,36 +66,31 @@ export default function register(api: PluginAPI, rawConfig: PluginConfig | Plugi
return; return;
} }
if (!config.apiKey) { if (sidecar) {
logger.debug('Sidecar already running');
return;
}
if (!live.apiKey) {
logger.warn('Missing config: apiKey'); logger.warn('Missing config: apiKey');
logger.warn('API authentication will fail. Generate apiKey from HarborForge Monitor admin.'); logger.warn('API authentication will fail. Generate apiKey from HarborForge Monitor admin.');
} }
const serverPath = join(__dirname, 'server', 'telemetry.mjs');
if (!existsSync(serverPath)) { if (!existsSync(serverPath)) {
logger.error('Telemetry server not found:', serverPath); logger.error('Telemetry server not found:', serverPath);
return; return;
} }
let sidecar: ReturnType<typeof spawn> | null = null;
function startSidecar() {
if (sidecar) {
logger.debug('Sidecar already running');
return;
}
logger.info('Starting HarborForge Monitor telemetry server...'); logger.info('Starting HarborForge Monitor telemetry server...');
const env = { const env = {
...process.env, ...process.env,
HF_MONITOR_BACKEND_URL: config.backendUrl || 'https://monitor.hangman-lab.top', HF_MONITOR_BACKEND_URL: live.backendUrl || 'https://monitor.hangman-lab.top',
HF_MONITOR_IDENTIFIER: config.identifier || '', HF_MONITOR_IDENTIFIER: live.identifier || '',
HF_MONITOR_API_KEY: config.apiKey || '', HF_MONITOR_API_KEY: live.apiKey || '',
HF_MONITOR_REPORT_INTERVAL: String(config.reportIntervalSec || 30), HF_MONITOR_REPORT_INTERVAL: String(live.reportIntervalSec || 30),
HF_MONITOR_HTTP_FALLBACK_INTERVAL: String(config.httpFallbackIntervalSec || 60), HF_MONITOR_HTTP_FALLBACK_INTERVAL: String(live.httpFallbackIntervalSec || 60),
HF_MONITOR_LOG_LEVEL: config.logLevel || 'info', HF_MONITOR_LOG_LEVEL: live.logLevel || 'info',
OPENCLAW_PATH: process.env.OPENCLAW_PATH || join(process.env.HOME || '/root', '.openclaw'), OPENCLAW_PATH: process.env.OPENCLAW_PATH || join(process.env.HOME || '/root', '.openclaw'),
OPENCLAW_VERSION: api.version || 'unknown', OPENCLAW_VERSION: api.version || 'unknown',
}; };
@@ -102,7 +98,7 @@ export default function register(api: PluginAPI, rawConfig: PluginConfig | Plugi
sidecar = spawn('node', [serverPath], { sidecar = spawn('node', [serverPath], {
env, env,
detached: false, detached: false,
stdio: ['ignore', 'pipe', 'pipe'] stdio: ['ignore', 'pipe', 'pipe'],
}); });
sidecar.stdout?.on('data', (data: Buffer) => { sidecar.stdout?.on('data', (data: Buffer) => {
@@ -147,42 +143,42 @@ export default function register(api: PluginAPI, rawConfig: PluginConfig | Plugi
}); });
} }
// Hook into Gateway lifecycle
api.on('gateway_start', () => { api.on('gateway_start', () => {
logger.info('Gateway starting, starting telemetry server...'); logger.info('gateway_start received, starting telemetry server...');
startSidecar(); startSidecar();
}); });
api.on('gateway_stop', () => { api.on('gateway_stop', () => {
logger.info('Gateway stopping, stopping telemetry server...'); logger.info('gateway_stop received, stopping telemetry server...');
stopSidecar(); stopSidecar();
}); });
// Handle process signals
process.on('SIGTERM', stopSidecar); process.on('SIGTERM', stopSidecar);
process.on('SIGINT', stopSidecar); process.on('SIGINT', stopSidecar);
// Register status tool
api.registerTool(() => ({ api.registerTool(() => ({
name: 'harborforge_monitor_status', name: 'harborforge_monitor_status',
description: 'Get HarborForge Monitor plugin status', description: 'Get HarborForge Monitor plugin status',
parameters: { parameters: {
type: 'object', type: 'object',
properties: {} properties: {},
}, },
async execute() { async execute() {
const live = resolveConfig();
return { return {
enabled: true, enabled: live.enabled !== false,
sidecarRunning: sidecar !== null && sidecar.exitCode === null, sidecarRunning: sidecar !== null && sidecar.exitCode === null,
pid: sidecar?.pid || null, pid: sidecar?.pid || null,
config: { config: {
backendUrl: config.backendUrl, backendUrl: live.backendUrl,
identifier: config.identifier || 'auto-detected', identifier: live.identifier || 'auto-detected',
reportIntervalSec: config.reportIntervalSec reportIntervalSec: live.reportIntervalSec,
} hasApiKey: Boolean(live.apiKey),
},
}; };
} },
})); }));
logger.info('HarborForge Monitor plugin registered'); logger.info('HarborForge Monitor plugin registered');
} },
};

View File

@@ -12,6 +12,6 @@
"declarationMap": true, "declarationMap": true,
"sourceMap": true "sourceMap": true
}, },
"include": ["*.ts"], "include": ["**/*.ts"],
"exclude": ["node_modules"] "exclude": ["node_modules"]
} }