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
|
||||
*.test
|
||||
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
|
||||
|
||||
### 1. pass_mgr - Password Manager Binary (Go)
|
||||
### 1. pass_mgr — Password Manager (Go)
|
||||
|
||||
AES-256-GCM encryption, per-agent key-based encryption/decryption.
|
||||
|
||||
```bash
|
||||
# Initialize
|
||||
pass_mgr admin init [--key-path <path>]
|
||||
|
||||
# Get password
|
||||
pass_mgr get <key> [--username]
|
||||
|
||||
# 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>
|
||||
pass_mgr admin init # Initialize
|
||||
pass_mgr get <key> # Get password
|
||||
pass_mgr set <key> <password> # Set password (human only)
|
||||
pass_mgr generate <key> # Generate password
|
||||
pass_mgr unset <key> # Delete
|
||||
pass_mgr rotate <key> # Rotate
|
||||
```
|
||||
|
||||
**Security Features:**
|
||||
- Agents cannot execute `set` (detected via environment variables)
|
||||
- All operations fail before initialization
|
||||
- Admin password leak detection (monitors messages/tool calls)
|
||||
### 2. pcguard — Exec Guard (Go)
|
||||
|
||||
### 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
|
||||
import { pcexec } from 'pcexec';
|
||||
|
||||
const result = await pcexec('echo $(pass_mgr get mypassword)', {
|
||||
cwd: '/workspace',
|
||||
timeout: 30000,
|
||||
});
|
||||
// Passwords in result.stdout will be replaced with ######
|
||||
```bash
|
||||
#!/bin/bash
|
||||
pcguard || exit 1
|
||||
# ... rest of script
|
||||
```
|
||||
|
||||
### 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:**
|
||||
- `idle` - Idle
|
||||
- `busy` - Processing messages
|
||||
- `focus` - Focus mode (workflow)
|
||||
- `freeze` - Frozen (not accepting new messages)
|
||||
- `pre-freeze` - Preparing to freeze
|
||||
- `pre-freeze-focus` - Preparing to freeze (focus mode)
|
||||
### 4. safe-restart — Coordinated Restart (TypeScript)
|
||||
|
||||
Agent state management and coordinated gateway restart.
|
||||
|
||||
**Agent States:** idle → busy → focus → freeze → pre-freeze
|
||||
|
||||
**APIs:**
|
||||
- `POST /query-restart` - Query restart readiness
|
||||
- `POST /restart-result` - Report restart result
|
||||
- `GET /status` - Get all statuses
|
||||
- `POST /query-restart` — Query restart readiness
|
||||
- `POST /restart-result` — Report restart result
|
||||
- `GET /status` — Get all statuses
|
||||
|
||||
**Slash Commands:**
|
||||
```
|
||||
/padded-cell-ctrl status
|
||||
/padded-cell-ctrl enable pass-mgr|safe-restart
|
||||
/padded-cell-ctrl disable pass-mgr|safe-restart
|
||||
```
|
||||
## ⚠️ Security Limitations
|
||||
|
||||
> **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.
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
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
|
||||
│ ├── src/
|
||||
│ │ └── main.go
|
||||
│ └── go.mod
|
||||
├── 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
|
||||
│ └── src/main.go
|
||||
├── pcguard/ # Go exec guard binary
|
||||
│ └── src/main.go
|
||||
├── docs/ # Documentation
|
||||
├── PROJECT_PLAN.md # Project plan
|
||||
├── AGENT_TASKS.md # Task list
|
||||
├── README.md # This file (English)
|
||||
└── README.zh-CN.md # Chinese version
|
||||
├── scripts/ # Utility scripts
|
||||
├── dist/padded-cell/ # Build output
|
||||
├── install.mjs # Installer
|
||||
└── README.md
|
||||
```
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
# Install
|
||||
node install.mjs --install
|
||||
# Install (default: ~/.openclaw)
|
||||
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
|
||||
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
|
||||
|
||||
> 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
|
||||
# Initialize (required before first use)
|
||||
# Initialize pass_mgr
|
||||
~/.openclaw/bin/pass_mgr admin init
|
||||
|
||||
# Set password
|
||||
# Set and get passwords
|
||||
~/.openclaw/bin/pass_mgr set mykey mypassword
|
||||
|
||||
# Get password
|
||||
~/.openclaw/bin/pass_mgr get mykey
|
||||
|
||||
# Use pcguard in scripts
|
||||
pcguard || exit 1
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
624
install.mjs
624
install.mjs
@@ -1,19 +1,18 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* PaddedCell Plugin Installer
|
||||
* PaddedCell Plugin Installer v0.2.0
|
||||
*
|
||||
* Usage:
|
||||
* 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 --skip-check
|
||||
* node install.mjs --uninstall
|
||||
* node install.mjs --uninstall --prefix /usr/local
|
||||
*/
|
||||
|
||||
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 { fileURLToPath } from 'url';
|
||||
import { homedir, platform } from 'os';
|
||||
@@ -21,534 +20,289 @@ import { homedir, platform } from 'os';
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = resolve(dirname(__filename));
|
||||
|
||||
// Plugin configuration - matches directory name in dist/
|
||||
const PLUGIN_NAME = 'padded-cell';
|
||||
const DIST_DIR = join(__dirname, 'dist', PLUGIN_NAME);
|
||||
const SRC_DIST_DIR = join(__dirname, 'dist', PLUGIN_NAME);
|
||||
|
||||
// Parse arguments
|
||||
const args = process.argv.slice(2);
|
||||
const options = {
|
||||
prefix: null,
|
||||
openclawProfilePath: null,
|
||||
buildOnly: args.includes('--build-only'),
|
||||
skipCheck: args.includes('--skip-check'),
|
||||
verbose: args.includes('--verbose') || args.includes('-v'),
|
||||
uninstall: args.includes('--uninstall'),
|
||||
};
|
||||
|
||||
// Parse --prefix value
|
||||
const prefixIndex = args.indexOf('--prefix');
|
||||
if (prefixIndex !== -1 && args[prefixIndex + 1]) {
|
||||
options.prefix = resolve(args[prefixIndex + 1]);
|
||||
// Parse --openclaw-profile-path value
|
||||
const profileIdx = args.indexOf('--openclaw-profile-path');
|
||||
if (profileIdx !== -1 && args[profileIdx + 1]) {
|
||||
options.openclawProfilePath = resolve(args[profileIdx + 1]);
|
||||
}
|
||||
|
||||
// Colors for output
|
||||
const colors = {
|
||||
reset: '\x1b[0m',
|
||||
red: '\x1b[31m',
|
||||
green: '\x1b[32m',
|
||||
yellow: '\x1b[33m',
|
||||
blue: '\x1b[34m',
|
||||
cyan: '\x1b[36m',
|
||||
// Resolve openclaw path: --openclaw-profile-path → $OPENCLAW_PATH → ~/.openclaw
|
||||
function resolveOpenclawPath() {
|
||||
if (options.openclawProfilePath) return options.openclawProfilePath;
|
||||
if (process.env.OPENCLAW_PATH) return resolve(process.env.OPENCLAW_PATH);
|
||||
return join(homedir(), '.openclaw');
|
||||
}
|
||||
|
||||
// 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') {
|
||||
console.log(`${colors[color]}${message}${colors.reset}`);
|
||||
}
|
||||
|
||||
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 = {
|
||||
function exec(command, opts = {}) {
|
||||
return execSync(command, {
|
||||
cwd: __dirname,
|
||||
stdio: options.silent ? 'pipe' : 'inherit',
|
||||
stdio: opts.silent ? 'pipe' : 'inherit',
|
||||
encoding: 'utf8',
|
||||
};
|
||||
return execSync(command, { ...defaultOptions, ...options });
|
||||
...opts,
|
||||
});
|
||||
}
|
||||
|
||||
// OpenClaw config helpers
|
||||
function getOpenclawConfig(pathKey, defaultValue = undefined) {
|
||||
function getOpenclawConfig(key, def = undefined) {
|
||||
try {
|
||||
const out = execSync(`openclaw config get ${pathKey} --json 2>/dev/null || echo "undefined"`, {
|
||||
encoding: 'utf8',
|
||||
cwd: __dirname
|
||||
}).trim();
|
||||
if (out === 'undefined' || out === '') return defaultValue;
|
||||
const out = exec(`openclaw config get ${key} --json 2>/dev/null || echo "undefined"`, { silent: true }).trim();
|
||||
if (out === 'undefined' || out === '') return def;
|
||||
return JSON.parse(out);
|
||||
} catch {
|
||||
return defaultValue;
|
||||
}
|
||||
} catch { return def; }
|
||||
}
|
||||
function setOpenclawConfig(key, value) {
|
||||
exec(`openclaw config set ${key} '${JSON.stringify(value)}' --json`, { silent: true });
|
||||
}
|
||||
function unsetOpenclawConfig(key) {
|
||||
try { exec(`openclaw config unset ${key}`, { silent: true }); } catch {}
|
||||
}
|
||||
|
||||
function 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) {
|
||||
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);
|
||||
}
|
||||
for (const entry of readdirSync(src, { withFileTypes: true })) {
|
||||
const s = join(src, entry.name);
|
||||
const d = join(dest, entry.name);
|
||||
if (entry.name === 'node_modules') continue; // skip node_modules
|
||||
entry.isDirectory() ? copyDir(s, d) : copyFileSync(s, d);
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Step 1: Environment Detection
|
||||
// ============================================================================
|
||||
// ── Step 1: Detect ──────────────────────────────────────────────────────
|
||||
|
||||
function detectEnvironment() {
|
||||
logStep(1, 'Detecting environment...');
|
||||
logStep(1, 6, 'Detecting environment...');
|
||||
const env = { platform: platform(), nodeVersion: null, goVersion: null };
|
||||
|
||||
const env = {
|
||||
platform: platform(),
|
||||
nodeVersion: null,
|
||||
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');
|
||||
}
|
||||
try { env.nodeVersion = exec('node --version', { silent: true }).trim(); logOk(`Node.js ${env.nodeVersion}`); } catch { logErr('Node.js not found'); }
|
||||
try { env.goVersion = exec('go version', { silent: true }).trim(); logOk(`Go: ${env.goVersion}`); } catch { logErr('Go not found'); }
|
||||
try { logOk(`openclaw at ${exec('which openclaw', { silent: true }).trim()}`); } catch { logWarn('openclaw CLI not in PATH'); }
|
||||
|
||||
return env;
|
||||
}
|
||||
|
||||
function checkDependencies(env) {
|
||||
if (options.skipCheck) {
|
||||
logWarning('Skipping dependency checks');
|
||||
return true;
|
||||
}
|
||||
// ── Step 2: Check deps ──────────────────────────────────────────────────
|
||||
|
||||
logStep(2, 'Checking dependencies...');
|
||||
|
||||
let hasErrors = false;
|
||||
|
||||
if (!env.nodeVersion) {
|
||||
logError('Node.js is required. Please install Node.js 18+');
|
||||
hasErrors = true;
|
||||
} else {
|
||||
const majorVersion = parseInt(env.nodeVersion.slice(1).split('.')[0]);
|
||||
if (majorVersion < 18) {
|
||||
logError(`Node.js 18+ required, found ${env.nodeVersion}`);
|
||||
hasErrors = true;
|
||||
} else {
|
||||
logSuccess(`Node.js version OK`);
|
||||
}
|
||||
}
|
||||
|
||||
if (!env.goVersion) {
|
||||
logError('Go is required. Please install Go 1.22+');
|
||||
hasErrors = true;
|
||||
} else {
|
||||
logSuccess(`Go version OK`);
|
||||
}
|
||||
|
||||
if (hasErrors) {
|
||||
log('\nPlease install missing dependencies and try again.', 'red');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
return true;
|
||||
function checkDeps(env) {
|
||||
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');
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Step 3: Build Components
|
||||
// ============================================================================
|
||||
// ── Step 3: Build ───────────────────────────────────────────────────────
|
||||
|
||||
async function buildComponents(env) {
|
||||
logStep(3, 'Building components...');
|
||||
async function build() {
|
||||
logStep(3, 6, 'Building components...');
|
||||
|
||||
// Build pass_mgr
|
||||
log(' Building pass_mgr (Go)...', 'blue');
|
||||
try {
|
||||
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 });
|
||||
// pass_mgr (Go)
|
||||
log(' Building pass_mgr...', 'blue');
|
||||
const pmDir = join(__dirname, 'pass_mgr');
|
||||
exec('go mod tidy', { cwd: pmDir, silent: !options.verbose });
|
||||
exec('go build -o dist/pass_mgr src/main.go', { cwd: pmDir, silent: !options.verbose });
|
||||
chmodSync(join(pmDir, 'dist', 'pass_mgr'), 0o755);
|
||||
logOk('pass_mgr');
|
||||
|
||||
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;
|
||||
}
|
||||
// pcguard (Go)
|
||||
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');
|
||||
|
||||
// Build pcexec
|
||||
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;
|
||||
}
|
||||
// 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');
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Step 4: Install Components
|
||||
// ============================================================================
|
||||
// ── Step 4: Install ─────────────────────────────────────────────────────
|
||||
|
||||
async function installComponents(env) {
|
||||
if (options.buildOnly) {
|
||||
logStep(4, 'Skipping installation (--build-only)');
|
||||
return null;
|
||||
}
|
||||
async function install() {
|
||||
if (options.buildOnly) { logStep(4, 6, 'Skipping install (--build-only)'); return null; }
|
||||
logStep(4, 6, 'Installing...');
|
||||
|
||||
logStep(4, 'Installing components...');
|
||||
const openclawPath = resolveOpenclawPath();
|
||||
const binDir = join(openclawPath, 'bin');
|
||||
const pluginsDir = join(openclawPath, 'plugins');
|
||||
const destDir = join(pluginsDir, PLUGIN_NAME);
|
||||
|
||||
const installDir = options.prefix || env.openclawDir;
|
||||
const binDir = join(installDir, 'bin');
|
||||
log(` OpenClaw path: ${openclawPath}`, 'blue');
|
||||
|
||||
log(` Install directory: ${installDir}`, 'blue');
|
||||
log(` Binary directory: ${binDir}`, 'blue');
|
||||
log(` Dist directory: ${DIST_DIR}`, 'blue');
|
||||
// Copy dist/padded-cell → plugins/padded-cell
|
||||
if (existsSync(destDir)) rmSync(destDir, { recursive: true, force: true });
|
||||
copyDir(SRC_DIST_DIR, destDir);
|
||||
|
||||
// Create dist/padded-cell directory and copy plugin files
|
||||
log(' Copying plugin files to dist/padded-cell...', 'blue');
|
||||
mkdirSync(DIST_DIR, { recursive: true });
|
||||
// Copy openclaw.plugin.json
|
||||
copyFileSync(join(__dirname, 'plugin', 'openclaw.plugin.json'), join(destDir, 'openclaw.plugin.json'));
|
||||
logOk(`Plugin files → ${destDir}`);
|
||||
|
||||
// Copy pcexec
|
||||
copyDir(join(__dirname, 'pcexec'), join(DIST_DIR, 'pcexec'));
|
||||
logSuccess('Copied pcexec to dist/padded-cell/');
|
||||
// Install runtime deps into dest (express, ws)
|
||||
exec('npm install --omit=dev', { cwd: destDir, silent: !options.verbose });
|
||||
logOk('Runtime deps installed');
|
||||
|
||||
// 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
|
||||
// Binaries
|
||||
mkdirSync(binDir, { recursive: true });
|
||||
const bins = [
|
||||
{ name: 'pass_mgr', src: join(__dirname, 'pass_mgr', 'dist', 'pass_mgr') },
|
||||
{ name: 'pcguard', src: join(__dirname, 'pcguard', 'dist', 'pcguard') },
|
||||
];
|
||||
for (const b of bins) {
|
||||
const dest = join(binDir, b.name);
|
||||
copyFileSync(b.src, dest);
|
||||
chmodSync(dest, 0o755);
|
||||
logOk(`${b.name} → ${dest}`);
|
||||
}
|
||||
|
||||
log(' Installing pass_mgr binary...', 'blue');
|
||||
const passMgrSource = join(__dirname, 'pass_mgr', 'dist', 'pass_mgr');
|
||||
const passMgrDest = join(binDir, 'pass_mgr');
|
||||
copyFileSync(passMgrSource, passMgrDest);
|
||||
chmodSync(passMgrDest, 0o755);
|
||||
logSuccess(`pass_mgr installed to ${passMgrDest}`);
|
||||
|
||||
return { passMgrPath: passMgrDest };
|
||||
return { binDir, destDir };
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Step 5: Configuration
|
||||
// ============================================================================
|
||||
// ── Step 5: Configure ───────────────────────────────────────────────────
|
||||
|
||||
async function configure(env) {
|
||||
if (options.buildOnly) {
|
||||
logStep(5, 'Skipping configuration (--build-only)');
|
||||
return;
|
||||
}
|
||||
async function configure() {
|
||||
if (options.buildOnly) { logStep(5, 6, 'Skipping config'); return; }
|
||||
logStep(5, 6, 'Configuring OpenClaw...');
|
||||
|
||||
logStep(5, 'Configuration...');
|
||||
|
||||
const installDir = options.prefix || env.openclawDir;
|
||||
const passMgrPath = join(installDir, 'bin', 'pass_mgr');
|
||||
|
||||
// Check if already initialized
|
||||
const adminKeyDir = join(homedir(), '.pass_mgr');
|
||||
const configPath = join(adminKeyDir, 'config.json');
|
||||
|
||||
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');
|
||||
const openclawPath = resolveOpenclawPath();
|
||||
const destDir = join(openclawPath, 'plugins', PLUGIN_NAME);
|
||||
const passMgrPath = join(openclawPath, 'bin', 'pass_mgr');
|
||||
|
||||
try {
|
||||
// 1. Add plugin path to plugins.load.paths FIRST (required for validation)
|
||||
const currentPaths = getOpenclawConfig('plugins.load.paths', []);
|
||||
log(` Current paths: ${JSON.stringify(currentPaths)}`, 'blue');
|
||||
log(` DIST_DIR: ${DIST_DIR}`, 'blue');
|
||||
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');
|
||||
}
|
||||
// plugins.load.paths
|
||||
const paths = getOpenclawConfig('plugins.load.paths', []);
|
||||
if (!paths.includes(destDir)) { paths.push(destDir); setOpenclawConfig('plugins.load.paths', paths); }
|
||||
logOk(`plugins.load.paths includes ${destDir}`);
|
||||
|
||||
// 2. Add to plugins.allow (after path is set)
|
||||
const allowList = getOpenclawConfig('plugins.allow', []);
|
||||
if (!allowList.includes(PLUGIN_NAME)) {
|
||||
allowList.push(PLUGIN_NAME);
|
||||
setOpenclawConfig('plugins.allow', allowList);
|
||||
logSuccess(`Added '${PLUGIN_NAME}' to plugins.allow`);
|
||||
} else {
|
||||
log(' Already in plugins.allow', 'green');
|
||||
}
|
||||
// plugins.allow
|
||||
const allow = getOpenclawConfig('plugins.allow', []);
|
||||
if (!allow.includes(PLUGIN_NAME)) { allow.push(PLUGIN_NAME); setOpenclawConfig('plugins.allow', allow); }
|
||||
logOk(`plugins.allow includes ${PLUGIN_NAME}`);
|
||||
|
||||
// 3. Add plugin entry
|
||||
// plugins.entries
|
||||
const plugins = getOpenclawConfig('plugins', {});
|
||||
plugins.entries = plugins.entries || {};
|
||||
plugins.entries[PLUGIN_NAME] = {
|
||||
enabled: true,
|
||||
config: {
|
||||
enabled: true,
|
||||
passMgrPath: passMgrPath,
|
||||
},
|
||||
config: { enabled: true, passMgrPath, openclawProfilePath: openclawPath },
|
||||
};
|
||||
setOpenclawConfig('plugins', plugins);
|
||||
logSuccess(`Configured ${PLUGIN_NAME} plugin entry`);
|
||||
logOk('Plugin entry configured');
|
||||
} catch (err) {
|
||||
logWarning(`Failed to configure OpenClaw: ${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');
|
||||
logWarn(`Config failed: ${err.message}`);
|
||||
}
|
||||
|
||||
// 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: Print Summary
|
||||
// ============================================================================
|
||||
|
||||
function printSummary(env, passMgrPath) {
|
||||
logStep(6, 'Installation Summary');
|
||||
// ── Step 6: Summary ─────────────────────────────────────────────────────
|
||||
|
||||
function summary(result) {
|
||||
logStep(6, 6, 'Done!');
|
||||
console.log('');
|
||||
log('╔════════════════════════════════════════════════════════╗', 'cyan');
|
||||
log('║ PaddedCell Installation Complete ║', 'cyan');
|
||||
log('╚════════════════════════════════════════════════════════╝', 'cyan');
|
||||
console.log('');
|
||||
log('╔══════════════════════════════════════════════╗', 'cyan');
|
||||
log('║ PaddedCell v0.2.0 Install Complete ║', 'cyan');
|
||||
log('╚══════════════════════════════════════════════╝', 'cyan');
|
||||
|
||||
if (options.buildOnly) {
|
||||
log('Build-only mode - binaries built but not installed', 'yellow');
|
||||
console.log('');
|
||||
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('');
|
||||
log('\nBuild-only — binaries not installed.', 'yellow');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('');
|
||||
log('Next steps:', 'blue');
|
||||
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:', 'yellow');
|
||||
log(' openclaw gateway restart', 'cyan');
|
||||
}
|
||||
log(' 1. 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('');
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Uninstall
|
||||
// ============================================================================
|
||||
// ── Uninstall ───────────────────────────────────────────────────────────
|
||||
|
||||
async function uninstall(env) {
|
||||
logStep(1, 'Uninstalling PaddedCell...');
|
||||
async function uninstall() {
|
||||
log('Uninstalling PaddedCell...', 'cyan');
|
||||
const openclawPath = resolveOpenclawPath();
|
||||
|
||||
const installDir = options.prefix || env.openclawDir || join(homedir(), '.openclaw');
|
||||
const passMgrBinary = join(installDir, 'bin', 'pass_mgr');
|
||||
// Remove binaries
|
||||
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
|
||||
if (existsSync(passMgrBinary)) {
|
||||
// Remove plugin dir
|
||||
const destDir = join(openclawPath, 'plugins', PLUGIN_NAME);
|
||||
if (existsSync(destDir)) { rmSync(destDir, { recursive: true }); logOk(`Removed ${destDir}`); }
|
||||
|
||||
// Remove config
|
||||
try {
|
||||
execSync(`rm -f "${passMgrBinary}"`, { silent: true });
|
||||
logSuccess(`Removed ${passMgrBinary}`);
|
||||
} catch (err) {
|
||||
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
|
||||
const allow = getOpenclawConfig('plugins.allow', []);
|
||||
const idx = allow.indexOf(PLUGIN_NAME);
|
||||
if (idx !== -1) { allow.splice(idx, 1); setOpenclawConfig('plugins.allow', allow); logOk('Removed from allow list'); }
|
||||
unsetOpenclawConfig(`plugins.entries.${PLUGIN_NAME}`);
|
||||
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
|
||||
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
|
||||
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');
|
||||
log('\nRun: openclaw gateway restart', 'yellow');
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Main
|
||||
// ============================================================================
|
||||
// ── Main ────────────────────────────────────────────────────────────────
|
||||
|
||||
async function main() {
|
||||
console.log('');
|
||||
log('╔════════════════════════════════════════════════════════╗', 'cyan');
|
||||
log('║ PaddedCell Plugin Installer v0.1.0 ║', 'cyan');
|
||||
log('╚════════════════════════════════════════════════════════╝', 'cyan');
|
||||
log('╔══════════════════════════════════════════════╗', 'cyan');
|
||||
log('║ PaddedCell Plugin Installer v0.2.0 ║', 'cyan');
|
||||
log('╚══════════════════════════════════════════════╝', 'cyan');
|
||||
console.log('');
|
||||
|
||||
try {
|
||||
const env = detectEnvironment();
|
||||
|
||||
// Handle uninstall
|
||||
if (options.uninstall) {
|
||||
await uninstall(env);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
checkDependencies(env);
|
||||
await buildComponents(env);
|
||||
const result = await installComponents(env);
|
||||
await configure(env);
|
||||
printSummary(env, result?.passMgrPath);
|
||||
process.exit(0);
|
||||
if (options.uninstall) { await uninstall(); process.exit(0); }
|
||||
checkDeps(env);
|
||||
await build();
|
||||
const result = await install();
|
||||
await configure();
|
||||
summary(result);
|
||||
} catch (err) {
|
||||
console.log('');
|
||||
log('╔════════════════════════════════════════════════════════╗', 'red');
|
||||
log('║ Installation Failed ║', 'red');
|
||||
log('╚════════════════════════════════════════════════════════╝', 'red');
|
||||
console.log('');
|
||||
log(`Error: ${err.message}`, 'red');
|
||||
log(`\nInstallation failed: ${err.message}`, 'red');
|
||||
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 {
|
||||
statusManager: StatusManager;
|
||||
@@ -1,4 +1,4 @@
|
||||
export { StatusManager, type AgentStatus, type GlobalStatus, type AgentState } from './status-manager';
|
||||
export { createApiServer, startApiServer } from './api';
|
||||
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
|
||||
// Registers pcexec and safe_restart tools
|
||||
|
||||
const { pcexec, pcexecSync } = require('./pcexec/dist/index.js');
|
||||
const {
|
||||
import { pcexec, pcexecSync } from './tools/pcexec';
|
||||
import {
|
||||
safeRestart,
|
||||
createSafeRestartTool,
|
||||
StatusManager,
|
||||
createApiServer,
|
||||
startApiServer,
|
||||
SlashCommandHandler
|
||||
} = require('./safe-restart/dist/index.js');
|
||||
} from './core/index';
|
||||
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
|
||||
function register(api, config) {
|
||||
function register(api: any, config?: any) {
|
||||
const logger = api.logger || { info: console.log, error: console.error };
|
||||
|
||||
logger.info('PaddedCell plugin initializing...');
|
||||
|
||||
// Register pcexec tool - pass a FACTORY function that receives context
|
||||
api.registerTool((ctx) => {
|
||||
console.log(`[PaddedCell] pcexec factory called with ctx:`, JSON.stringify(ctx, null, 2));
|
||||
const openclawPath = resolveOpenclawPath(config);
|
||||
const binDir = require('path').join(openclawPath, 'bin');
|
||||
|
||||
// Register pcexec tool — pass a FACTORY function that receives context
|
||||
api.registerTool((ctx: any) => {
|
||||
const agentId = ctx.agentId;
|
||||
const workspaceDir = ctx.workspaceDir;
|
||||
|
||||
@@ -35,20 +51,29 @@ function register(api, config) {
|
||||
},
|
||||
required: ['command'],
|
||||
},
|
||||
async execute(_id, params) {
|
||||
async execute(_id: string, params: any) {
|
||||
const command = params.command;
|
||||
if (!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, {
|
||||
cwd: params.cwd || workspaceDir,
|
||||
timeout: params.timeout,
|
||||
env: {
|
||||
AGENT_ID: agentId || '',
|
||||
AGENT_WORKSPACE: workspaceDir || '',
|
||||
AGENT_VERIFY,
|
||||
PATH: newPath,
|
||||
},
|
||||
});
|
||||
|
||||
// Format output for OpenClaw tool response
|
||||
let output = result.stdout;
|
||||
if (result.stderr) {
|
||||
@@ -59,8 +84,8 @@ function register(api, config) {
|
||||
};
|
||||
});
|
||||
|
||||
// Register safe_restart tool - pass a FACTORY function that receives context
|
||||
api.registerTool((ctx) => {
|
||||
// Register safe_restart tool
|
||||
api.registerTool((ctx: any) => {
|
||||
const agentId = ctx.agentId;
|
||||
const sessionKey = ctx.sessionKey;
|
||||
|
||||
@@ -74,10 +99,10 @@ function register(api, config) {
|
||||
log: { type: 'string', description: 'Log file path' },
|
||||
},
|
||||
},
|
||||
async execute(_id, params) {
|
||||
async execute(_id: string, params: any) {
|
||||
return await safeRestart({
|
||||
agentId: agentId,
|
||||
sessionKey: sessionKey,
|
||||
agentId,
|
||||
sessionKey,
|
||||
rollback: params.rollback,
|
||||
log: params.log,
|
||||
});
|
||||
@@ -88,7 +113,7 @@ function register(api, config) {
|
||||
logger.info('PaddedCell plugin initialized');
|
||||
}
|
||||
|
||||
// Export for OpenClaw
|
||||
// CommonJS export for OpenClaw
|
||||
module.exports = { register };
|
||||
|
||||
// Also export individual modules for direct use
|
||||
@@ -100,3 +125,4 @@ module.exports.StatusManager = StatusManager;
|
||||
module.exports.createApiServer = createApiServer;
|
||||
module.exports.startApiServer = startApiServer;
|
||||
module.exports.SlashCommandHandler = SlashCommandHandler;
|
||||
module.exports.AGENT_VERIFY = AGENT_VERIFY;
|
||||
@@ -1,14 +1,15 @@
|
||||
{
|
||||
"id": "padded-cell",
|
||||
"name": "PaddedCell",
|
||||
"version": "0.1.0",
|
||||
"description": "Secure password management, safe execution, and coordinated restart",
|
||||
"version": "0.2.0",
|
||||
"description": "Secure password management, safe execution, and coordinated agent restart",
|
||||
"entry": "./index.js",
|
||||
"configSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"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",
|
||||
"module": "commonjs",
|
||||
"lib": ["ES2020"],
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"outDir": "../dist/padded-cell",
|
||||
"rootDir": ".",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
@@ -14,6 +14,6 @@
|
||||
"sourceMap": true,
|
||||
"resolveJsonModule": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist", "**/*.test.ts"]
|
||||
"include": ["./**/*.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