feat: refactor project structure + add pcguard + AGENT_VERIFY injection
- Restructure: pcexec/ and safe-restart/ → plugin/{tools,core,commands}
- New pcguard Go binary: validates AGENT_VERIFY, AGENT_ID, AGENT_WORKSPACE
- pcexec now injects AGENT_VERIFY env + appends openclaw bin to PATH
- plugin/index.ts: unified TypeScript entry point with resolveOpenclawPath()
- install.mjs: support --openclaw-profile-path, install pcguard, new paths
- README: updated structure docs + security limitations note
- Removed old root index.js and openclaw.plugin.json
This commit is contained in:
3
.gitignore
vendored
3
.gitignore
vendored
@@ -28,3 +28,6 @@ Thumbs.db
|
|||||||
*.a
|
*.a
|
||||||
*.test
|
*.test
|
||||||
vendor/
|
vendor/
|
||||||
|
|
||||||
|
# Lock files (sub-packages)
|
||||||
|
plugin/package-lock.json
|
||||||
|
|||||||
152
README.md
152
README.md
@@ -10,128 +10,116 @@ OpenClaw plugin for secure password management, safe command execution, and coor
|
|||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
### 1. pass_mgr - Password Manager Binary (Go)
|
### 1. pass_mgr — Password Manager (Go)
|
||||||
|
|
||||||
AES-256-GCM encryption, per-agent key-based encryption/decryption.
|
AES-256-GCM encryption, per-agent key-based encryption/decryption.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Initialize
|
pass_mgr admin init # Initialize
|
||||||
pass_mgr admin init [--key-path <path>]
|
pass_mgr get <key> # Get password
|
||||||
|
pass_mgr set <key> <password> # Set password (human only)
|
||||||
# Get password
|
pass_mgr generate <key> # Generate password
|
||||||
pass_mgr get <key> [--username]
|
pass_mgr unset <key> # Delete
|
||||||
|
pass_mgr rotate <key> # Rotate
|
||||||
# Generate password (agent can use)
|
|
||||||
pass_mgr generate <key> [--username <user>]
|
|
||||||
|
|
||||||
# Set password (human only)
|
|
||||||
pass_mgr set <key> <password> [--username <user>]
|
|
||||||
|
|
||||||
# Delete password
|
|
||||||
pass_mgr unset <key>
|
|
||||||
|
|
||||||
# Rotate password
|
|
||||||
pass_mgr rotate <key>
|
|
||||||
```
|
```
|
||||||
|
|
||||||
**Security Features:**
|
### 2. pcguard — Exec Guard (Go)
|
||||||
- Agents cannot execute `set` (detected via environment variables)
|
|
||||||
- All operations fail before initialization
|
|
||||||
- Admin password leak detection (monitors messages/tool calls)
|
|
||||||
|
|
||||||
### 2. pcexec - Safe Execution Tool (TypeScript)
|
Validates that a process is running inside a pcexec context by checking environment sentinels (`AGENT_VERIFY`, `AGENT_ID`, `AGENT_WORKSPACE`). Returns exit code 1 with error message if any check fails.
|
||||||
|
|
||||||
Compatible with OpenClaw native exec interface, automatically handles `pass_mgr get` and sanitizes output.
|
Scripts can call `pcguard` at the top to ensure they're executed via pcexec:
|
||||||
|
|
||||||
```typescript
|
```bash
|
||||||
import { pcexec } from 'pcexec';
|
#!/bin/bash
|
||||||
|
pcguard || exit 1
|
||||||
const result = await pcexec('echo $(pass_mgr get mypassword)', {
|
# ... rest of script
|
||||||
cwd: '/workspace',
|
|
||||||
timeout: 30000,
|
|
||||||
});
|
|
||||||
// Passwords in result.stdout will be replaced with ######
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### 3. safe-restart - Safe Restart Module (TypeScript)
|
### 3. pcexec — Safe Execution Tool (TypeScript)
|
||||||
|
|
||||||
Provides agent state management and coordinated restart.
|
Drop-in replacement for `exec` that:
|
||||||
|
- Resolves `$(pass_mgr get key)` inline and sanitizes passwords from output
|
||||||
|
- Injects `AGENT_VERIFY`, `AGENT_ID`, `AGENT_WORKSPACE` environment variables
|
||||||
|
- Appends `$(openclaw path)/bin` to `PATH` (making `pcguard` and `pass_mgr` available)
|
||||||
|
|
||||||
**Agent States:**
|
### 4. safe-restart — Coordinated Restart (TypeScript)
|
||||||
- `idle` - Idle
|
|
||||||
- `busy` - Processing messages
|
Agent state management and coordinated gateway restart.
|
||||||
- `focus` - Focus mode (workflow)
|
|
||||||
- `freeze` - Frozen (not accepting new messages)
|
**Agent States:** idle → busy → focus → freeze → pre-freeze
|
||||||
- `pre-freeze` - Preparing to freeze
|
|
||||||
- `pre-freeze-focus` - Preparing to freeze (focus mode)
|
|
||||||
|
|
||||||
**APIs:**
|
**APIs:**
|
||||||
- `POST /query-restart` - Query restart readiness
|
- `POST /query-restart` — Query restart readiness
|
||||||
- `POST /restart-result` - Report restart result
|
- `POST /restart-result` — Report restart result
|
||||||
- `GET /status` - Get all statuses
|
- `GET /status` — Get all statuses
|
||||||
|
|
||||||
**Slash Commands:**
|
## ⚠️ Security Limitations
|
||||||
```
|
|
||||||
/padded-cell-ctrl status
|
> **PCEXEC + PCGUARD only mitigate light model hallucination / misoperation / prompt forgetting.**
|
||||||
/padded-cell-ctrl enable pass-mgr|safe-restart
|
> They **do not** defend against malicious attacks.
|
||||||
/padded-cell-ctrl disable pass-mgr|safe-restart
|
> For stronger security, use **sandbox mode** instead of this plugin.
|
||||||
```
|
|
||||||
|
|
||||||
## Project Structure
|
## Project Structure
|
||||||
|
|
||||||
```
|
```
|
||||||
PaddedCell/
|
PaddedCell/
|
||||||
|
├── plugin/ # Plugin source (TypeScript)
|
||||||
|
│ ├── commands/ # Slash commands
|
||||||
|
│ ├── core/ # Core modules (safe-restart, status, api)
|
||||||
|
│ ├── hooks/ # Lifecycle hooks
|
||||||
|
│ ├── tools/ # Tool definitions (pcexec)
|
||||||
|
│ ├── index.ts # Plugin entry point
|
||||||
|
│ ├── openclaw.plugin.json
|
||||||
|
│ ├── package.json
|
||||||
|
│ └── tsconfig.json
|
||||||
├── pass_mgr/ # Go password manager binary
|
├── pass_mgr/ # Go password manager binary
|
||||||
│ ├── src/
|
│ └── src/main.go
|
||||||
│ │ └── main.go
|
├── pcguard/ # Go exec guard binary
|
||||||
│ └── go.mod
|
│ └── src/main.go
|
||||||
├── pcexec/ # TypeScript safe execution tool
|
|
||||||
│ ├── src/
|
|
||||||
│ │ └── index.ts
|
|
||||||
│ ├── package.json
|
|
||||||
│ └── tsconfig.json
|
|
||||||
├── safe-restart/ # TypeScript safe restart module
|
|
||||||
│ ├── src/
|
|
||||||
│ │ ├── index.ts
|
|
||||||
│ │ ├── status-manager.ts
|
|
||||||
│ │ ├── api.ts
|
|
||||||
│ │ ├── safe-restart.ts
|
|
||||||
│ │ └── slash-commands.ts
|
|
||||||
│ ├── package.json
|
|
||||||
│ └── tsconfig.json
|
|
||||||
├── docs/ # Documentation
|
├── docs/ # Documentation
|
||||||
├── PROJECT_PLAN.md # Project plan
|
├── scripts/ # Utility scripts
|
||||||
├── AGENT_TASKS.md # Task list
|
├── dist/padded-cell/ # Build output
|
||||||
├── README.md # This file (English)
|
├── install.mjs # Installer
|
||||||
└── README.zh-CN.md # Chinese version
|
└── README.md
|
||||||
```
|
```
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Install
|
# Install (default: ~/.openclaw)
|
||||||
node install.mjs --install
|
node install.mjs
|
||||||
|
|
||||||
|
# Install with custom openclaw profile path
|
||||||
|
node install.mjs --openclaw-profile-path /path/to/.openclaw
|
||||||
|
|
||||||
|
# Build only (no install)
|
||||||
|
node install.mjs --build-only
|
||||||
|
|
||||||
# Uninstall
|
# Uninstall
|
||||||
node install.mjs --uninstall
|
node install.mjs --uninstall
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Install paths
|
||||||
|
|
||||||
|
The installer resolves the openclaw base path with this priority:
|
||||||
|
1. `--openclaw-profile-path` CLI argument
|
||||||
|
2. `$OPENCLAW_PATH` environment variable
|
||||||
|
3. `~/.openclaw` (default)
|
||||||
|
|
||||||
|
Binaries go to `$(openclaw path)/bin/`, plugin files to `$(openclaw path)/plugins/padded-cell/`.
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
> PCEXEC + PCGUARD only mitigate light model hallucination / misoperation / prompt forgetting. They do not defend against malicious attacks. For stronger security, use sandbox mode instead of this plugin.
|
|
||||||
|
|
||||||
|
|
||||||
### pass_mgr
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Initialize (required before first use)
|
# Initialize pass_mgr
|
||||||
~/.openclaw/bin/pass_mgr admin init
|
~/.openclaw/bin/pass_mgr admin init
|
||||||
|
|
||||||
# Set password
|
# Set and get passwords
|
||||||
~/.openclaw/bin/pass_mgr set mykey mypassword
|
~/.openclaw/bin/pass_mgr set mykey mypassword
|
||||||
|
|
||||||
# Get password
|
|
||||||
~/.openclaw/bin/pass_mgr get mykey
|
~/.openclaw/bin/pass_mgr get mykey
|
||||||
|
|
||||||
|
# Use pcguard in scripts
|
||||||
|
pcguard || exit 1
|
||||||
```
|
```
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|||||||
626
install.mjs
626
install.mjs
@@ -1,19 +1,18 @@
|
|||||||
#!/usr/bin/env node
|
#!/usr/bin/env node
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* PaddedCell Plugin Installer
|
* PaddedCell Plugin Installer v0.2.0
|
||||||
*
|
*
|
||||||
* Usage:
|
* Usage:
|
||||||
* node install.mjs
|
* node install.mjs
|
||||||
* node install.mjs --prefix /usr/local
|
* node install.mjs --openclaw-profile-path /path/to/.openclaw
|
||||||
* node install.mjs --build-only
|
* node install.mjs --build-only
|
||||||
* node install.mjs --skip-check
|
* node install.mjs --skip-check
|
||||||
* node install.mjs --uninstall
|
* node install.mjs --uninstall
|
||||||
* node install.mjs --uninstall --prefix /usr/local
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { execSync } from 'child_process';
|
import { execSync } from 'child_process';
|
||||||
import { existsSync, mkdirSync, copyFileSync, writeFileSync, chmodSync, readdirSync, statSync } from 'fs';
|
import { existsSync, mkdirSync, copyFileSync, chmodSync, readdirSync, rmSync } from 'fs';
|
||||||
import { dirname, join, resolve } from 'path';
|
import { dirname, join, resolve } from 'path';
|
||||||
import { fileURLToPath } from 'url';
|
import { fileURLToPath } from 'url';
|
||||||
import { homedir, platform } from 'os';
|
import { homedir, platform } from 'os';
|
||||||
@@ -21,534 +20,289 @@ 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));
|
||||||
|
|
||||||
// Plugin configuration - matches directory name in dist/
|
|
||||||
const PLUGIN_NAME = 'padded-cell';
|
const PLUGIN_NAME = 'padded-cell';
|
||||||
const DIST_DIR = join(__dirname, 'dist', PLUGIN_NAME);
|
const SRC_DIST_DIR = join(__dirname, 'dist', PLUGIN_NAME);
|
||||||
|
|
||||||
// Parse arguments
|
// Parse arguments
|
||||||
const args = process.argv.slice(2);
|
const args = process.argv.slice(2);
|
||||||
const options = {
|
const options = {
|
||||||
prefix: null,
|
openclawProfilePath: null,
|
||||||
buildOnly: args.includes('--build-only'),
|
buildOnly: args.includes('--build-only'),
|
||||||
skipCheck: args.includes('--skip-check'),
|
skipCheck: args.includes('--skip-check'),
|
||||||
verbose: args.includes('--verbose') || args.includes('-v'),
|
verbose: args.includes('--verbose') || args.includes('-v'),
|
||||||
uninstall: args.includes('--uninstall'),
|
uninstall: args.includes('--uninstall'),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Parse --prefix value
|
// Parse --openclaw-profile-path value
|
||||||
const prefixIndex = args.indexOf('--prefix');
|
const profileIdx = args.indexOf('--openclaw-profile-path');
|
||||||
if (prefixIndex !== -1 && args[prefixIndex + 1]) {
|
if (profileIdx !== -1 && args[profileIdx + 1]) {
|
||||||
options.prefix = resolve(args[prefixIndex + 1]);
|
options.openclawProfilePath = resolve(args[profileIdx + 1]);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Colors for output
|
// Resolve openclaw path: --openclaw-profile-path → $OPENCLAW_PATH → ~/.openclaw
|
||||||
const colors = {
|
function resolveOpenclawPath() {
|
||||||
reset: '\x1b[0m',
|
if (options.openclawProfilePath) return options.openclawProfilePath;
|
||||||
red: '\x1b[31m',
|
if (process.env.OPENCLAW_PATH) return resolve(process.env.OPENCLAW_PATH);
|
||||||
green: '\x1b[32m',
|
return join(homedir(), '.openclaw');
|
||||||
yellow: '\x1b[33m',
|
}
|
||||||
blue: '\x1b[34m',
|
|
||||||
cyan: '\x1b[36m',
|
// Colors
|
||||||
|
const c = {
|
||||||
|
reset: '\x1b[0m', red: '\x1b[31m', green: '\x1b[32m',
|
||||||
|
yellow: '\x1b[33m', blue: '\x1b[34m', cyan: '\x1b[36m',
|
||||||
};
|
};
|
||||||
|
function log(msg, color = 'reset') { console.log(`${c[color]}${msg}${c.reset}`); }
|
||||||
|
function logStep(n, total, msg) { log(`[${n}/${total}] ${msg}`, 'cyan'); }
|
||||||
|
function logOk(msg) { log(` ✓ ${msg}`, 'green'); }
|
||||||
|
function logWarn(msg) { log(` ⚠ ${msg}`, 'yellow'); }
|
||||||
|
function logErr(msg) { log(` ✗ ${msg}`, 'red'); }
|
||||||
|
|
||||||
function log(message, color = 'reset') {
|
function exec(command, opts = {}) {
|
||||||
console.log(`${colors[color]}${message}${colors.reset}`);
|
return execSync(command, {
|
||||||
}
|
|
||||||
|
|
||||||
function logStep(step, message) {
|
|
||||||
log(`[${step}/6] ${message}`, 'cyan');
|
|
||||||
}
|
|
||||||
|
|
||||||
function logSuccess(message) {
|
|
||||||
log(` ✓ ${message}`, 'green');
|
|
||||||
}
|
|
||||||
|
|
||||||
function logWarning(message) {
|
|
||||||
log(` ⚠ ${message}`, 'yellow');
|
|
||||||
}
|
|
||||||
|
|
||||||
function logError(message) {
|
|
||||||
log(` ✗ ${message}`, 'red');
|
|
||||||
}
|
|
||||||
|
|
||||||
function exec(command, options = {}) {
|
|
||||||
const defaultOptions = {
|
|
||||||
cwd: __dirname,
|
cwd: __dirname,
|
||||||
stdio: options.silent ? 'pipe' : 'inherit',
|
stdio: opts.silent ? 'pipe' : 'inherit',
|
||||||
encoding: 'utf8',
|
encoding: 'utf8',
|
||||||
};
|
...opts,
|
||||||
return execSync(command, { ...defaultOptions, ...options });
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// OpenClaw config helpers
|
function getOpenclawConfig(key, def = undefined) {
|
||||||
function getOpenclawConfig(pathKey, defaultValue = undefined) {
|
|
||||||
try {
|
try {
|
||||||
const out = execSync(`openclaw config get ${pathKey} --json 2>/dev/null || echo "undefined"`, {
|
const out = exec(`openclaw config get ${key} --json 2>/dev/null || echo "undefined"`, { silent: true }).trim();
|
||||||
encoding: 'utf8',
|
if (out === 'undefined' || out === '') return def;
|
||||||
cwd: __dirname
|
|
||||||
}).trim();
|
|
||||||
if (out === 'undefined' || out === '') return defaultValue;
|
|
||||||
return JSON.parse(out);
|
return JSON.parse(out);
|
||||||
} catch {
|
} catch { return def; }
|
||||||
return defaultValue;
|
|
||||||
}
|
}
|
||||||
|
function setOpenclawConfig(key, value) {
|
||||||
|
exec(`openclaw config set ${key} '${JSON.stringify(value)}' --json`, { silent: true });
|
||||||
|
}
|
||||||
|
function unsetOpenclawConfig(key) {
|
||||||
|
try { exec(`openclaw config unset ${key}`, { silent: true }); } catch {}
|
||||||
}
|
}
|
||||||
|
|
||||||
function setOpenclawConfig(pathKey, value) {
|
|
||||||
const cmd = `openclaw config set ${pathKey} '${JSON.stringify(value)}' --json`;
|
|
||||||
execSync(cmd, { cwd: __dirname, encoding: 'utf8' });
|
|
||||||
}
|
|
||||||
|
|
||||||
function unsetOpenclawConfig(pathKey) {
|
|
||||||
try {
|
|
||||||
execSync(`openclaw config unset ${pathKey}`, { cwd: __dirname, encoding: 'utf8' });
|
|
||||||
} catch {
|
|
||||||
// Ignore errors
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Copy directory recursively
|
|
||||||
function copyDir(src, dest) {
|
function copyDir(src, dest) {
|
||||||
mkdirSync(dest, { recursive: true });
|
mkdirSync(dest, { recursive: true });
|
||||||
const entries = readdirSync(src, { withFileTypes: true });
|
for (const entry of readdirSync(src, { withFileTypes: true })) {
|
||||||
|
const s = join(src, entry.name);
|
||||||
for (const entry of entries) {
|
const d = join(dest, entry.name);
|
||||||
const srcPath = join(src, entry.name);
|
if (entry.name === 'node_modules') continue; // skip node_modules
|
||||||
const destPath = join(dest, entry.name);
|
entry.isDirectory() ? copyDir(s, d) : copyFileSync(s, d);
|
||||||
|
|
||||||
if (entry.isDirectory()) {
|
|
||||||
copyDir(srcPath, destPath);
|
|
||||||
} else {
|
|
||||||
copyFileSync(srcPath, destPath);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============================================================================
|
// ── Step 1: Detect ──────────────────────────────────────────────────────
|
||||||
// Step 1: Environment Detection
|
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
function detectEnvironment() {
|
function detectEnvironment() {
|
||||||
logStep(1, 'Detecting environment...');
|
logStep(1, 6, 'Detecting environment...');
|
||||||
|
const env = { platform: platform(), nodeVersion: null, goVersion: null };
|
||||||
|
|
||||||
const env = {
|
try { env.nodeVersion = exec('node --version', { silent: true }).trim(); logOk(`Node.js ${env.nodeVersion}`); } catch { logErr('Node.js not found'); }
|
||||||
platform: platform(),
|
try { env.goVersion = exec('go version', { silent: true }).trim(); logOk(`Go: ${env.goVersion}`); } catch { logErr('Go not found'); }
|
||||||
nodeVersion: null,
|
try { logOk(`openclaw at ${exec('which openclaw', { silent: true }).trim()}`); } catch { logWarn('openclaw CLI not in PATH'); }
|
||||||
goVersion: null,
|
|
||||||
openclawDir: join(homedir(), '.openclaw'),
|
|
||||||
};
|
|
||||||
|
|
||||||
// Check Node.js
|
|
||||||
try {
|
|
||||||
env.nodeVersion = exec('node --version', { silent: true }).trim();
|
|
||||||
logSuccess(`Node.js ${env.nodeVersion}`);
|
|
||||||
} catch {
|
|
||||||
logError('Node.js not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check Go
|
|
||||||
try {
|
|
||||||
env.goVersion = exec('go version', { silent: true }).trim();
|
|
||||||
logSuccess(`Go ${env.goVersion}`);
|
|
||||||
} catch {
|
|
||||||
logError('Go not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check openclaw
|
|
||||||
try {
|
|
||||||
const path = exec('which openclaw', { silent: true }).trim();
|
|
||||||
logSuccess(`openclaw at ${path}`);
|
|
||||||
|
|
||||||
// Try to find openclaw config dir
|
|
||||||
const home = homedir();
|
|
||||||
const possibleDirs = [
|
|
||||||
join(home, '.openclaw'),
|
|
||||||
join(home, '.config', 'openclaw'),
|
|
||||||
];
|
|
||||||
|
|
||||||
for (const dir of possibleDirs) {
|
|
||||||
if (existsSync(dir)) {
|
|
||||||
env.openclawDir = dir;
|
|
||||||
logSuccess(`openclaw config dir: ${dir}`);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
logWarning('openclaw CLI not found in PATH');
|
|
||||||
}
|
|
||||||
|
|
||||||
return env;
|
return env;
|
||||||
}
|
}
|
||||||
|
|
||||||
function checkDependencies(env) {
|
// ── Step 2: Check deps ──────────────────────────────────────────────────
|
||||||
if (options.skipCheck) {
|
|
||||||
logWarning('Skipping dependency checks');
|
function checkDeps(env) {
|
||||||
return true;
|
if (options.skipCheck) { logStep(2, 6, 'Skipping dep checks'); return; }
|
||||||
|
logStep(2, 6, 'Checking dependencies...');
|
||||||
|
let fail = false;
|
||||||
|
if (!env.nodeVersion || parseInt(env.nodeVersion.slice(1)) < 18) { logErr('Node.js 18+ required'); fail = true; }
|
||||||
|
if (!env.goVersion) { logErr('Go 1.22+ required'); fail = true; }
|
||||||
|
if (fail) { log('\nInstall missing deps and retry.', 'red'); process.exit(1); }
|
||||||
|
logOk('All deps OK');
|
||||||
}
|
}
|
||||||
|
|
||||||
logStep(2, 'Checking dependencies...');
|
// ── Step 3: Build ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
let hasErrors = false;
|
async function build() {
|
||||||
|
logStep(3, 6, 'Building components...');
|
||||||
|
|
||||||
if (!env.nodeVersion) {
|
// pass_mgr (Go)
|
||||||
logError('Node.js is required. Please install Node.js 18+');
|
log(' Building pass_mgr...', 'blue');
|
||||||
hasErrors = true;
|
const pmDir = join(__dirname, 'pass_mgr');
|
||||||
} else {
|
exec('go mod tidy', { cwd: pmDir, silent: !options.verbose });
|
||||||
const majorVersion = parseInt(env.nodeVersion.slice(1).split('.')[0]);
|
exec('go build -o dist/pass_mgr src/main.go', { cwd: pmDir, silent: !options.verbose });
|
||||||
if (majorVersion < 18) {
|
chmodSync(join(pmDir, 'dist', 'pass_mgr'), 0o755);
|
||||||
logError(`Node.js 18+ required, found ${env.nodeVersion}`);
|
logOk('pass_mgr');
|
||||||
hasErrors = true;
|
|
||||||
} else {
|
// pcguard (Go)
|
||||||
logSuccess(`Node.js version OK`);
|
log(' Building pcguard...', 'blue');
|
||||||
}
|
const pgDir = join(__dirname, 'pcguard');
|
||||||
|
exec('go mod tidy', { cwd: pgDir, silent: !options.verbose });
|
||||||
|
exec('go build -o dist/pcguard src/main.go', { cwd: pgDir, silent: !options.verbose });
|
||||||
|
chmodSync(join(pgDir, 'dist', 'pcguard'), 0o755);
|
||||||
|
logOk('pcguard');
|
||||||
|
|
||||||
|
// Plugin (TypeScript)
|
||||||
|
log(' Building plugin...', 'blue');
|
||||||
|
const pluginDir = join(__dirname, 'plugin');
|
||||||
|
exec('npm install', { cwd: pluginDir, silent: !options.verbose });
|
||||||
|
exec('npx tsc', { cwd: pluginDir, silent: !options.verbose });
|
||||||
|
logOk('plugin');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!env.goVersion) {
|
// ── Step 4: Install ─────────────────────────────────────────────────────
|
||||||
logError('Go is required. Please install Go 1.22+');
|
|
||||||
hasErrors = true;
|
|
||||||
} else {
|
|
||||||
logSuccess(`Go version OK`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (hasErrors) {
|
async function install() {
|
||||||
log('\nPlease install missing dependencies and try again.', 'red');
|
if (options.buildOnly) { logStep(4, 6, 'Skipping install (--build-only)'); return null; }
|
||||||
process.exit(1);
|
logStep(4, 6, 'Installing...');
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
const openclawPath = resolveOpenclawPath();
|
||||||
}
|
const binDir = join(openclawPath, 'bin');
|
||||||
|
const pluginsDir = join(openclawPath, 'plugins');
|
||||||
|
const destDir = join(pluginsDir, PLUGIN_NAME);
|
||||||
|
|
||||||
// ============================================================================
|
log(` OpenClaw path: ${openclawPath}`, 'blue');
|
||||||
// Step 3: Build Components
|
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
async function buildComponents(env) {
|
// Copy dist/padded-cell → plugins/padded-cell
|
||||||
logStep(3, 'Building components...');
|
if (existsSync(destDir)) rmSync(destDir, { recursive: true, force: true });
|
||||||
|
copyDir(SRC_DIST_DIR, destDir);
|
||||||
|
|
||||||
// Build pass_mgr
|
// Copy openclaw.plugin.json
|
||||||
log(' Building pass_mgr (Go)...', 'blue');
|
copyFileSync(join(__dirname, 'plugin', 'openclaw.plugin.json'), join(destDir, 'openclaw.plugin.json'));
|
||||||
try {
|
logOk(`Plugin files → ${destDir}`);
|
||||||
const passMgrDir = join(__dirname, 'pass_mgr');
|
|
||||||
exec('go mod tidy', { cwd: passMgrDir, silent: !options.verbose });
|
|
||||||
exec('go build -o dist/pass_mgr src/main.go', { cwd: passMgrDir, silent: !options.verbose });
|
|
||||||
|
|
||||||
const binaryPath = join(passMgrDir, 'dist', 'pass_mgr');
|
// Install runtime deps into dest (express, ws)
|
||||||
if (!existsSync(binaryPath)) {
|
exec('npm install --omit=dev', { cwd: destDir, silent: !options.verbose });
|
||||||
throw new Error('pass_mgr binary not found after build');
|
logOk('Runtime deps installed');
|
||||||
}
|
|
||||||
chmodSync(binaryPath, 0o755);
|
|
||||||
logSuccess('pass_mgr built successfully');
|
|
||||||
} catch (err) {
|
|
||||||
logError(`Failed to build pass_mgr: ${err.message}`);
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Build pcexec
|
// Binaries
|
||||||
log(' Building pcexec (TypeScript)...', 'blue');
|
|
||||||
try {
|
|
||||||
const pcexecDir = join(__dirname, 'pcexec');
|
|
||||||
exec('npm install', { cwd: pcexecDir, silent: !options.verbose });
|
|
||||||
exec('npm run build', { cwd: pcexecDir, silent: !options.verbose });
|
|
||||||
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');
|
|
||||||
exec('npm install', { cwd: safeRestartDir, silent: !options.verbose });
|
|
||||||
exec('npm run build', { cwd: safeRestartDir, silent: !options.verbose });
|
|
||||||
logSuccess('safe-restart built successfully');
|
|
||||||
} catch (err) {
|
|
||||||
logError(`Failed to build safe-restart: ${err.message}`);
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ============================================================================
|
|
||||||
// Step 4: Install Components
|
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
async function installComponents(env) {
|
|
||||||
if (options.buildOnly) {
|
|
||||||
logStep(4, 'Skipping installation (--build-only)');
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
logStep(4, 'Installing components...');
|
|
||||||
|
|
||||||
const installDir = options.prefix || env.openclawDir;
|
|
||||||
const binDir = join(installDir, 'bin');
|
|
||||||
|
|
||||||
log(` Install directory: ${installDir}`, 'blue');
|
|
||||||
log(` Binary directory: ${binDir}`, 'blue');
|
|
||||||
log(` Dist directory: ${DIST_DIR}`, 'blue');
|
|
||||||
|
|
||||||
// Create dist/padded-cell directory and copy plugin files
|
|
||||||
log(' Copying plugin files to dist/padded-cell...', 'blue');
|
|
||||||
mkdirSync(DIST_DIR, { recursive: true });
|
|
||||||
|
|
||||||
// Copy pcexec
|
|
||||||
copyDir(join(__dirname, 'pcexec'), join(DIST_DIR, 'pcexec'));
|
|
||||||
logSuccess('Copied pcexec to dist/padded-cell/');
|
|
||||||
|
|
||||||
// Copy safe-restart
|
|
||||||
copyDir(join(__dirname, 'safe-restart'), join(DIST_DIR, 'safe-restart'));
|
|
||||||
logSuccess('Copied safe-restart to dist/padded-cell/');
|
|
||||||
|
|
||||||
// Create root index.js entry point (copy from source)
|
|
||||||
copyFileSync(join(__dirname, 'index.js'), join(DIST_DIR, 'index.js'));
|
|
||||||
logSuccess('Copied index.js entry point');
|
|
||||||
|
|
||||||
// Copy openclaw.plugin.json from source
|
|
||||||
copyFileSync(join(__dirname, 'openclaw.plugin.json'), join(DIST_DIR, 'openclaw.plugin.json'));
|
|
||||||
logSuccess('Copied openclaw.plugin.json');
|
|
||||||
|
|
||||||
// Create bin directory and install pass_mgr binary
|
|
||||||
mkdirSync(binDir, { recursive: true });
|
mkdirSync(binDir, { recursive: true });
|
||||||
|
const bins = [
|
||||||
log(' Installing pass_mgr binary...', 'blue');
|
{ name: 'pass_mgr', src: join(__dirname, 'pass_mgr', 'dist', 'pass_mgr') },
|
||||||
const passMgrSource = join(__dirname, 'pass_mgr', 'dist', 'pass_mgr');
|
{ name: 'pcguard', src: join(__dirname, 'pcguard', 'dist', 'pcguard') },
|
||||||
const passMgrDest = join(binDir, 'pass_mgr');
|
];
|
||||||
copyFileSync(passMgrSource, passMgrDest);
|
for (const b of bins) {
|
||||||
chmodSync(passMgrDest, 0o755);
|
const dest = join(binDir, b.name);
|
||||||
logSuccess(`pass_mgr installed to ${passMgrDest}`);
|
copyFileSync(b.src, dest);
|
||||||
|
chmodSync(dest, 0o755);
|
||||||
return { passMgrPath: passMgrDest };
|
logOk(`${b.name} → ${dest}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============================================================================
|
return { binDir, destDir };
|
||||||
// Step 5: Configuration
|
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
async function configure(env) {
|
|
||||||
if (options.buildOnly) {
|
|
||||||
logStep(5, 'Skipping configuration (--build-only)');
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
logStep(5, 'Configuration...');
|
// ── Step 5: Configure ───────────────────────────────────────────────────
|
||||||
|
|
||||||
const installDir = options.prefix || env.openclawDir;
|
async function configure() {
|
||||||
const passMgrPath = join(installDir, 'bin', 'pass_mgr');
|
if (options.buildOnly) { logStep(5, 6, 'Skipping config'); return; }
|
||||||
|
logStep(5, 6, 'Configuring OpenClaw...');
|
||||||
|
|
||||||
// Check if already initialized
|
const openclawPath = resolveOpenclawPath();
|
||||||
const adminKeyDir = join(homedir(), '.pass_mgr');
|
const destDir = join(openclawPath, 'plugins', PLUGIN_NAME);
|
||||||
const configPath = join(adminKeyDir, 'config.json');
|
const passMgrPath = join(openclawPath, 'bin', 'pass_mgr');
|
||||||
|
|
||||||
if (existsSync(configPath)) {
|
|
||||||
logSuccess('pass_mgr already initialized');
|
|
||||||
} else {
|
|
||||||
log(' pass_mgr not initialized yet.', 'yellow');
|
|
||||||
log(` Run "${passMgrPath} admin init" manually after installation.`, 'cyan');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Configure OpenClaw
|
|
||||||
log('\n Configuring OpenClaw plugin...', 'blue');
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 1. Add plugin path to plugins.load.paths FIRST (required for validation)
|
// plugins.load.paths
|
||||||
const currentPaths = getOpenclawConfig('plugins.load.paths', []);
|
const paths = getOpenclawConfig('plugins.load.paths', []);
|
||||||
log(` Current paths: ${JSON.stringify(currentPaths)}`, 'blue');
|
if (!paths.includes(destDir)) { paths.push(destDir); setOpenclawConfig('plugins.load.paths', paths); }
|
||||||
log(` DIST_DIR: ${DIST_DIR}`, 'blue');
|
logOk(`plugins.load.paths includes ${destDir}`);
|
||||||
if (!currentPaths.includes(DIST_DIR)) {
|
|
||||||
currentPaths.push(DIST_DIR);
|
|
||||||
log(` Adding plugin path...`, 'blue');
|
|
||||||
try {
|
|
||||||
setOpenclawConfig('plugins.load.paths', currentPaths);
|
|
||||||
logSuccess(`Added ${DIST_DIR} to plugins.load.paths`);
|
|
||||||
} catch (err) {
|
|
||||||
logError(`Failed to set paths: ${err.message}`);
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
log(' Plugin path already in plugins.load.paths', 'green');
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. Add to plugins.allow (after path is set)
|
// plugins.allow
|
||||||
const allowList = getOpenclawConfig('plugins.allow', []);
|
const allow = getOpenclawConfig('plugins.allow', []);
|
||||||
if (!allowList.includes(PLUGIN_NAME)) {
|
if (!allow.includes(PLUGIN_NAME)) { allow.push(PLUGIN_NAME); setOpenclawConfig('plugins.allow', allow); }
|
||||||
allowList.push(PLUGIN_NAME);
|
logOk(`plugins.allow includes ${PLUGIN_NAME}`);
|
||||||
setOpenclawConfig('plugins.allow', allowList);
|
|
||||||
logSuccess(`Added '${PLUGIN_NAME}' to plugins.allow`);
|
|
||||||
} else {
|
|
||||||
log(' Already in plugins.allow', 'green');
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. Add plugin entry
|
// plugins.entries
|
||||||
const plugins = getOpenclawConfig('plugins', {});
|
const plugins = getOpenclawConfig('plugins', {});
|
||||||
plugins.entries = plugins.entries || {};
|
plugins.entries = plugins.entries || {};
|
||||||
plugins.entries[PLUGIN_NAME] = {
|
plugins.entries[PLUGIN_NAME] = {
|
||||||
enabled: true,
|
enabled: true,
|
||||||
config: {
|
config: { enabled: true, passMgrPath, openclawProfilePath: openclawPath },
|
||||||
enabled: true,
|
|
||||||
passMgrPath: passMgrPath,
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
setOpenclawConfig('plugins', plugins);
|
setOpenclawConfig('plugins', plugins);
|
||||||
logSuccess(`Configured ${PLUGIN_NAME} plugin entry`);
|
logOk('Plugin entry configured');
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logWarning(`Failed to configure OpenClaw: ${err.message}`);
|
logWarn(`Config failed: ${err.message}`);
|
||||||
log(' Please manually configure:', 'yellow');
|
}
|
||||||
log(` openclaw config set plugins.allow --json '[..., "${PLUGIN_NAME}"]'`, 'cyan');
|
|
||||||
log(` openclaw config set plugins.load.paths --json '[..., "${DIST_DIR}"]'`, 'cyan');
|
// Check pass_mgr init
|
||||||
|
if (existsSync(join(homedir(), '.pass_mgr', 'config.json'))) {
|
||||||
|
logOk('pass_mgr already initialized');
|
||||||
|
} else {
|
||||||
|
logWarn(`pass_mgr not initialized — run: ${passMgrPath} admin init`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============================================================================
|
// ── Step 6: Summary ─────────────────────────────────────────────────────
|
||||||
// Step 6: Print Summary
|
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
function printSummary(env, passMgrPath) {
|
|
||||||
logStep(6, 'Installation Summary');
|
|
||||||
|
|
||||||
|
function summary(result) {
|
||||||
|
logStep(6, 6, 'Done!');
|
||||||
console.log('');
|
console.log('');
|
||||||
log('╔════════════════════════════════════════════════════════╗', 'cyan');
|
log('╔══════════════════════════════════════════════╗', 'cyan');
|
||||||
log('║ PaddedCell Installation Complete ║', 'cyan');
|
log('║ PaddedCell v0.2.0 Install Complete ║', 'cyan');
|
||||||
log('╚════════════════════════════════════════════════════════╝', 'cyan');
|
log('╚══════════════════════════════════════════════╝', 'cyan');
|
||||||
console.log('');
|
|
||||||
|
|
||||||
if (options.buildOnly) {
|
if (options.buildOnly) {
|
||||||
log('Build-only mode - binaries built but not installed', 'yellow');
|
log('\nBuild-only — binaries not installed.', 'yellow');
|
||||||
console.log('');
|
return;
|
||||||
log('Built artifacts:', 'blue');
|
}
|
||||||
log(` • pass_mgr: ${join(__dirname, 'pass_mgr', 'dist', 'pass_mgr')}`, 'reset');
|
|
||||||
log(` • pcexec: ${join(__dirname, 'pcexec', 'dist')}`, 'reset');
|
|
||||||
log(` • safe-restart: ${join(__dirname, 'safe-restart', 'dist')}`, 'reset');
|
|
||||||
} else {
|
|
||||||
log('Installed components:', 'blue');
|
|
||||||
log(` • pass_mgr binary: ${passMgrPath}`, 'reset');
|
|
||||||
log(` • Plugin files: ${DIST_DIR}`, 'reset');
|
|
||||||
console.log('');
|
|
||||||
|
|
||||||
|
console.log('');
|
||||||
log('Next steps:', 'blue');
|
log('Next steps:', 'blue');
|
||||||
console.log('');
|
log(' 1. openclaw gateway restart', 'cyan');
|
||||||
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:', 'yellow');
|
|
||||||
log(' openclaw gateway restart', 'cyan');
|
|
||||||
}
|
|
||||||
|
|
||||||
|
const openclawPath = resolveOpenclawPath();
|
||||||
|
const pmPath = join(openclawPath, 'bin', 'pass_mgr');
|
||||||
|
if (!existsSync(join(homedir(), '.pass_mgr', 'config.json'))) {
|
||||||
|
log(` 2. ${pmPath} admin init`, 'cyan');
|
||||||
|
}
|
||||||
console.log('');
|
console.log('');
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============================================================================
|
// ── Uninstall ───────────────────────────────────────────────────────────
|
||||||
// Uninstall
|
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
async function uninstall(env) {
|
async function uninstall() {
|
||||||
logStep(1, 'Uninstalling PaddedCell...');
|
log('Uninstalling PaddedCell...', 'cyan');
|
||||||
|
const openclawPath = resolveOpenclawPath();
|
||||||
|
|
||||||
const installDir = options.prefix || env.openclawDir || join(homedir(), '.openclaw');
|
// Remove binaries
|
||||||
const passMgrBinary = join(installDir, 'bin', 'pass_mgr');
|
for (const name of ['pass_mgr', 'pcguard']) {
|
||||||
|
const p = join(openclawPath, 'bin', name);
|
||||||
|
if (existsSync(p)) { rmSync(p); logOk(`Removed ${p}`); }
|
||||||
|
}
|
||||||
|
|
||||||
// Remove pass_mgr binary
|
// Remove plugin dir
|
||||||
if (existsSync(passMgrBinary)) {
|
const destDir = join(openclawPath, 'plugins', PLUGIN_NAME);
|
||||||
|
if (existsSync(destDir)) { rmSync(destDir, { recursive: true }); logOk(`Removed ${destDir}`); }
|
||||||
|
|
||||||
|
// Remove config
|
||||||
try {
|
try {
|
||||||
execSync(`rm -f "${passMgrBinary}"`, { silent: true });
|
const allow = getOpenclawConfig('plugins.allow', []);
|
||||||
logSuccess(`Removed ${passMgrBinary}`);
|
const idx = allow.indexOf(PLUGIN_NAME);
|
||||||
} catch (err) {
|
if (idx !== -1) { allow.splice(idx, 1); setOpenclawConfig('plugins.allow', allow); logOk('Removed from allow list'); }
|
||||||
logError(`Failed to remove ${passMgrBinary}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Remove dist/padded-cell directory
|
|
||||||
if (existsSync(DIST_DIR)) {
|
|
||||||
try {
|
|
||||||
execSync(`rm -rf "${DIST_DIR}"`, { silent: true });
|
|
||||||
logSuccess(`Removed ${DIST_DIR}`);
|
|
||||||
} catch (err) {
|
|
||||||
logError(`Failed to remove ${DIST_DIR}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Remove OpenClaw configuration
|
|
||||||
log('\n Removing OpenClaw configuration...', 'blue');
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Remove from plugins.allow
|
|
||||||
const allowList = getOpenclawConfig('plugins.allow', []);
|
|
||||||
const idx = allowList.indexOf(PLUGIN_NAME);
|
|
||||||
if (idx !== -1) {
|
|
||||||
allowList.splice(idx, 1);
|
|
||||||
setOpenclawConfig('plugins.allow', allowList);
|
|
||||||
logSuccess(`Removed '${PLUGIN_NAME}' from plugins.allow`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Remove plugin entry
|
|
||||||
unsetOpenclawConfig(`plugins.entries.${PLUGIN_NAME}`);
|
unsetOpenclawConfig(`plugins.entries.${PLUGIN_NAME}`);
|
||||||
logSuccess(`Removed ${PLUGIN_NAME} plugin entry`);
|
logOk('Removed plugin entry');
|
||||||
|
const paths = getOpenclawConfig('plugins.load.paths', []);
|
||||||
|
const pidx = paths.indexOf(destDir);
|
||||||
|
if (pidx !== -1) { paths.splice(pidx, 1); setOpenclawConfig('plugins.load.paths', paths); logOk('Removed from load paths'); }
|
||||||
|
} catch (err) { logWarn(`Config cleanup: ${err.message}`); }
|
||||||
|
|
||||||
// Remove from plugins.load.paths
|
log('\nRun: openclaw gateway restart', 'yellow');
|
||||||
const currentPaths = getOpenclawConfig('plugins.load.paths', []);
|
|
||||||
const pathIdx = currentPaths.indexOf(DIST_DIR);
|
|
||||||
if (pathIdx !== -1) {
|
|
||||||
currentPaths.splice(pathIdx, 1);
|
|
||||||
setOpenclawConfig('plugins.load.paths', currentPaths);
|
|
||||||
logSuccess(`Removed plugin path from plugins.load.paths`);
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
logWarning(`Failed to update OpenClaw config: ${err.message}`);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check for admin key directory
|
// ── Main ────────────────────────────────────────────────────────────────
|
||||||
const adminKeyDir = join(homedir(), '.pass_mgr');
|
|
||||||
if (existsSync(adminKeyDir)) {
|
|
||||||
log('\n⚠️ Admin key directory found:', 'yellow');
|
|
||||||
log(` ${adminKeyDir}`, 'cyan');
|
|
||||||
log(' This contains your encryption keys. Remove manually if desired.', 'yellow');
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('');
|
|
||||||
log('╔════════════════════════════════════════════════════════╗', 'cyan');
|
|
||||||
log('║ PaddedCell Uninstall Complete ║', 'cyan');
|
|
||||||
log('╚════════════════════════════════════════════════════════╝', 'cyan');
|
|
||||||
console.log('');
|
|
||||||
log('Restart OpenClaw gateway:', 'yellow');
|
|
||||||
log(' openclaw gateway restart', 'cyan');
|
|
||||||
}
|
|
||||||
|
|
||||||
// ============================================================================
|
|
||||||
// Main
|
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
async function main() {
|
async function main() {
|
||||||
console.log('');
|
console.log('');
|
||||||
log('╔════════════════════════════════════════════════════════╗', 'cyan');
|
log('╔══════════════════════════════════════════════╗', 'cyan');
|
||||||
log('║ PaddedCell Plugin Installer v0.1.0 ║', 'cyan');
|
log('║ PaddedCell Plugin Installer v0.2.0 ║', 'cyan');
|
||||||
log('╚════════════════════════════════════════════════════════╝', 'cyan');
|
log('╚══════════════════════════════════════════════╝', 'cyan');
|
||||||
console.log('');
|
console.log('');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const env = detectEnvironment();
|
const env = detectEnvironment();
|
||||||
|
if (options.uninstall) { await uninstall(); process.exit(0); }
|
||||||
// Handle uninstall
|
checkDeps(env);
|
||||||
if (options.uninstall) {
|
await build();
|
||||||
await uninstall(env);
|
const result = await install();
|
||||||
process.exit(0);
|
await configure();
|
||||||
}
|
summary(result);
|
||||||
|
|
||||||
checkDependencies(env);
|
|
||||||
await buildComponents(env);
|
|
||||||
const result = await installComponents(env);
|
|
||||||
await configure(env);
|
|
||||||
printSummary(env, result?.passMgrPath);
|
|
||||||
process.exit(0);
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log('');
|
log(`\nInstallation failed: ${err.message}`, 'red');
|
||||||
log('╔════════════════════════════════════════════════════════╗', 'red');
|
|
||||||
log('║ Installation Failed ║', 'red');
|
|
||||||
log('╚════════════════════════════════════════════════════════╝', 'red');
|
|
||||||
console.log('');
|
|
||||||
log(`Error: ${err.message}`, 'red');
|
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
3846
pcexec/package-lock.json
generated
3846
pcexec/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,21 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "pcexec",
|
|
||||||
"version": "0.1.0",
|
|
||||||
"description": "Safe exec wrapper for OpenClaw with password sanitization",
|
|
||||||
"main": "dist/index.js",
|
|
||||||
"types": "dist/index.d.ts",
|
|
||||||
"scripts": {
|
|
||||||
"build": "tsc",
|
|
||||||
"dev": "tsc --watch",
|
|
||||||
"test": "jest"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"@types/node": "^20.0.0"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"typescript": "^5.0.0",
|
|
||||||
"jest": "^29.0.0",
|
|
||||||
"@types/jest": "^29.0.0",
|
|
||||||
"ts-jest": "^29.0.0"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
3
pcguard/go.mod
Normal file
3
pcguard/go.mod
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
module pcguard
|
||||||
|
|
||||||
|
go 1.24.0
|
||||||
36
pcguard/src/main.go
Normal file
36
pcguard/src/main.go
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
// Must match the sentinel value injected by pcexec
|
||||||
|
expectedAgentVerify = "IF YOU ARE AN AGENT/MODEL, YOU SHOULD NEVER TOUCH THIS ENV VARIABLE"
|
||||||
|
errorMessage = "PLEASE USE TOOL PCEXEC TO RUN THIS SCRIPT"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
agentVerify := os.Getenv("AGENT_VERIFY")
|
||||||
|
agentID := os.Getenv("AGENT_ID")
|
||||||
|
agentWorkspace := os.Getenv("AGENT_WORKSPACE")
|
||||||
|
|
||||||
|
if agentVerify != expectedAgentVerify {
|
||||||
|
fmt.Fprintln(os.Stderr, errorMessage)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
if agentID == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, errorMessage)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
if agentWorkspace == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, errorMessage)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// All checks passed — output nothing, exit 0
|
||||||
|
os.Exit(0)
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { StatusManager } from './status-manager';
|
import { StatusManager } from '../core/status-manager';
|
||||||
|
|
||||||
export interface SlashCommandOptions {
|
export interface SlashCommandOptions {
|
||||||
statusManager: StatusManager;
|
statusManager: StatusManager;
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
export { StatusManager, type AgentStatus, type GlobalStatus, type AgentState } from './status-manager';
|
export { StatusManager, type AgentStatus, type GlobalStatus, type AgentState } from './status-manager';
|
||||||
export { createApiServer, startApiServer } from './api';
|
export { createApiServer, startApiServer } from './api';
|
||||||
export { safeRestart, createSafeRestartTool, type SafeRestartOptions, type SafeRestartResult } from './safe-restart';
|
export { safeRestart, createSafeRestartTool, type SafeRestartOptions, type SafeRestartResult } from './safe-restart';
|
||||||
export { SlashCommandHandler, type SlashCommandOptions } from './slash-commands';
|
export { SlashCommandHandler, type SlashCommandOptions } from '../commands/slash-commands';
|
||||||
1
plugin/hooks/.gitkeep
Normal file
1
plugin/hooks/.gitkeep
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# placeholder
|
||||||
@@ -1,25 +1,41 @@
|
|||||||
// PaddedCell Plugin for OpenClaw
|
// PaddedCell Plugin for OpenClaw
|
||||||
// Registers pcexec and safe_restart tools
|
// Registers pcexec and safe_restart tools
|
||||||
|
|
||||||
const { pcexec, pcexecSync } = require('./pcexec/dist/index.js');
|
import { pcexec, pcexecSync } from './tools/pcexec';
|
||||||
const {
|
import {
|
||||||
safeRestart,
|
safeRestart,
|
||||||
createSafeRestartTool,
|
createSafeRestartTool,
|
||||||
StatusManager,
|
StatusManager,
|
||||||
createApiServer,
|
createApiServer,
|
||||||
startApiServer,
|
startApiServer,
|
||||||
SlashCommandHandler
|
} from './core/index';
|
||||||
} = require('./safe-restart/dist/index.js');
|
import { SlashCommandHandler } from './commands/slash-commands';
|
||||||
|
|
||||||
|
/** Sentinel value injected into every pcexec subprocess */
|
||||||
|
const AGENT_VERIFY = 'IF YOU ARE AN AGENT/MODEL, YOU SHOULD NEVER TOUCH THIS ENV VARIABLE';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve the openclaw base path.
|
||||||
|
* Priority: explicit config → $OPENCLAW_PATH → ~/.openclaw
|
||||||
|
*/
|
||||||
|
function resolveOpenclawPath(config?: { openclawProfilePath?: string }): string {
|
||||||
|
if (config?.openclawProfilePath) return config.openclawProfilePath;
|
||||||
|
if (process.env.OPENCLAW_PATH) return process.env.OPENCLAW_PATH;
|
||||||
|
const home = process.env.HOME || require('os').homedir();
|
||||||
|
return require('path').join(home, '.openclaw');
|
||||||
|
}
|
||||||
|
|
||||||
// Plugin registration function
|
// Plugin registration function
|
||||||
function register(api, config) {
|
function register(api: any, config?: any) {
|
||||||
const logger = api.logger || { info: console.log, error: console.error };
|
const logger = api.logger || { info: console.log, error: console.error };
|
||||||
|
|
||||||
logger.info('PaddedCell plugin initializing...');
|
logger.info('PaddedCell plugin initializing...');
|
||||||
|
|
||||||
// Register pcexec tool - pass a FACTORY function that receives context
|
const openclawPath = resolveOpenclawPath(config);
|
||||||
api.registerTool((ctx) => {
|
const binDir = require('path').join(openclawPath, 'bin');
|
||||||
console.log(`[PaddedCell] pcexec factory called with ctx:`, JSON.stringify(ctx, null, 2));
|
|
||||||
|
// Register pcexec tool — pass a FACTORY function that receives context
|
||||||
|
api.registerTool((ctx: any) => {
|
||||||
const agentId = ctx.agentId;
|
const agentId = ctx.agentId;
|
||||||
const workspaceDir = ctx.workspaceDir;
|
const workspaceDir = ctx.workspaceDir;
|
||||||
|
|
||||||
@@ -35,20 +51,29 @@ function register(api, config) {
|
|||||||
},
|
},
|
||||||
required: ['command'],
|
required: ['command'],
|
||||||
},
|
},
|
||||||
async execute(_id, params) {
|
async execute(_id: string, params: any) {
|
||||||
const command = params.command;
|
const command = params.command;
|
||||||
if (!command) {
|
if (!command) {
|
||||||
throw new Error('Missing required parameter: command');
|
throw new Error('Missing required parameter: command');
|
||||||
}
|
}
|
||||||
console.log(`[PaddedCell] pcexec execute: agentId=${agentId}, workspaceDir=${workspaceDir}`);
|
|
||||||
|
// Build PATH with openclaw bin dir appended
|
||||||
|
const currentPath = process.env.PATH || '';
|
||||||
|
const newPath = currentPath.includes(binDir)
|
||||||
|
? currentPath
|
||||||
|
: `${currentPath}:${binDir}`;
|
||||||
|
|
||||||
const result = await pcexec(command, {
|
const result = await pcexec(command, {
|
||||||
cwd: params.cwd || workspaceDir,
|
cwd: params.cwd || workspaceDir,
|
||||||
timeout: params.timeout,
|
timeout: params.timeout,
|
||||||
env: {
|
env: {
|
||||||
AGENT_ID: agentId || '',
|
AGENT_ID: agentId || '',
|
||||||
AGENT_WORKSPACE: workspaceDir || '',
|
AGENT_WORKSPACE: workspaceDir || '',
|
||||||
|
AGENT_VERIFY,
|
||||||
|
PATH: newPath,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// Format output for OpenClaw tool response
|
// Format output for OpenClaw tool response
|
||||||
let output = result.stdout;
|
let output = result.stdout;
|
||||||
if (result.stderr) {
|
if (result.stderr) {
|
||||||
@@ -59,8 +84,8 @@ function register(api, config) {
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
// Register safe_restart tool - pass a FACTORY function that receives context
|
// Register safe_restart tool
|
||||||
api.registerTool((ctx) => {
|
api.registerTool((ctx: any) => {
|
||||||
const agentId = ctx.agentId;
|
const agentId = ctx.agentId;
|
||||||
const sessionKey = ctx.sessionKey;
|
const sessionKey = ctx.sessionKey;
|
||||||
|
|
||||||
@@ -74,10 +99,10 @@ function register(api, config) {
|
|||||||
log: { type: 'string', description: 'Log file path' },
|
log: { type: 'string', description: 'Log file path' },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
async execute(_id, params) {
|
async execute(_id: string, params: any) {
|
||||||
return await safeRestart({
|
return await safeRestart({
|
||||||
agentId: agentId,
|
agentId,
|
||||||
sessionKey: sessionKey,
|
sessionKey,
|
||||||
rollback: params.rollback,
|
rollback: params.rollback,
|
||||||
log: params.log,
|
log: params.log,
|
||||||
});
|
});
|
||||||
@@ -88,7 +113,7 @@ function register(api, config) {
|
|||||||
logger.info('PaddedCell plugin initialized');
|
logger.info('PaddedCell plugin initialized');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Export for OpenClaw
|
// CommonJS export for OpenClaw
|
||||||
module.exports = { register };
|
module.exports = { register };
|
||||||
|
|
||||||
// Also export individual modules for direct use
|
// Also export individual modules for direct use
|
||||||
@@ -100,3 +125,4 @@ module.exports.StatusManager = StatusManager;
|
|||||||
module.exports.createApiServer = createApiServer;
|
module.exports.createApiServer = createApiServer;
|
||||||
module.exports.startApiServer = startApiServer;
|
module.exports.startApiServer = startApiServer;
|
||||||
module.exports.SlashCommandHandler = SlashCommandHandler;
|
module.exports.SlashCommandHandler = SlashCommandHandler;
|
||||||
|
module.exports.AGENT_VERIFY = AGENT_VERIFY;
|
||||||
@@ -1,14 +1,15 @@
|
|||||||
{
|
{
|
||||||
"id": "padded-cell",
|
"id": "padded-cell",
|
||||||
"name": "PaddedCell",
|
"name": "PaddedCell",
|
||||||
"version": "0.1.0",
|
"version": "0.2.0",
|
||||||
"description": "Secure password management, safe execution, and coordinated restart",
|
"description": "Secure password management, safe execution, and coordinated agent restart",
|
||||||
"entry": "./index.js",
|
"entry": "./index.js",
|
||||||
"configSchema": {
|
"configSchema": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
"enabled": { "type": "boolean", "default": true },
|
"enabled": { "type": "boolean", "default": true },
|
||||||
"passMgrPath": { "type": "string", "default": "/root/.openclaw/bin/pass_mgr" }
|
"passMgrPath": { "type": "string", "default": "" },
|
||||||
|
"openclawProfilePath": { "type": "string", "default": "" }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
20
plugin/package.json
Normal file
20
plugin/package.json
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"name": "padded-cell-plugin",
|
||||||
|
"version": "0.2.0",
|
||||||
|
"description": "PaddedCell plugin for OpenClaw - secure exec, password management, coordinated restart",
|
||||||
|
"main": "index.ts",
|
||||||
|
"scripts": {
|
||||||
|
"build": "tsc",
|
||||||
|
"dev": "tsc --watch"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@types/node": "^20.0.0",
|
||||||
|
"express": "^4.18.0",
|
||||||
|
"ws": "^8.14.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"typescript": "^5.0.0",
|
||||||
|
"@types/express": "^4.17.0",
|
||||||
|
"@types/ws": "^8.5.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,8 +3,8 @@
|
|||||||
"target": "ES2020",
|
"target": "ES2020",
|
||||||
"module": "commonjs",
|
"module": "commonjs",
|
||||||
"lib": ["ES2020"],
|
"lib": ["ES2020"],
|
||||||
"outDir": "./dist",
|
"outDir": "../dist/padded-cell",
|
||||||
"rootDir": "./src",
|
"rootDir": ".",
|
||||||
"strict": true,
|
"strict": true,
|
||||||
"esModuleInterop": true,
|
"esModuleInterop": true,
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
@@ -14,6 +14,6 @@
|
|||||||
"sourceMap": true,
|
"sourceMap": true,
|
||||||
"resolveJsonModule": true
|
"resolveJsonModule": true
|
||||||
},
|
},
|
||||||
"include": ["src/**/*"],
|
"include": ["./**/*.ts"],
|
||||||
"exclude": ["node_modules", "dist", "**/*.test.ts"]
|
"exclude": ["node_modules", "../dist", "**/*.test.ts"]
|
||||||
}
|
}
|
||||||
4821
safe-restart/package-lock.json
generated
4821
safe-restart/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,25 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "safe-restart",
|
|
||||||
"version": "0.1.0",
|
|
||||||
"description": "Safe restart module for OpenClaw agents",
|
|
||||||
"main": "dist/index.js",
|
|
||||||
"types": "dist/index.d.ts",
|
|
||||||
"scripts": {
|
|
||||||
"build": "tsc",
|
|
||||||
"dev": "tsc --watch",
|
|
||||||
"test": "jest"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"@types/node": "^20.0.0",
|
|
||||||
"express": "^4.18.0",
|
|
||||||
"ws": "^8.14.0"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"typescript": "^5.0.0",
|
|
||||||
"@types/express": "^4.17.0",
|
|
||||||
"@types/ws": "^8.5.0",
|
|
||||||
"jest": "^29.0.0",
|
|
||||||
"@types/jest": "^29.0.0",
|
|
||||||
"ts-jest": "^29.0.0"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
{
|
|
||||||
"compilerOptions": {
|
|
||||||
"target": "ES2020",
|
|
||||||
"module": "commonjs",
|
|
||||||
"lib": ["ES2020"],
|
|
||||||
"outDir": "./dist",
|
|
||||||
"rootDir": "./src",
|
|
||||||
"strict": true,
|
|
||||||
"esModuleInterop": true,
|
|
||||||
"skipLibCheck": true,
|
|
||||||
"forceConsistentCasingInFileNames": true,
|
|
||||||
"declaration": true,
|
|
||||||
"declarationMap": true,
|
|
||||||
"sourceMap": true,
|
|
||||||
"resolveJsonModule": true
|
|
||||||
},
|
|
||||||
"include": ["src/**/*"],
|
|
||||||
"exclude": ["node_modules", "dist", "**/*.test.ts"]
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user