Files
PaddedCell/install.mjs
zhi 0daf1432a7 refactor: rewrite install script to match Dirigent pattern
- Plugin name changed to 'padded-cell' (in OpenClaw)
- Install to ~/.openclaw/plugins/padded-cell/ instead of skills
- Add plugins.entries.padded-cell configuration
- Add to plugins.allow list
- Use --install and --uninstall flags
- Follow Dirigent's delta tracking pattern
2026-03-05 11:49:56 +00:00

449 lines
13 KiB
JavaScript
Executable File

#!/usr/bin/env node
/**
* PaddedCell Plugin Installer
*
* Usage:
* node install.mjs --install
* node install.mjs --uninstall
*/
import { execSync, spawnSync } from 'child_process';
import { existsSync, mkdirSync, copyFileSync, writeFileSync, chmodSync, readdirSync, statSync } from 'fs';
import { dirname, join, resolve } from 'path';
import { fileURLToPath } from 'url';
import { homedir, platform } from 'os';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Plugin configuration
const PLUGIN_NAME = 'padded-cell';
const PLUGIN_ENTRY = `plugins.entries.${PLUGIN_NAME}`;
const PLUGIN_ALLOW_PATH = 'plugins.allow';
const PLUGINS_LOAD_PATHS = 'plugins.load.paths';
// Parse arguments
const args = process.argv.slice(2);
const mode = args.includes('--uninstall') ? 'uninstall' : (args.includes('--install') ? 'install' : null);
if (!mode) {
console.error('Usage: install.mjs --install | --uninstall');
process.exit(2);
}
// Colors for output
const colors = {
reset: '\x1b[0m',
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
cyan: '\x1b[36m',
};
function log(message, color = 'reset') {
console.log(`${colors[color]}${message}${colors.reset}`);
}
function logSuccess(message) {
log(`[${PLUGIN_NAME}] ✓ ${message}`, 'green');
}
function logWarning(message) {
log(`[${PLUGIN_NAME}] ⚠ ${message}`, 'yellow');
}
function logError(message) {
log(`[${PLUGIN_NAME}] ✗ ${message}`, 'red');
}
function logInfo(message) {
log(`[${PLUGIN_NAME}] ${message}`, 'cyan');
}
// Execute openclaw command
function runOpenclaw(args, { allowFail = false } = {}) {
try {
return execSync('openclaw', args, { encoding: 'utf8' }).trim();
} catch (e) {
if (allowFail) return null;
throw e;
}
}
// Get config value as JSON
function getJson(pathKey) {
const out = runOpenclaw(['config', 'get', pathKey, '--json'], { allowFail: true });
if (out == null || out === '' || out === 'undefined') return undefined;
try {
return JSON.parse(out);
} catch {
return undefined;
}
}
// Set config value as JSON
function setJson(pathKey, value) {
runOpenclaw(['config', 'set', pathKey, JSON.stringify(value), '--json']);
}
// Unset config path
function unsetPath(pathKey) {
runOpenclaw(['config', 'unset', pathKey], { allowFail: true });
}
// Deep clone
function clone(v) {
if (v === undefined) return undefined;
return JSON.parse(JSON.stringify(v));
}
// Copy directory recursively
function copyDir(src, dest) {
mkdirSync(dest, { recursive: true });
const entries = readdirSync(src, { withFileTypes: true });
for (const entry of entries) {
const srcPath = join(src, entry.name);
const destPath = join(dest, entry.name);
if (entry.isDirectory()) {
copyDir(srcPath, destPath);
} else {
copyFileSync(srcPath, destPath);
}
}
}
// ============================================================================
// Detect Environment
// ============================================================================
function detectEnvironment() {
const env = {
openclawDir: join(homedir(), '.openclaw'),
nodeVersion: null,
goVersion: null,
};
// Check Node.js
try {
env.nodeVersion = execSync('node --version', { encoding: 'utf8' }).trim();
} catch {
logError('Node.js not found');
}
// Check Go
try {
env.goVersion = execSync('go version', { encoding: 'utf8' }).trim();
} catch {
logError('Go not found');
}
return env;
}
// ============================================================================
// Build Components
// ============================================================================
function buildComponents(env) {
logInfo('Building components...');
// Build pass_mgr
log(' Building pass_mgr (Go)...', 'blue');
try {
const passMgrDir = join(__dirname, 'pass_mgr');
execSync('go mod tidy', { cwd: passMgrDir, stdio: 'inherit' });
execSync('go build -o dist/pass_mgr src/main.go', { cwd: passMgrDir, stdio: 'inherit' });
const binaryPath = join(passMgrDir, 'dist', 'pass_mgr');
if (!existsSync(binaryPath)) {
throw new Error('pass_mgr binary not found after build');
}
chmodSync(binaryPath, 0o755);
logSuccess('pass_mgr built successfully');
} catch (err) {
logError(`Failed to build pass_mgr: ${err.message}`);
throw err;
}
// Build pcexec
log(' Building pcexec (TypeScript)...', 'blue');
try {
const pcexecDir = join(__dirname, 'pcexec');
execSync('npm install', { cwd: pcexecDir, stdio: 'inherit' });
execSync('npm run build', { cwd: pcexecDir, stdio: 'inherit' });
logSuccess('pcexec built successfully');
} catch (err) {
logError(`Failed to build pcexec: ${err.message}`);
throw err;
}
// Build safe-restart
log(' Building safe-restart (TypeScript)...', 'blue');
try {
const safeRestartDir = join(__dirname, 'safe-restart');
execSync('npm install', { cwd: safeRestartDir, stdio: 'inherit' });
execSync('npm run build', { cwd: safeRestartDir, stdio: 'inherit' });
logSuccess('safe-restart built successfully');
} catch (err) {
logError(`Failed to build safe-restart: ${err.message}`);
throw err;
}
}
// ============================================================================
// Install Plugin
// ============================================================================
function installPlugin(env) {
logInfo('Installing plugin...');
const pluginDir = join(env.openclawDir, 'plugins', PLUGIN_NAME);
const binDir = join(env.openclawDir, 'bin');
// Create directories
mkdirSync(pluginDir, { recursive: true });
mkdirSync(binDir, { recursive: true });
// Copy plugin files
log(' Copying plugin files...', 'blue');
// Copy pcexec
const pcexecSource = join(__dirname, 'pcexec');
const pcexecDest = join(pluginDir, 'pcexec');
copyDir(pcexecSource, pcexecDest);
logSuccess(`Installed pcexec to ${pcexecDest}`);
// Copy safe-restart
const safeRestartSource = join(__dirname, 'safe-restart');
const safeRestartDest = join(pluginDir, 'safe-restart');
copyDir(safeRestartSource, safeRestartDest);
logSuccess(`Installed safe-restart to ${safeRestartDest}`);
// Install pass_mgr binary
const passMgrSource = join(__dirname, 'pass_mgr', 'dist', 'pass_mgr');
const passMgrDest = join(binDir, 'pass_mgr');
copyFileSync(passMgrSource, passMgrDest);
chmodSync(passMgrDest, 0o755);
logSuccess(`Installed pass_mgr binary to ${passMgrDest}`);
return { pluginDir, passMgrPath: passMgrDest };
}
// ============================================================================
// Configure OpenClaw
// ============================================================================
function configureOpenClaw(env, pluginDir, delta) {
logInfo('Configuring OpenClaw...');
// 1. Add plugin to plugins.allow
const allowList = getJson(PLUGIN_ALLOW_PATH) || [];
const oldAllow = clone(allowList);
if (!allowList.includes(PLUGIN_NAME)) {
allowList.push(PLUGIN_NAME);
setJson(PLUGIN_ALLOW_PATH, allowList);
delta.added[PLUGIN_ALLOW_PATH] = PLUGIN_NAME;
delta._prev = delta._prev || {};
delta._prev[PLUGIN_ALLOW_PATH] = oldAllow;
logSuccess(`Added '${PLUGIN_NAME}' to plugins.allow`);
} else {
log(' Already in plugins.allow', 'green');
}
// 2. Add plugin entry
const oldEntry = getJson(PLUGIN_ENTRY);
const newEntry = {
enabled: true,
config: {
enabled: true,
passMgrPath: join(env.openclawDir, 'bin', 'pass_mgr'),
pluginDir: pluginDir,
},
};
if (oldEntry === undefined) {
delta.added[PLUGIN_ENTRY] = newEntry;
} else {
delta.replaced[PLUGIN_ENTRY] = oldEntry;
}
// Use set for nested path
const plugins = getJson('plugins') || {};
plugins.entries = plugins.entries || {};
plugins.entries[PLUGIN_NAME] = newEntry;
setJson('plugins', plugins);
logSuccess(`Configured ${PLUGIN_ENTRY}`);
// 3. Add to plugins.load.paths
const pluginsConfig = getJson('plugins') || {};
const oldPaths = clone(pluginsConfig.load?.paths) || [];
const newPaths = clone(oldPaths);
if (!newPaths.includes(pluginDir)) {
newPaths.push(pluginDir);
delta.added[PLUGINS_LOAD_PATHS] = pluginDir;
delta._prev = delta._prev || {};
delta._prev[PLUGINS_LOAD_PATHS] = oldPaths;
pluginsConfig.load = pluginsConfig.load || {};
pluginsConfig.load.paths = newPaths;
setJson('plugins', pluginsConfig);
logSuccess(`Added plugin path to ${PLUGINS_LOAD_PATHS}`);
} else {
log(' Plugin path already in load.paths', 'green');
}
}
// ============================================================================
// Unconfigure OpenClaw
// ============================================================================
function unconfigureOpenClaw(env, delta) {
logInfo('Removing OpenClaw configuration...');
// 1. Remove from plugins.allow first (before removing entry)
if (delta.added?.[PLUGIN_ALLOW_PATH] !== undefined) {
const allowList = getJson(PLUGIN_ALLOW_PATH) || [];
const idx = allowList.indexOf(PLUGIN_NAME);
if (idx !== -1) {
allowList.splice(idx, 1);
setJson(PLUGIN_ALLOW_PATH, allowList);
logSuccess(`Removed '${PLUGIN_NAME}' from plugins.allow`);
}
}
// 2. Remove plugin entry
if (delta.added?.[PLUGIN_ENTRY] !== undefined || delta.replaced?.[PLUGIN_ENTRY] !== undefined) {
unsetPath(PLUGIN_ENTRY);
logSuccess(`Removed ${PLUGIN_ENTRY}`);
}
// 3. Remove from plugins.load.paths
if (delta.added?.[PLUGINS_LOAD_PATHS] !== undefined) {
const plugins = getJson('plugins') || {};
const paths = plugins.load?.paths || [];
const pluginDir = join(env.openclawDir, 'plugins', PLUGIN_NAME);
const idx = paths.indexOf(pluginDir);
if (idx !== -1) {
paths.splice(idx, 1);
plugins.load.paths = paths;
setJson('plugins', plugins);
logSuccess(`Removed plugin path from ${PLUGINS_LOAD_PATHS}`);
}
}
}
// ============================================================================
// Remove Plugin Files
// ============================================================================
function removePluginFiles(env) {
logInfo('Removing plugin files...');
const pluginDir = join(env.openclawDir, 'plugins', PLUGIN_NAME);
const passMgrBinary = join(env.openclawDir, 'bin', 'pass_mgr');
// Remove plugin directory
if (existsSync(pluginDir)) {
try {
execSync(`rm -rf "${pluginDir}"`, { encoding: 'utf8' });
logSuccess(`Removed ${pluginDir}`);
} catch (err) {
logError(`Failed to remove ${pluginDir}: ${err.message}`);
}
}
// Remove pass_mgr binary
if (existsSync(passMgrBinary)) {
try {
execSync(`rm -f "${passMgrBinary}"`, { encoding: 'utf8' });
logSuccess(`Removed ${passMgrBinary}`);
} catch (err) {
logError(`Failed to remove ${passMgrBinary}: ${err.message}`);
}
}
}
// ============================================================================
// Main
// ============================================================================
function main() {
const env = detectEnvironment();
if (mode === 'install') {
logInfo('Starting installation...');
try {
// Build components
buildComponents(env);
// Install plugin files
const { pluginDir, passMgrPath } = installPlugin(env);
// Configure OpenClaw
const delta = { added: {}, replaced: {}, removed: {} };
configureOpenClaw(env, pluginDir, delta);
logInfo('Installation complete!');
console.log('');
log('Next steps:', 'cyan');
console.log('');
log('1. Initialize pass_mgr (required before first use):', 'yellow');
log(` ${passMgrPath} admin init`, 'cyan');
console.log('');
log('2. Test pass_mgr:', 'yellow');
log(` ${passMgrPath} set test_key mypass`, 'cyan');
log(` ${passMgrPath} get test_key`, 'cyan');
console.log('');
log('3. Restart OpenClaw gateway to apply changes:', 'yellow');
log(' openclaw gateway restart', 'cyan');
} catch (err) {
logError(`Installation failed: ${err.message}`);
process.exit(1);
}
} else {
logInfo('Starting uninstallation...');
// For uninstall, we need the delta from install
// For simplicity, we'll track what we added and remove it
const delta = {
added: {},
replaced: {},
removed: {}
};
// Assume we added these during install
const pluginDir = join(env.openclawDir, 'plugins', PLUGIN_NAME);
delta.added[PLUGIN_ALLOW_PATH] = PLUGIN_NAME;
delta.added[PLUGIN_ENTRY] = { enabled: true };
delta.added[PLUGINS_LOAD_PATHS] = pluginDir;
try {
// Unconfigure OpenClaw
unconfigureOpenClaw(env, delta);
// Remove plugin files
removePluginFiles(env);
logInfo('Uninstallation complete!');
console.log('');
log('Restart OpenClaw gateway to apply changes:', 'yellow');
log(' openclaw gateway restart', 'cyan');
} catch (err) {
logError(`Uninstallation failed: ${err.message}`);
process.exit(1);
}
}
}
main();