Compare commits
73 Commits
10d7e8a6c2
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| cb683c43bb | |||
| 392eafccf2 | |||
| 39856a3060 | |||
| c6f0393c65 | |||
| 1a202986e8 | |||
| dcc91ead9b | |||
| 311d9f4d9f | |||
| 525436d64b | |||
| 36f3c93484 | |||
| 1ac75f429c | |||
| a2b965094d | |||
| 98a75a50d3 | |||
| 4a8a4b01cb | |||
| 95fb9ba820 | |||
| 764ada7c60 | |||
| 81c0a4c289 | |||
| 4e8e264390 | |||
| 21d7a85ba1 | |||
| 7346c80c88 | |||
| 7fd2819a04 | |||
| 98fc3da39c | |||
| be0f194f47 | |||
| 2816f3a862 | |||
| ce79a782b9 | |||
| 63d7fb569e | |||
| 2f149ed1b4 | |||
| 123c73cfc6 | |||
| 79c5f4cd27 | |||
| 61cffae9ca | |||
| 99787e6ded | |||
| 2e38cb8fe2 | |||
| c16149db9d | |||
| b00086816c | |||
| a347908d9f | |||
| bc2c5f8bd6 | |||
| ddaea57f2d | |||
| c186eb24ec | |||
| 0569a5dcf5 | |||
| 239a6c3552 | |||
| 59d72ef365 | |||
| 0760fed8ff | |||
| 5134325794 | |||
| 842a19a56c | |||
| 903e5efddb | |||
| 9c70cc33a5 | |||
| c2fb28301c | |||
| 27a94d1da7 | |||
| 858538aaad | |||
| e97ce0208e | |||
| 6454004d66 | |||
| 232b772a6b | |||
| bb194ef978 | |||
| 888ed0e51a | |||
| c366958a37 | |||
| da34a3eb5e | |||
| 08e74e3806 | |||
| 7e0c4cd5e6 | |||
| 15474eee48 | |||
| 0daf1432a7 | |||
| 1c84b4d6a0 | |||
| 62044ab948 | |||
| 3a495f8d64 | |||
| 259f9dc418 | |||
| ceb17f375b | |||
| 9ecb065b43 | |||
| 84c9df633a | |||
| 5084cfecb8 | |||
| 21d04b17cd | |||
| 8d270bfddf | |||
| 28af11cfbb | |||
| 849effd301 | |||
| b37ebb3db1 | |||
|
|
10e1124550 |
36
.gitignore
vendored
Normal file
36
.gitignore
vendored
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
# Dependencies
|
||||||
|
node_modules/
|
||||||
|
*.log
|
||||||
|
|
||||||
|
# Build outputs
|
||||||
|
dist/
|
||||||
|
*.exe
|
||||||
|
*.dll
|
||||||
|
*.so
|
||||||
|
*.dylib
|
||||||
|
|
||||||
|
# Environment
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
|
||||||
|
# IDE
|
||||||
|
.vscode/
|
||||||
|
.idea/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# Go
|
||||||
|
*.o
|
||||||
|
*.a
|
||||||
|
*.test
|
||||||
|
vendor/
|
||||||
|
|
||||||
|
# Lock files (sub-packages)
|
||||||
|
plugin/package-lock.json
|
||||||
|
|
||||||
|
# Build secret (generated by install.mjs)
|
||||||
|
.build-secret
|
||||||
106
AGENT_TASKS.md
106
AGENT_TASKS.md
@@ -1,106 +0,0 @@
|
|||||||
# PaddedCell — Agent Tasks
|
|
||||||
|
|
||||||
> 任务拆分 + 依赖关系(基于 PROJECT_PLAN.md)
|
|
||||||
|
|
||||||
## Legend
|
|
||||||
- **ID**: 任务唯一编号
|
|
||||||
- **Deps**: 前置任务(可并行则留空)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 0. 项目准备
|
|
||||||
- **T-0001**:确认配置项清单(路径模板、rotate 语义、admin 泄露检测范围)
|
|
||||||
- Deps: —
|
|
||||||
- **T-0002**:确定加密库与存储格式(选型与接口约束)
|
|
||||||
- Deps: T-0001
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. pass_mgr 二进制
|
|
||||||
- **T-1001**:CLI 命令规范与参数校验(get/generate/unset/rotate/admin init/set)
|
|
||||||
- Deps: T-0001
|
|
||||||
- **T-1002**:初始化与 admin 密码存储/校验机制
|
|
||||||
- Deps: T-1001, T-0002
|
|
||||||
- **T-1003**:加/解密与存取实现(内置加密库)
|
|
||||||
- Deps: T-1001, T-0002
|
|
||||||
- **T-1004**:generate / rotate 实现与语义落地
|
|
||||||
- Deps: T-1003
|
|
||||||
- **T-1005**:admin-only set 实现(环境变量检测 + 禁止 agent 执行)
|
|
||||||
- Deps: T-1001
|
|
||||||
- **T-1006**:未初始化状态阻断逻辑(所有 get/generate/set 报错)
|
|
||||||
- Deps: T-1002
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. pcexec 工具(TS)
|
|
||||||
- **T-2001**:exec 参数/行为兼容设计(与原生 exec 对齐)
|
|
||||||
- Deps: —
|
|
||||||
- **T-2002**:pass_mgr get 检测与预执行(不限 `$(...)`)
|
|
||||||
- Deps: T-2001, T-1001
|
|
||||||
- **T-2003**:多密码脱敏替换(stdout/stderr)
|
|
||||||
- Deps: T-2002
|
|
||||||
- **T-2004**:错误处理/退出码一致性
|
|
||||||
- Deps: T-2001
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. 安全重启(CalmGate 功能并入)
|
|
||||||
- **T-3001**:状态机与 session tracker(idle/busy/focus/freeze…)
|
|
||||||
- Deps: —
|
|
||||||
- **T-3002**:消息生命周期 hooks(start/end)与状态迁移
|
|
||||||
- Deps: T-3001
|
|
||||||
- **T-3003**:workflow/focus 机制与“忙碌回复”
|
|
||||||
- Deps: T-3001
|
|
||||||
- **T-3004**:query-restart API(OK/NOT_READY/ALREADY_SCHEDULED)
|
|
||||||
- Deps: T-3001, T-3002
|
|
||||||
- **T-3005**:safe-restart 工具(轮询/重启/rollback/log)
|
|
||||||
- Deps: T-3004
|
|
||||||
- **T-3006**:重启后恢复与通知(冻结/解冻与回到工作 session)
|
|
||||||
- Deps: T-3005
|
|
||||||
- **T-3007**:持久化(mem+file)与恢复策略
|
|
||||||
- Deps: T-3001
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. 安全监控与泄露防护
|
|
||||||
- **T-4001**:admin 密码泄露检测(message/tool calling)
|
|
||||||
- Deps: T-1002
|
|
||||||
- **T-4002**:泄露触发处理(重置未初始化 + 严重漏洞日志)
|
|
||||||
- Deps: T-4001
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4.1 功能开关(Slash Commands)
|
|
||||||
- **T-4101**:实现 `/padded-cell-ctrl` 命令(status/enable/disable)
|
|
||||||
- Deps: —
|
|
||||||
- **T-4102**:开关状态持久化、权限限制(授权用户)与 10 秒冷却
|
|
||||||
- Deps: T-4101
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. 文档 & Skill 指南
|
|
||||||
- **T-5001**:Agent 使用指南(如何用 pass_mgr/pcexec)
|
|
||||||
- Deps: T-1001, T-2001
|
|
||||||
- **T-5002**:Skill 文档与示例(正确使用密码相关工具)
|
|
||||||
- Deps: T-5001
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 6. 测试与验收
|
|
||||||
- **T-6001**:pass_mgr 单测(get/generate/unset/rotate/admin init)
|
|
||||||
- Deps: T-1002, T-1003, T-1004, T-1005, T-1006
|
|
||||||
- **T-6002**:pcexec 兼容性测试(参数/管道/多密码替换)
|
|
||||||
- Deps: T-2002, T-2003, T-2004
|
|
||||||
- **T-6003**:安全重启回归(并发/冻结/rollback)
|
|
||||||
- Deps: T-3004, T-3005, T-3006, T-3007
|
|
||||||
- **T-6004**:admin 泄露触发测试
|
|
||||||
- Deps: T-4002
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 依赖关系示意(简化)
|
|
||||||
- 0.* → 1.* / 2.* / 3.*
|
|
||||||
- 1.* → 4.* → 6.*
|
|
||||||
- 2.* → 6.*
|
|
||||||
- 3.* → 6.*
|
|
||||||
- 5.* 可与 1.* / 2.* 并行,但需接口稳定
|
|
||||||
178
README.md
Normal file
178
README.md
Normal file
@@ -0,0 +1,178 @@
|
|||||||
|
<div align="center">
|
||||||
|
|
||||||
|
[English](README.md) | [简体中文](README.zh-CN.md)
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
# PaddedCell
|
||||||
|
|
||||||
|
OpenClaw plugin for secure secret management, agent identity management, safe command execution, and coordinated agent restart.
|
||||||
|
|
||||||
|
## ⚠️ Security Model
|
||||||
|
|
||||||
|
> **pcexec + pcguard mitigate light model hallucination / misoperation / prompt forgetting.**
|
||||||
|
> They **do not** defend against malicious attacks.
|
||||||
|
> For stronger security, use **sandbox mode** instead of this plugin.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
### 1. secret-mgr — Secret Manager (Go)
|
||||||
|
|
||||||
|
AES-256-GCM encryption with a **build-time secret** injected at compile time.
|
||||||
|
Secrets are stored per-agent under `pc-pass-store/<agent-id>/<key>.gpg`.
|
||||||
|
|
||||||
|
**Agent commands** (require pcguard — must run through pcexec):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
secret-mgr list # List keys for current agent
|
||||||
|
secret-mgr get-secret --key <key> # Output secret
|
||||||
|
secret-mgr get-username --key <key> # Output username
|
||||||
|
secret-mgr set --key <key> --secret <s> [--username <u>] # Set entry
|
||||||
|
secret-mgr generate --key <key> [--username <u>] # Generate random secret
|
||||||
|
secret-mgr unset --key <key> # Delete entry
|
||||||
|
secret-mgr get <key> # Legacy (maps to get-secret)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Admin commands** (human-only — rejected if any `AGENT_*` env var is set):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
secret-mgr admin handoff [file] # Export build secret to file (default: pc-pass-store.secret)
|
||||||
|
secret-mgr admin init-from [file] # Re-encrypt all data from old build secret to current
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. ego-mgr — Agent Identity Manager (Go)
|
||||||
|
|
||||||
|
Manages agent personal information (name, email, timezone, etc.) stored in `~/.openclaw/ego.json`.
|
||||||
|
|
||||||
|
Supports **Agent Scope** (per-agent values) and **Public Scope** (shared by all agents).
|
||||||
|
|
||||||
|
**Commands** (require pcguard — must run through pcexec):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ego-mgr add column <name> [--default <val>] # Add agent-scope field
|
||||||
|
ego-mgr add public-column <name> [--default <val>] # Add public-scope field
|
||||||
|
ego-mgr delete <name> # Delete field and all values
|
||||||
|
ego-mgr set <name> <value> # Set field value
|
||||||
|
ego-mgr get <name> # Get field value
|
||||||
|
ego-mgr show # Show all fields and values
|
||||||
|
ego-mgr list columns # List all field names
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. pcguard — Exec Guard (Go)
|
||||||
|
|
||||||
|
Validates that a process is running inside a pcexec context by checking environment sentinels (`AGENT_VERIFY`, `AGENT_ID`, `AGENT_WORKSPACE`). Returns exit code 1 if any check fails.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
#!/bin/bash
|
||||||
|
pcguard || exit 1
|
||||||
|
# ... rest of script
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. pcexec — Safe Execution Tool (TypeScript)
|
||||||
|
|
||||||
|
Drop-in replacement for `exec` that:
|
||||||
|
- Resolves `$(secret-mgr get-secret --key <key>)` and legacy `$(pass_mgr get-secret --key <key>)` inline
|
||||||
|
- Sanitizes all resolved passwords from stdout/stderr
|
||||||
|
- Injects `AGENT_VERIFY`, `AGENT_ID`, `AGENT_WORKSPACE` environment variables
|
||||||
|
- Appends `$(openclaw path)/bin` to `PATH` (making `pcguard`, `secret-mgr`, and `ego-mgr` available)
|
||||||
|
|
||||||
|
### 5. safe-restart — Coordinated Restart (TypeScript)
|
||||||
|
|
||||||
|
Agent state management and coordinated gateway restart.
|
||||||
|
|
||||||
|
## 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
|
||||||
|
├── secret-mgr/ # Go secret manager binary
|
||||||
|
│ └── src/main.go
|
||||||
|
├── ego-mgr/ # Go agent identity manager binary
|
||||||
|
│ └── src/main.go
|
||||||
|
├── pcguard/ # Go exec guard binary
|
||||||
|
│ └── src/main.go
|
||||||
|
├── skills/ # Agent skills
|
||||||
|
│ ├── secret-mgr/SKILL.md
|
||||||
|
│ └── ego-mgr/SKILL.md
|
||||||
|
├── dist/padded-cell/ # Build output
|
||||||
|
├── install.mjs # Installer
|
||||||
|
└── README.md
|
||||||
|
```
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 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
|
||||||
|
```
|
||||||
|
|
||||||
|
The installer automatically generates a random 32-byte build secret (stored in `.build-secret`, gitignored) and injects it into `secret-mgr` at compile time. Subsequent builds reuse the same secret.
|
||||||
|
|
||||||
|
### Install paths
|
||||||
|
|
||||||
|
Priority: `--openclaw-profile-path` → `$OPENCLAW_PATH` → `~/.openclaw`
|
||||||
|
|
||||||
|
Binaries → `$(openclaw path)/bin/`, plugin files → `$(openclaw path)/plugins/padded-cell/`.
|
||||||
|
|
||||||
|
## Plugin Update Workflow (admin handoff)
|
||||||
|
|
||||||
|
When you rebuild PaddedCell (which generates a new build secret), existing encrypted data needs re-encryption:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. Before updating — export current build secret
|
||||||
|
~/.openclaw/bin/secret-mgr admin handoff
|
||||||
|
|
||||||
|
# 2. Rebuild & reinstall (generates new .build-secret)
|
||||||
|
rm .build-secret
|
||||||
|
node install.mjs
|
||||||
|
|
||||||
|
# 3. After updating — re-encrypt data with new secret
|
||||||
|
~/.openclaw/bin/secret-mgr admin init-from
|
||||||
|
|
||||||
|
# 4. Restart gateway
|
||||||
|
openclaw gateway restart
|
||||||
|
```
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Agent sets and gets private passwords (via pcexec)
|
||||||
|
secret-mgr set --key myservice --secret s3cret --username admin
|
||||||
|
secret-mgr get-secret --key myservice
|
||||||
|
secret-mgr get-username --key myservice
|
||||||
|
|
||||||
|
# Shared scope (.public)
|
||||||
|
secret-mgr set --public --key shared-api --secret s3cret
|
||||||
|
secret-mgr list --public
|
||||||
|
secret-mgr get-secret --public --key shared-api
|
||||||
|
|
||||||
|
# Use in shell commands (pcexec resolves and sanitizes)
|
||||||
|
curl -u "$(secret-mgr get-username --key myservice):$(secret-mgr get-secret --key myservice)" https://api.example.com
|
||||||
|
|
||||||
|
# Agent identity management (via pcexec)
|
||||||
|
ego-mgr add column name
|
||||||
|
ego-mgr set name "小智"
|
||||||
|
ego-mgr add public-column timezone --default UTC
|
||||||
|
ego-mgr show
|
||||||
|
```
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
MIT
|
||||||
136
README.zh-CN.md
Normal file
136
README.zh-CN.md
Normal file
@@ -0,0 +1,136 @@
|
|||||||
|
<div align="center">
|
||||||
|
|
||||||
|
[English](README.md) | [简体中文](README.zh-CN.md)
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
# PaddedCell
|
||||||
|
|
||||||
|
OpenClaw 插件:安全密码管理 + 安全执行 + 安全重启
|
||||||
|
|
||||||
|
## 功能模块
|
||||||
|
|
||||||
|
### 1. pass_mgr - 密码管理二进制 (Go)
|
||||||
|
|
||||||
|
使用 AES-256-GCM 加密,每个 agent 基于公私钥进行加/解密。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 初始化
|
||||||
|
pass_mgr admin init [--key-path <path>]
|
||||||
|
|
||||||
|
# 获取密码
|
||||||
|
pass_mgr get <key> [--username]
|
||||||
|
|
||||||
|
# 生成密码 (agent 可用)
|
||||||
|
pass_mgr generate <key> [--username <user>]
|
||||||
|
|
||||||
|
# 设置密码 (仅人类)
|
||||||
|
pass_mgr set <key> <password> [--username <user>]
|
||||||
|
|
||||||
|
# 删除密码
|
||||||
|
pass_mgr unset <key>
|
||||||
|
|
||||||
|
# 轮换密码
|
||||||
|
pass_mgr rotate <key>
|
||||||
|
```
|
||||||
|
|
||||||
|
**安全特性:**
|
||||||
|
- Agent 无法执行 `set` 操作(通过环境变量检测)
|
||||||
|
- 未初始化前所有操作报错
|
||||||
|
- Admin 密码泄露检测(监控 message/tool calling)
|
||||||
|
|
||||||
|
### 2. pcexec - 安全执行工具 (TypeScript)
|
||||||
|
|
||||||
|
与 OpenClaw 原生 exec 接口一致,自动处理 pass_mgr get 并脱敏输出。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { pcexec } from 'pcexec';
|
||||||
|
|
||||||
|
const result = await pcexec('echo $(pass_mgr get mypassword)', {
|
||||||
|
cwd: '/workspace',
|
||||||
|
timeout: 30000,
|
||||||
|
});
|
||||||
|
// result.stdout 中密码会被替换为 ######
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. safe-restart - 安全重启模块 (TypeScript)
|
||||||
|
|
||||||
|
提供 agent 状态管理和协调重启。
|
||||||
|
|
||||||
|
**Agent 状态:**
|
||||||
|
- `idle` - 空闲
|
||||||
|
- `busy` - 处理消息中
|
||||||
|
- `focus` - 专注模式(工作流)
|
||||||
|
- `freeze` - 冻结(不接受新消息)
|
||||||
|
- `pre-freeze` - 准备冻结
|
||||||
|
- `pre-freeze-focus` - 准备冻结(专注模式)
|
||||||
|
|
||||||
|
**API:**
|
||||||
|
- `POST /query-restart` - 查询重启就绪状态
|
||||||
|
- `POST /restart-result` - 报告重启结果
|
||||||
|
- `GET /status` - 获取所有状态
|
||||||
|
|
||||||
|
**Slash 命令:**
|
||||||
|
```
|
||||||
|
/padded-cell-ctrl status
|
||||||
|
/padded-cell-ctrl enable pass-mgr|safe-restart
|
||||||
|
/padded-cell-ctrl disable pass-mgr|safe-restart
|
||||||
|
```
|
||||||
|
|
||||||
|
## 项目结构
|
||||||
|
|
||||||
|
```
|
||||||
|
PaddedCell/
|
||||||
|
├── pass_mgr/ # Go 密码管理二进制
|
||||||
|
│ ├── src/
|
||||||
|
│ │ └── main.go
|
||||||
|
│ └── go.mod
|
||||||
|
├── pcexec/ # TypeScript 安全执行工具
|
||||||
|
│ ├── src/
|
||||||
|
│ │ └── index.ts
|
||||||
|
│ ├── package.json
|
||||||
|
│ └── tsconfig.json
|
||||||
|
├── safe-restart/ # TypeScript 安全重启模块
|
||||||
|
│ ├── src/
|
||||||
|
│ │ ├── index.ts
|
||||||
|
│ │ ├── status-manager.ts
|
||||||
|
│ │ ├── api.ts
|
||||||
|
│ │ ├── safe-restart.ts
|
||||||
|
│ │ └── slash-commands.ts
|
||||||
|
│ ├── package.json
|
||||||
|
│ └── tsconfig.json
|
||||||
|
├── docs/ # 文档
|
||||||
|
├── PROJECT_PLAN.md # 项目计划
|
||||||
|
├── AGENT_TASKS.md # 任务清单
|
||||||
|
├── README.md # 英文版本
|
||||||
|
└── README.zh-CN.md # 本文档 (简体中文)
|
||||||
|
```
|
||||||
|
|
||||||
|
## 安装
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 安装
|
||||||
|
node install.mjs --install
|
||||||
|
|
||||||
|
# 卸载
|
||||||
|
node install.mjs --uninstall
|
||||||
|
```
|
||||||
|
|
||||||
|
## 使用
|
||||||
|
|
||||||
|
### pass_mgr
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 初始化(首次使用前必须执行)
|
||||||
|
~/.openclaw/bin/pass_mgr admin init
|
||||||
|
|
||||||
|
# 设置密码
|
||||||
|
~/.openclaw/bin/pass_mgr set mykey mypassword
|
||||||
|
|
||||||
|
# 获取密码
|
||||||
|
~/.openclaw/bin/pass_mgr get mykey
|
||||||
|
```
|
||||||
|
|
||||||
|
## 许可证
|
||||||
|
|
||||||
|
MIT
|
||||||
16
achieve/NEW_FEAT.md
Normal file
16
achieve/NEW_FEAT.md
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
# New Features
|
||||||
|
|
||||||
|
## From TASKLIST
|
||||||
|
|
||||||
|
- Add AGENT_VERIFY env injection in pcexec: `AGENT_VERIFY="IF YOU ARE AN AGENT/MODEL, YOU SHOULD NEVER TOUCH THIS ENV VARIABLE"`.
|
||||||
|
- Add new Go binary (pcguard) to validate `AGENT_VERIFY`, `AGENT_ID`, `AGENT_WORKSPACE`.
|
||||||
|
- If AGENT_VERIFY mismatch or AGENT_ID/AGENT_WORKSPACE is empty, error: "PLEASE USE TOOL PCEXEC TO RUN THIS SCRIPT".
|
||||||
|
- Update README: 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.
|
||||||
|
|
||||||
|
## Additional Requirements
|
||||||
|
|
||||||
|
1. 入环境变量时修改 PATH,追加 `$(openclaw path)/bin`。
|
||||||
|
2. 重构项目结构:项目根目录下放 docs, plugin, scripts, pass_mgr。plugin 下放 commands, core, hooks, tools 目录以及 index.ts, openclaw.plugin.json 等;根据这个结构重构现在的 codebase。
|
||||||
|
3. 构建目录:dist/padded-cell。
|
||||||
|
4. 安装时把 dist/padded-cell 复制到 `$(openclaw path)/plugins/padded-cell` 并用此路径注册插件。
|
||||||
|
5. 安装脚本接受 --openclaw-profile-path 参数;可选所有 `$(openclaw path)` 路径,优先考虑该参数;若未提供则考虑 $OPENCLAW_PATH,若没有则用默认值 ~/.openclaw。
|
||||||
@@ -244,6 +244,56 @@ Request:
|
|||||||
- 任务分配清单
|
- 任务分配清单
|
||||||
- 测试用例列表
|
- 测试用例列表
|
||||||
|
|
||||||
|
## 6. 安装脚本
|
||||||
|
|
||||||
|
### 6.1 需求
|
||||||
|
提供统一的插件安装脚本 `install.mjs`,实现以下功能:
|
||||||
|
|
||||||
|
**检测与依赖**
|
||||||
|
- 检测系统平台 (Linux/macOS)
|
||||||
|
- 检测必要依赖 (Node.js, Go, openclaw CLI)
|
||||||
|
- 检测 openclaw 配置目录
|
||||||
|
|
||||||
|
**构建**
|
||||||
|
- 自动构建 pass_mgr Go 二进制
|
||||||
|
- 自动构建 pcexec TypeScript 模块
|
||||||
|
- 自动构建 safe-restart TypeScript 模块
|
||||||
|
|
||||||
|
**安装**
|
||||||
|
- 安装 pass_mgr 到系统 PATH (或 openclaw bin 目录)
|
||||||
|
- 安装 TypeScript 模块到 openclaw skills 目录
|
||||||
|
- 创建必要的配置文件和目录
|
||||||
|
|
||||||
|
**配置**
|
||||||
|
- 初始化 pass_mgr admin (引导用户设置 admin 密码)
|
||||||
|
- 配置环境变量
|
||||||
|
- 注册 safe-restart API 服务
|
||||||
|
|
||||||
|
**验证**
|
||||||
|
- 验证所有组件安装成功
|
||||||
|
- 输出安装摘要和下一步操作提示
|
||||||
|
|
||||||
|
### 6.2 使用方式
|
||||||
|
```bash
|
||||||
|
# 默认安装
|
||||||
|
node install.mjs
|
||||||
|
|
||||||
|
# 指定安装路径
|
||||||
|
node install.mjs --prefix /usr/local
|
||||||
|
|
||||||
|
# 仅构建不安装
|
||||||
|
node install.mjs --build-only
|
||||||
|
|
||||||
|
# 跳过依赖检测
|
||||||
|
node install.mjs --skip-check
|
||||||
|
|
||||||
|
# 卸载
|
||||||
|
node install.mjs --uninstall
|
||||||
|
|
||||||
|
# 从指定路径卸载
|
||||||
|
node install.mjs --uninstall --prefix /usr/local
|
||||||
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
> 更新日志:v0.1(基于当前需求整理)
|
> 更新日志:v0.1(基于当前需求整理)
|
||||||
279
achieve/REQUIREMENTS_EGO_MGR.md
Normal file
279
achieve/REQUIREMENTS_EGO_MGR.md
Normal file
@@ -0,0 +1,279 @@
|
|||||||
|
# PaddedCell 需求更新 — ego-mgr & 重命名
|
||||||
|
|
||||||
|
> 版本:v0.2
|
||||||
|
> 日期:2026-03-24
|
||||||
|
> 状态:待实现
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 重命名:pass_mgr → secret-mgr
|
||||||
|
|
||||||
|
### 1.1 范围
|
||||||
|
所有文档、代码、技能引用中的 `pass_mgr` 统一更名为 `secret-mgr`:
|
||||||
|
|
||||||
|
- 二进制文件名:`pass_mgr` → `secret-mgr`
|
||||||
|
- 命令引用:`pass_mgr <cmd>` → `secret-mgr <cmd>`
|
||||||
|
- 文档:README.md, PROJECT_PLAN.md, SKILL.md 等
|
||||||
|
- 技能目录:`skills/pass-mgr/` → `skills/secret-mgr/`
|
||||||
|
|
||||||
|
### 1.2 命令保持不变
|
||||||
|
```bash
|
||||||
|
secret-mgr list # List keys for current agent
|
||||||
|
secret-mgr get-secret --key <key> # Output secret
|
||||||
|
secret-mgr get-username --key <key> # Output username
|
||||||
|
secret-mgr set --key <key> --secret <s> [--username <u>] # Set entry
|
||||||
|
secret-mgr generate --key <key> [--username <u>] # Generate random secret
|
||||||
|
secret-mgr unset --key <key> # Delete entry
|
||||||
|
secret-mgr get <key> # Legacy (maps to get-secret)
|
||||||
|
secret-mgr admin handoff [file] # Export build secret
|
||||||
|
secret-mgr admin init-from [file] # Re-encrypt data
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 新增 ego-mgr 二进制(Go)
|
||||||
|
|
||||||
|
### 2.1 功能概述
|
||||||
|
`ego-mgr` 管理 Agent 的个人信息(名字、邮箱、出生日期等),支持:
|
||||||
|
- **Agent Scope 字段**:每个 Agent 独立存储,值可不同
|
||||||
|
- **Public Scope 字段**:全局共用,所有 Agent 共享同一值
|
||||||
|
|
||||||
|
### 2.2 数据存储
|
||||||
|
- **文件路径**:`~/.openclaw/ego.json`
|
||||||
|
- **格式**:JSON
|
||||||
|
- **Schema**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"columns": ["col1", "col2", "..."],
|
||||||
|
"public-columns": ["pub-col1", "pub-col2", "..."],
|
||||||
|
"public-scope": {
|
||||||
|
"pub-col1": "value1",
|
||||||
|
"pub-col2": "value2"
|
||||||
|
},
|
||||||
|
"agent-scope": {
|
||||||
|
"agent-id-1": {
|
||||||
|
"col1": "value-x",
|
||||||
|
"col2": "value-y"
|
||||||
|
},
|
||||||
|
"agent-id-2": {
|
||||||
|
"col1": "value-z"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.3 命令接口
|
||||||
|
|
||||||
|
#### 2.3.0 帮助
|
||||||
|
```bash
|
||||||
|
ego-mgr --help
|
||||||
|
```
|
||||||
|
输出命令使用说明和示例。
|
||||||
|
|
||||||
|
#### 2.3.1 增加字段
|
||||||
|
```bash
|
||||||
|
# Agent Scope 字段
|
||||||
|
ego-mgr add column <column-name> [--default <default-value>]
|
||||||
|
|
||||||
|
# Public Scope 字段
|
||||||
|
ego-mgr add public-column <column-name> [--default <default-value>]
|
||||||
|
```
|
||||||
|
- `--default`:可选,设置默认值(不设置则默认为空字符串)
|
||||||
|
- 字段已存在时返回错误
|
||||||
|
|
||||||
|
### 2.3.2 删除字段
|
||||||
|
```bash
|
||||||
|
ego-mgr delete <column-name>
|
||||||
|
```
|
||||||
|
- 删除指定字段及其所有值(包括 `public-scope` 和所有 `agent-scope` 中的值)
|
||||||
|
- 字段不存在时返回错误
|
||||||
|
|
||||||
|
#### 2.3.3 设置字段值
|
||||||
|
```bash
|
||||||
|
ego-mgr set <column-name> <value>
|
||||||
|
```
|
||||||
|
- 字段必须已存在(通过 `add column` 或 `add public-column` 创建)
|
||||||
|
- 字段不存在时返回错误
|
||||||
|
- 根据字段类型自动写入 `agent-scope` 或 `public-scope`
|
||||||
|
|
||||||
|
#### 2.3.4 查询字段
|
||||||
|
```bash
|
||||||
|
# 获取单个字段值
|
||||||
|
ego-mgr get <column-name>
|
||||||
|
|
||||||
|
# 列出所有字段和值(先 Public 后 Agent Scope)
|
||||||
|
ego-mgr show
|
||||||
|
|
||||||
|
# 仅列出字段名(先 Public 后 Agent Scope)
|
||||||
|
ego-mgr list columns
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.4 输出示例
|
||||||
|
|
||||||
|
#### ego-mgr show
|
||||||
|
```
|
||||||
|
pub-col1: val1
|
||||||
|
pub-col2: val2
|
||||||
|
...
|
||||||
|
col1: valx
|
||||||
|
col2: valy
|
||||||
|
```
|
||||||
|
|
||||||
|
#### ego-mgr list columns
|
||||||
|
```
|
||||||
|
pub-col1
|
||||||
|
pub-col2
|
||||||
|
...
|
||||||
|
col1
|
||||||
|
col2
|
||||||
|
```
|
||||||
|
|
||||||
|
#### ego-mgr get <column>
|
||||||
|
```
|
||||||
|
<value>
|
||||||
|
```
|
||||||
|
(仅输出值,无额外格式)
|
||||||
|
|
||||||
|
### 2.5 安全约束
|
||||||
|
- **必须由 pcexec 调用**:检测到非 pcexec 环境(缺少 `AGENT_VERIFY` 等环境变量)时拒绝执行
|
||||||
|
- **Agent 隔离**:Agent 只能读写自己的 `agent-scope` 字段,不能访问其他 Agent 的数据
|
||||||
|
- **Public Scope 读取**:所有 Agent 可读取 `public-scope`
|
||||||
|
|
||||||
|
### 2.6 字段命名规则
|
||||||
|
- **字符限制**:无限制(允许空格、特殊字符)
|
||||||
|
- **长度限制**:无限制
|
||||||
|
- **大小写**:区分大小写
|
||||||
|
- **唯一性**:public-column 和 column 名字不能重复(全局唯一)
|
||||||
|
|
||||||
|
### 2.7 初始化逻辑
|
||||||
|
- `ego.json` 不存在时,由 PaddedCell 安装脚本自动创建空结构:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"columns": [],
|
||||||
|
"public-columns": [],
|
||||||
|
"public-scope": {},
|
||||||
|
"agent-scope": {}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.8 并发安全
|
||||||
|
- 写操作(`add`, `delete`, `set`)必须使用文件锁,防止多 Agent 并发写入导致数据损坏
|
||||||
|
- 读操作(`get`, `show`, `list columns`)无需锁
|
||||||
|
|
||||||
|
### 2.9 Agent 自动注册
|
||||||
|
- **读/写操作时**:如果当前 `agent-id` 不存在于 `agent-scope` 中,自动创建空条目:
|
||||||
|
```json
|
||||||
|
"agent-scope": {
|
||||||
|
"new-agent-id": {}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
- **字段验证**:如果 `column-name` 不存在于 `columns` 或 `public-columns` 中,返回错误(退出码 2)
|
||||||
|
|
||||||
|
### 2.10 错误退出码
|
||||||
|
| 退出码 | 含义 |
|
||||||
|
|--------|------|
|
||||||
|
| 0 | 成功 |
|
||||||
|
| 1 | 参数错误 / 用法错误 |
|
||||||
|
| 2 | 字段不存在(column-name 不在 columns 或 public-columns 中) |
|
||||||
|
| 3 | 字段已存在 |
|
||||||
|
| 4 | 权限错误(非 pcexec 环境 / Agent 越权) |
|
||||||
|
| 5 | 文件锁获取失败 |
|
||||||
|
| 6 | JSON 解析/写入错误 |
|
||||||
|
|
||||||
|
### 2.11 值的大小限制
|
||||||
|
- 单字段值长度无限制
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 新增 ego-mgr Skill
|
||||||
|
|
||||||
|
### 3.1 Skill 路径
|
||||||
|
`~/.openclaw/skills/ego-mgr/SKILL.md`
|
||||||
|
|
||||||
|
### 3.2 Skill 功能
|
||||||
|
- 指导 Agent 正确使用 `ego-mgr` 命令
|
||||||
|
- 说明字段管理流程(先 `add column`,再 `set`)
|
||||||
|
- 提供常见用例(设置名字、邮箱、时区等)
|
||||||
|
|
||||||
|
### 3.3 触发条件
|
||||||
|
- 用户请求管理 Agent 个人信息
|
||||||
|
- 用户询问 ego-mgr 用法
|
||||||
|
- 需要存储/读取 Agent 配置信息
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 依赖关系
|
||||||
|
|
||||||
|
```
|
||||||
|
+------------------+
|
||||||
|
| pcexec |
|
||||||
|
+--------+---------+
|
||||||
|
|
|
||||||
|
v
|
||||||
|
+--------+---------+ +------------------+
|
||||||
|
| ego-mgr |<----| ~.openclaw/ |
|
||||||
|
| secret-mgr | | ego.json |
|
||||||
|
+------------------+ +------------------+
|
||||||
|
```
|
||||||
|
|
||||||
|
- `ego-mgr` 和 `secret-mgr` 都必须通过 `pcexec` 调用
|
||||||
|
- `pcexec` 负责:
|
||||||
|
- 注入环境变量(`AGENT_VERIFY`, `AGENT_ID`, `AGENT_WORKSPACE`)
|
||||||
|
- 解析并脱敏敏感信息
|
||||||
|
- 验证执行上下文
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 待确认事项
|
||||||
|
|
||||||
|
1. **字段类型**:是否支持字段类型约束(如 email、date、number)?
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 实现任务清单
|
||||||
|
|
||||||
|
### M1:重命名 pass_mgr → secret-mgr & 初始化 ego.json
|
||||||
|
- [ ] 重命名二进制文件
|
||||||
|
- [ ] 更新所有文档引用
|
||||||
|
- [ ] 更新 Skill 目录和引用
|
||||||
|
- [ ] 更新 install.mjs 安装脚本
|
||||||
|
- [ ] install.mjs 自动创建空 `ego.json` 结构
|
||||||
|
|
||||||
|
### M1.5:pass_mgr → secret-mgr 数据迁移
|
||||||
|
**迁移步骤**:
|
||||||
|
1. 删除旧的 `pass_mgr` 前,执行:`pass_mgr admin handoff`(导出当前 build secret)
|
||||||
|
2. 安装新的 `secret-mgr` 后,执行:`secret-mgr admin init-from`(用新 secret 重新加密数据)
|
||||||
|
3. 重启 gateway:`openclaw gateway restart`
|
||||||
|
|
||||||
|
### M2:实现 ego-mgr 二进制
|
||||||
|
- [ ] 设计 JSON Schema 和文件结构
|
||||||
|
- [ ] 实现 `--help`
|
||||||
|
- [ ] 实现 `add column` / `add public-column`
|
||||||
|
- [ ] 实现 `delete`
|
||||||
|
- [ ] 实现 `set`
|
||||||
|
- [ ] 实现 `get` / `show` / `list columns`
|
||||||
|
- [ ] 实现 pcexec 环境检测
|
||||||
|
- [ ] 实现 Agent 隔离逻辑
|
||||||
|
- [ ] 实现文件锁(并发安全)
|
||||||
|
- [ ] 实现错误退出码
|
||||||
|
|
||||||
|
### M3:编写 ego-mgr Skill
|
||||||
|
- [ ] 创建 `skills/ego-mgr/SKILL.md`
|
||||||
|
- [ ] 编写使用示例
|
||||||
|
- [ ] 集成到 OpenClaw Skill 系统
|
||||||
|
|
||||||
|
### M4:集成测试
|
||||||
|
- [ ] 测试 ego-mgr 与 pcexec 集成
|
||||||
|
- [ ] 测试多 Agent 隔离
|
||||||
|
- [ ] 测试 Public/Agent Scope 分离
|
||||||
|
- [ ] 测试边界条件(字段不存在、重复添加等)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 验收标准
|
||||||
|
|
||||||
|
1. `secret-mgr` 所有原有功能正常工作,文档更新完成
|
||||||
|
2. `ego-mgr` 支持完整的 CRUD 操作
|
||||||
|
3. `ego-mgr` 只能通过 `pcexec` 调用
|
||||||
|
4. Agent 数据隔离正确,Public Scope 共享正确
|
||||||
|
5. Skill 文档清晰,Agent 能独立使用
|
||||||
62
achieve/TEST_PLAN.md
Normal file
62
achieve/TEST_PLAN.md
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
# PaddedCell 测试计划 - 2026-03-05
|
||||||
|
|
||||||
|
## 当前状态
|
||||||
|
- 代码已推送到 `dev/zhi` 分支 (commit: 28af11c)
|
||||||
|
- 已修复构建错误
|
||||||
|
- 安装脚本已更新
|
||||||
|
|
||||||
|
## 测试步骤及结果
|
||||||
|
|
||||||
|
### 1. 安装脚本测试 ✅
|
||||||
|
```bash
|
||||||
|
cd /root/.openclaw/workspace-developer/PaddedCell
|
||||||
|
node install.mjs --verbose
|
||||||
|
```
|
||||||
|
|
||||||
|
**结果**: 构建成功,但安装未完成(等待用户确认安装路径)
|
||||||
|
|
||||||
|
### 2. 依赖安装 ✅
|
||||||
|
- Go v1.22.2 已安装
|
||||||
|
- Node.js v22.x 可用
|
||||||
|
|
||||||
|
### 3. 构建测试 ✅
|
||||||
|
- pass_mgr Go 二进制编译成功
|
||||||
|
- pcexec TypeScript 构建成功
|
||||||
|
- safe-restart TypeScript 构建成功
|
||||||
|
|
||||||
|
### 4. 修复的构建错误
|
||||||
|
|
||||||
|
#### pass_mgr (Go)
|
||||||
|
- **问题**: `username` string 变量用作 boolean 判断
|
||||||
|
- **修复**: 使用 `BoolVar` 定义 `--username` flag
|
||||||
|
|
||||||
|
#### pcexec (TypeScript)
|
||||||
|
- **问题**: `process.env` 类型不匹配 `Record<string, string>`
|
||||||
|
- **修复**: 循环复制并过滤 undefined 值
|
||||||
|
|
||||||
|
#### safe-restart (TypeScript)
|
||||||
|
- **问题**: `fetch` 返回 `unknown` 类型
|
||||||
|
- **修复**: 添加类型断言 `as { status: string }`
|
||||||
|
|
||||||
|
## 下一步测试
|
||||||
|
|
||||||
|
需要完成的测试:
|
||||||
|
1. 完整安装流程测试(需要确认安装路径)
|
||||||
|
2. pass_mgr 功能测试(init/get/set/generate/rotate)
|
||||||
|
3. pcexec 密码脱敏测试
|
||||||
|
4. safe-restart API 测试
|
||||||
|
|
||||||
|
## 重启后计划
|
||||||
|
|
||||||
|
如果测试过程中需要重启 OpenClaw gateway,重启后我需要:
|
||||||
|
|
||||||
|
1. **验证环境变量** - 检查 PATH 和 PADDEDCELL_SKILLS_DIR 是否正确设置
|
||||||
|
2. **继续安装测试** - 重新运行 install.mjs 或验证已安装组件
|
||||||
|
3. **功能测试** - 测试 pass_mgr/pcexec/safe-restart 是否正常工作
|
||||||
|
4. **记录结果** - 更新此文件,记录测试通过/失败项
|
||||||
|
|
||||||
|
## 当前阻塞点
|
||||||
|
|
||||||
|
**无阻塞** - 构建已通过,可以开始完整安装测试。
|
||||||
|
|
||||||
|
**建议**: 运行 `node install.mjs` 完成安装,然后进行功能测试。
|
||||||
10
ego-mgr/go.mod
Normal file
10
ego-mgr/go.mod
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
module ego-mgr
|
||||||
|
|
||||||
|
go 1.24.0
|
||||||
|
|
||||||
|
require github.com/spf13/cobra v1.8.0
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||||
|
github.com/spf13/pflag v1.0.5 // indirect
|
||||||
|
)
|
||||||
10
ego-mgr/go.sum
Normal file
10
ego-mgr/go.sum
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
||||||
|
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||||
|
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||||
|
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||||
|
github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0=
|
||||||
|
github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho=
|
||||||
|
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
||||||
|
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
517
ego-mgr/src/main.go
Normal file
517
ego-mgr/src/main.go
Normal file
@@ -0,0 +1,517 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
expectedAgentVerify = "IF YOU ARE AN AGENT/MODEL, YOU SHOULD NEVER TOUCH THIS ENV VARIABLE"
|
||||||
|
egoFileName = "ego.json"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Exit codes per spec
|
||||||
|
const (
|
||||||
|
ExitSuccess = 0
|
||||||
|
ExitUsageError = 1
|
||||||
|
ExitColumnNotFound = 2
|
||||||
|
ExitColumnExists = 3
|
||||||
|
ExitPermission = 4
|
||||||
|
ExitLockFailed = 5
|
||||||
|
ExitJSONError = 6
|
||||||
|
ExitNotFound = 7
|
||||||
|
)
|
||||||
|
|
||||||
|
// EgoData is the on-disk JSON structure
|
||||||
|
type EgoData struct {
|
||||||
|
Columns []string `json:"columns"`
|
||||||
|
PublicColumns []string `json:"public-columns"`
|
||||||
|
PublicScope map[string]string `json:"public-scope"`
|
||||||
|
AgentScope map[string]map[string]string `json:"agent-scope"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolveOpenclawPath() string {
|
||||||
|
if p := os.Getenv("OPENCLAW_PATH"); p != "" {
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
home, _ := os.UserHomeDir()
|
||||||
|
return filepath.Join(home, ".openclaw")
|
||||||
|
}
|
||||||
|
|
||||||
|
func egoFilePath() string {
|
||||||
|
return filepath.Join(resolveOpenclawPath(), egoFileName)
|
||||||
|
}
|
||||||
|
|
||||||
|
func currentAgentID() string {
|
||||||
|
return os.Getenv("AGENT_ID")
|
||||||
|
}
|
||||||
|
|
||||||
|
func requirePcguard() {
|
||||||
|
if os.Getenv("AGENT_VERIFY") != expectedAgentVerify {
|
||||||
|
fmt.Fprintln(os.Stderr, "Error: must be invoked via pcexec (AGENT_VERIFY mismatch)")
|
||||||
|
os.Exit(ExitPermission)
|
||||||
|
}
|
||||||
|
if os.Getenv("AGENT_ID") == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, "Error: AGENT_ID not set — must be invoked via pcexec")
|
||||||
|
os.Exit(ExitPermission)
|
||||||
|
}
|
||||||
|
if os.Getenv("AGENT_WORKSPACE") == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, "Error: AGENT_WORKSPACE not set — must be invoked via pcexec")
|
||||||
|
os.Exit(ExitPermission)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// readEgoData reads and parses the ego.json file
|
||||||
|
func readEgoData() (*EgoData, error) {
|
||||||
|
fp := egoFilePath()
|
||||||
|
raw, err := os.ReadFile(fp)
|
||||||
|
if err != nil {
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
// Return empty structure
|
||||||
|
return &EgoData{
|
||||||
|
Columns: []string{},
|
||||||
|
PublicColumns: []string{},
|
||||||
|
PublicScope: map[string]string{},
|
||||||
|
AgentScope: map[string]map[string]string{},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("failed to read %s: %w", fp, err)
|
||||||
|
}
|
||||||
|
var data EgoData
|
||||||
|
if err := json.Unmarshal(raw, &data); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to parse %s: %w", fp, err)
|
||||||
|
}
|
||||||
|
// Ensure maps are initialized
|
||||||
|
if data.PublicScope == nil {
|
||||||
|
data.PublicScope = map[string]string{}
|
||||||
|
}
|
||||||
|
if data.AgentScope == nil {
|
||||||
|
data.AgentScope = map[string]map[string]string{}
|
||||||
|
}
|
||||||
|
if data.Columns == nil {
|
||||||
|
data.Columns = []string{}
|
||||||
|
}
|
||||||
|
if data.PublicColumns == nil {
|
||||||
|
data.PublicColumns = []string{}
|
||||||
|
}
|
||||||
|
return &data, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeEgoData writes ego data to ego.json with file locking
|
||||||
|
func writeEgoData(data *EgoData) error {
|
||||||
|
fp := egoFilePath()
|
||||||
|
|
||||||
|
// Acquire file lock
|
||||||
|
lockPath := fp + ".lock"
|
||||||
|
lockFile, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0600)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: cannot create lock file: %v\n", err)
|
||||||
|
os.Exit(ExitLockFailed)
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
lockFile.Close()
|
||||||
|
os.Remove(lockPath)
|
||||||
|
}()
|
||||||
|
|
||||||
|
if err := syscall.Flock(int(lockFile.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "Error: failed to acquire file lock (another process is writing)")
|
||||||
|
os.Exit(ExitLockFailed)
|
||||||
|
}
|
||||||
|
defer syscall.Flock(int(lockFile.Fd()), syscall.LOCK_UN)
|
||||||
|
|
||||||
|
raw, err := json.MarshalIndent(data, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to marshal JSON: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := os.WriteFile(fp, append(raw, '\n'), 0644); err != nil {
|
||||||
|
return fmt.Errorf("failed to write %s: %w", fp, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ensureAgent ensures the current agent has an entry in agent-scope
|
||||||
|
func ensureAgent(data *EgoData) {
|
||||||
|
agentID := currentAgentID()
|
||||||
|
if _, ok := data.AgentScope[agentID]; !ok {
|
||||||
|
data.AgentScope[agentID] = map[string]string{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// isPublicColumn checks if a column name is in public-columns
|
||||||
|
func isPublicColumn(data *EgoData, name string) bool {
|
||||||
|
for _, c := range data.PublicColumns {
|
||||||
|
if c == name {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// isAgentColumn checks if a column name is in columns (agent scope)
|
||||||
|
func isAgentColumn(data *EgoData, name string) bool {
|
||||||
|
for _, c := range data.Columns {
|
||||||
|
if c == name {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// columnExists checks if a column name exists in either scope
|
||||||
|
func columnExists(data *EgoData, name string) bool {
|
||||||
|
return isPublicColumn(data, name) || isAgentColumn(data, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
rootCmd := &cobra.Command{
|
||||||
|
Use: "ego-mgr",
|
||||||
|
Short: "Agent identity/profile manager for OpenClaw",
|
||||||
|
Long: `ego-mgr manages agent personal information (name, email, timezone, etc.).
|
||||||
|
|
||||||
|
Fields can be Agent Scope (per-agent) or Public Scope (shared by all agents).
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
ego-mgr add column name
|
||||||
|
ego-mgr add public-column timezone --default UTC
|
||||||
|
ego-mgr set name "小智"
|
||||||
|
ego-mgr get name
|
||||||
|
ego-mgr show
|
||||||
|
ego-mgr list columns
|
||||||
|
ego-mgr delete name`,
|
||||||
|
}
|
||||||
|
|
||||||
|
rootCmd.AddCommand(addCmd(), deleteCmd(), setCmd(), getCmd(), showCmd(), listCmd(), lookupCmd())
|
||||||
|
|
||||||
|
if err := rootCmd.Execute(); err != nil {
|
||||||
|
os.Exit(ExitUsageError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func addCmd() *cobra.Command {
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "add",
|
||||||
|
Short: "Add a new column",
|
||||||
|
}
|
||||||
|
cmd.AddCommand(addColumnCmd(), addPublicColumnCmd())
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func addColumnCmd() *cobra.Command {
|
||||||
|
var defaultVal string
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "column <column-name>",
|
||||||
|
Short: "Add an agent-scope column",
|
||||||
|
Args: cobra.ExactArgs(1),
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
requirePcguard()
|
||||||
|
colName := args[0]
|
||||||
|
|
||||||
|
data, err := readEgoData()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(ExitJSONError)
|
||||||
|
}
|
||||||
|
|
||||||
|
if columnExists(data, colName) {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: column '%s' already exists\n", colName)
|
||||||
|
os.Exit(ExitColumnExists)
|
||||||
|
}
|
||||||
|
|
||||||
|
data.Columns = append(data.Columns, colName)
|
||||||
|
|
||||||
|
// Set default value for all existing agents
|
||||||
|
if defaultVal != "" {
|
||||||
|
for agentID := range data.AgentScope {
|
||||||
|
data.AgentScope[agentID][colName] = defaultVal
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := writeEgoData(data); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(ExitJSONError)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
cmd.Flags().StringVar(&defaultVal, "default", "", "Default value for the column")
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func addPublicColumnCmd() *cobra.Command {
|
||||||
|
var defaultVal string
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "public-column <column-name>",
|
||||||
|
Short: "Add a public-scope column",
|
||||||
|
Args: cobra.ExactArgs(1),
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
requirePcguard()
|
||||||
|
colName := args[0]
|
||||||
|
|
||||||
|
data, err := readEgoData()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(ExitJSONError)
|
||||||
|
}
|
||||||
|
|
||||||
|
if columnExists(data, colName) {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: column '%s' already exists\n", colName)
|
||||||
|
os.Exit(ExitColumnExists)
|
||||||
|
}
|
||||||
|
|
||||||
|
data.PublicColumns = append(data.PublicColumns, colName)
|
||||||
|
if defaultVal != "" {
|
||||||
|
data.PublicScope[colName] = defaultVal
|
||||||
|
} else {
|
||||||
|
data.PublicScope[colName] = ""
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := writeEgoData(data); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(ExitJSONError)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
cmd.Flags().StringVar(&defaultVal, "default", "", "Default value for the column")
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func deleteCmd() *cobra.Command {
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "delete <column-name>",
|
||||||
|
Short: "Delete a column and all its values",
|
||||||
|
Args: cobra.ExactArgs(1),
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
requirePcguard()
|
||||||
|
colName := args[0]
|
||||||
|
|
||||||
|
data, err := readEgoData()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(ExitJSONError)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !columnExists(data, colName) {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: column '%s' does not exist\n", colName)
|
||||||
|
os.Exit(ExitColumnNotFound)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove from public-columns if present
|
||||||
|
if isPublicColumn(data, colName) {
|
||||||
|
newCols := []string{}
|
||||||
|
for _, c := range data.PublicColumns {
|
||||||
|
if c != colName {
|
||||||
|
newCols = append(newCols, c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
data.PublicColumns = newCols
|
||||||
|
delete(data.PublicScope, colName)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove from agent columns if present
|
||||||
|
if isAgentColumn(data, colName) {
|
||||||
|
newCols := []string{}
|
||||||
|
for _, c := range data.Columns {
|
||||||
|
if c != colName {
|
||||||
|
newCols = append(newCols, c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
data.Columns = newCols
|
||||||
|
// Remove from all agent scopes
|
||||||
|
for agentID := range data.AgentScope {
|
||||||
|
delete(data.AgentScope[agentID], colName)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := writeEgoData(data); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(ExitJSONError)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func setCmd() *cobra.Command {
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "set <column-name> <value>",
|
||||||
|
Short: "Set a field value",
|
||||||
|
Args: cobra.ExactArgs(2),
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
requirePcguard()
|
||||||
|
colName := args[0]
|
||||||
|
value := args[1]
|
||||||
|
|
||||||
|
data, err := readEgoData()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(ExitJSONError)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !columnExists(data, colName) {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: column '%s' does not exist (use 'ego-mgr add column' or 'ego-mgr add public-column' first)\n", colName)
|
||||||
|
os.Exit(ExitColumnNotFound)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Auto-register agent
|
||||||
|
ensureAgent(data)
|
||||||
|
|
||||||
|
if isPublicColumn(data, colName) {
|
||||||
|
data.PublicScope[colName] = value
|
||||||
|
} else {
|
||||||
|
agentID := currentAgentID()
|
||||||
|
data.AgentScope[agentID][colName] = value
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := writeEgoData(data); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(ExitJSONError)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func getCmd() *cobra.Command {
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "get <column-name>",
|
||||||
|
Short: "Get a field value",
|
||||||
|
Args: cobra.ExactArgs(1),
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
requirePcguard()
|
||||||
|
colName := args[0]
|
||||||
|
|
||||||
|
data, err := readEgoData()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(ExitJSONError)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !columnExists(data, colName) {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: column '%s' does not exist\n", colName)
|
||||||
|
os.Exit(ExitColumnNotFound)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Auto-register agent
|
||||||
|
ensureAgent(data)
|
||||||
|
|
||||||
|
if isPublicColumn(data, colName) {
|
||||||
|
fmt.Print(data.PublicScope[colName])
|
||||||
|
} else {
|
||||||
|
agentID := currentAgentID()
|
||||||
|
fmt.Print(data.AgentScope[agentID][colName])
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func showCmd() *cobra.Command {
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "show",
|
||||||
|
Short: "Show all fields and values",
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
requirePcguard()
|
||||||
|
|
||||||
|
data, err := readEgoData()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(ExitJSONError)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Auto-register agent
|
||||||
|
ensureAgent(data)
|
||||||
|
agentID := currentAgentID()
|
||||||
|
|
||||||
|
// Print public scope first
|
||||||
|
for _, col := range data.PublicColumns {
|
||||||
|
val := data.PublicScope[col]
|
||||||
|
fmt.Printf("%s: %s\n", col, val)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Then agent scope
|
||||||
|
for _, col := range data.Columns {
|
||||||
|
val := ""
|
||||||
|
if agentData, ok := data.AgentScope[agentID]; ok {
|
||||||
|
val = agentData[col]
|
||||||
|
}
|
||||||
|
fmt.Printf("%s: %s\n", col, val)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func listCmd() *cobra.Command {
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "list",
|
||||||
|
Short: "List information",
|
||||||
|
}
|
||||||
|
cmd.AddCommand(listColumnsCmd())
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func listColumnsCmd() *cobra.Command {
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "columns",
|
||||||
|
Short: "List all column names",
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
requirePcguard()
|
||||||
|
|
||||||
|
data, err := readEgoData()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(ExitJSONError)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Print public columns first
|
||||||
|
for _, col := range data.PublicColumns {
|
||||||
|
fmt.Println(col)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Then agent columns
|
||||||
|
for _, col := range data.Columns {
|
||||||
|
fmt.Println(col)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func lookupCmd() *cobra.Command {
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "lookup <username>",
|
||||||
|
Short: "Look up an agent ID by default-username",
|
||||||
|
Args: cobra.ExactArgs(1),
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
username := args[0]
|
||||||
|
|
||||||
|
data, err := readEgoData()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(ExitJSONError)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify default-username column exists
|
||||||
|
if !isAgentColumn(data, "default-username") {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: column 'default-username' does not exist\n")
|
||||||
|
os.Exit(ExitColumnNotFound)
|
||||||
|
}
|
||||||
|
|
||||||
|
for agentID, agentData := range data.AgentScope {
|
||||||
|
if agentData["default-username"] == username {
|
||||||
|
fmt.Print(agentID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: no agent found with default-username '%s'\n", username)
|
||||||
|
os.Exit(ExitNotFound)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
429
install.mjs
Executable file
429
install.mjs
Executable file
@@ -0,0 +1,429 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PaddedCell Plugin Installer v0.3.0
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { execSync } from 'child_process';
|
||||||
|
import {
|
||||||
|
existsSync,
|
||||||
|
mkdirSync,
|
||||||
|
copyFileSync,
|
||||||
|
chmodSync,
|
||||||
|
readdirSync,
|
||||||
|
rmSync,
|
||||||
|
readFileSync,
|
||||||
|
writeFileSync,
|
||||||
|
} from 'fs';
|
||||||
|
import { randomBytes } from 'crypto';
|
||||||
|
import { dirname, join, resolve } from 'path';
|
||||||
|
import { fileURLToPath } from 'url';
|
||||||
|
import { homedir, platform } from 'os';
|
||||||
|
|
||||||
|
const __filename = fileURLToPath(import.meta.url);
|
||||||
|
const __dirname = resolve(dirname(__filename));
|
||||||
|
|
||||||
|
const PLUGIN_NAME = 'padded-cell';
|
||||||
|
const SRC_DIST_DIR = join(__dirname, 'dist', PLUGIN_NAME);
|
||||||
|
|
||||||
|
const args = process.argv.slice(2);
|
||||||
|
const options = {
|
||||||
|
openclawProfilePath: null,
|
||||||
|
buildOnly: args.includes('--build-only'),
|
||||||
|
skipCheck: args.includes('--skip-check'),
|
||||||
|
verbose: args.includes('--verbose') || args.includes('-v'),
|
||||||
|
uninstall: args.includes('--uninstall'),
|
||||||
|
installOnly: args.includes('--install'),
|
||||||
|
};
|
||||||
|
|
||||||
|
const profileIdx = args.indexOf('--openclaw-profile-path');
|
||||||
|
if (profileIdx !== -1 && args[profileIdx + 1]) {
|
||||||
|
options.openclawProfilePath = resolve(args[profileIdx + 1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveOpenclawPath() {
|
||||||
|
if (options.openclawProfilePath) return options.openclawProfilePath;
|
||||||
|
if (process.env.OPENCLAW_PATH) return resolve(process.env.OPENCLAW_PATH);
|
||||||
|
return join(homedir(), '.openclaw');
|
||||||
|
}
|
||||||
|
|
||||||
|
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 exec(command, opts = {}) {
|
||||||
|
return execSync(command, {
|
||||||
|
cwd: __dirname,
|
||||||
|
stdio: opts.silent ? 'pipe' : 'inherit',
|
||||||
|
encoding: 'utf8',
|
||||||
|
...opts,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function getOpenclawConfig(key, def = undefined) {
|
||||||
|
try {
|
||||||
|
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 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 copyDir(src, dest) {
|
||||||
|
mkdirSync(dest, { recursive: true });
|
||||||
|
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;
|
||||||
|
entry.isDirectory() ? copyDir(s, d) : copyFileSync(s, d);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function detectEnvironment() {
|
||||||
|
logStep(1, 6, 'Detecting environment...');
|
||||||
|
const env = { platform: platform(), nodeVersion: null, goVersion: null };
|
||||||
|
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 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');
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureBuildSecret() {
|
||||||
|
const secretFile = join(__dirname, '.build-secret');
|
||||||
|
if (existsSync(secretFile)) {
|
||||||
|
const existing = readFileSync(secretFile, 'utf8').trim();
|
||||||
|
if (existing.length >= 32) {
|
||||||
|
logOk('Reusing existing build secret');
|
||||||
|
return existing;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const secret = randomBytes(32).toString('hex');
|
||||||
|
writeFileSync(secretFile, secret + '\n', { mode: 0o600 });
|
||||||
|
logOk('Generated new build secret');
|
||||||
|
return secret;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function build() {
|
||||||
|
logStep(3, 6, 'Building components...');
|
||||||
|
|
||||||
|
const buildSecret = ensureBuildSecret();
|
||||||
|
|
||||||
|
rmSync(SRC_DIST_DIR, { recursive: true, force: true });
|
||||||
|
|
||||||
|
log(' Building secret-mgr...', 'blue');
|
||||||
|
const pmDir = join(__dirname, 'secret-mgr');
|
||||||
|
exec('go mod tidy', { cwd: pmDir, silent: !options.verbose });
|
||||||
|
const ldflags = `-X main.buildSecret=${buildSecret}`;
|
||||||
|
exec(`go build -ldflags "${ldflags}" -o dist/secret-mgr src/main.go`, { cwd: pmDir, silent: !options.verbose });
|
||||||
|
chmodSync(join(pmDir, 'dist', 'secret-mgr'), 0o755);
|
||||||
|
logOk('secret-mgr');
|
||||||
|
|
||||||
|
log(' Building ego-mgr...', 'blue');
|
||||||
|
const emDir = join(__dirname, 'ego-mgr');
|
||||||
|
exec('go mod tidy', { cwd: emDir, silent: !options.verbose });
|
||||||
|
exec('go build -o dist/ego-mgr src/main.go', { cwd: emDir, silent: !options.verbose });
|
||||||
|
chmodSync(join(emDir, 'dist', 'ego-mgr'), 0o755);
|
||||||
|
logOk('ego-mgr');
|
||||||
|
|
||||||
|
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');
|
||||||
|
|
||||||
|
log(' Building lock-mgr...', 'blue');
|
||||||
|
const lmDir = join(__dirname, 'lock-mgr');
|
||||||
|
exec('go mod tidy', { cwd: lmDir, silent: !options.verbose });
|
||||||
|
exec('go build -o dist/lock-mgr .', { cwd: lmDir, silent: !options.verbose });
|
||||||
|
chmodSync(join(lmDir, 'dist', 'lock-mgr'), 0o755);
|
||||||
|
logOk('lock-mgr');
|
||||||
|
|
||||||
|
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');
|
||||||
|
|
||||||
|
const skillsSrc = join(__dirname, 'skills');
|
||||||
|
const skillsDist = join(SRC_DIST_DIR, 'skills');
|
||||||
|
if (existsSync(skillsSrc)) {
|
||||||
|
copyDir(skillsSrc, skillsDist);
|
||||||
|
logOk('skills copied to dist/padded-cell/skills');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handoffSecretIfPossible(openclawPath) {
|
||||||
|
// Check both old (pass_mgr) and new (secret-mgr) binary names
|
||||||
|
let passMgrPath = join(openclawPath, 'bin', 'secret-mgr');
|
||||||
|
if (!existsSync(passMgrPath)) {
|
||||||
|
passMgrPath = join(openclawPath, 'bin', 'pass_mgr');
|
||||||
|
}
|
||||||
|
if (!existsSync(passMgrPath)) return null;
|
||||||
|
|
||||||
|
const storeA = join(openclawPath, 'pc-pass-store');
|
||||||
|
const storeB = join(openclawPath, 'pc-secret-store');
|
||||||
|
if (!existsSync(storeA) && !existsSync(storeB)) return null;
|
||||||
|
|
||||||
|
const secretFile = join(openclawPath, 'pc-pass-store.secret');
|
||||||
|
try {
|
||||||
|
exec(`${passMgrPath} admin handoff ${secretFile}`, { silent: !options.verbose });
|
||||||
|
logOk(`handoff secret → ${secretFile}`);
|
||||||
|
return secretFile;
|
||||||
|
} catch (err) {
|
||||||
|
logWarn(`handoff failed: ${err.message}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearInstallTargets(openclawPath) {
|
||||||
|
const binDir = join(openclawPath, 'bin');
|
||||||
|
for (const name of ['pass_mgr', 'secret-mgr', 'ego-mgr', 'pcguard', 'lock-mgr']) {
|
||||||
|
const p = join(binDir, name);
|
||||||
|
if (existsSync(p)) { rmSync(p, { force: true }); logOk(`Removed ${p}`); }
|
||||||
|
}
|
||||||
|
|
||||||
|
const destDir = join(openclawPath, 'plugins', PLUGIN_NAME);
|
||||||
|
if (existsSync(destDir)) { rmSync(destDir, { recursive: true, force: true }); logOk(`Removed ${destDir}`); }
|
||||||
|
}
|
||||||
|
|
||||||
|
function cleanupConfig(openclawPath) {
|
||||||
|
const destDir = join(openclawPath, 'plugins', PLUGIN_NAME);
|
||||||
|
const skillsDir = join(openclawPath, 'skills');
|
||||||
|
try {
|
||||||
|
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}`);
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
|
||||||
|
const skillEntries = ['pcexec', 'safe-restart', 'safe_restart', 'pass-mgr', 'secret-mgr', 'ego-mgr'];
|
||||||
|
for (const sk of skillEntries) {
|
||||||
|
const p = join(skillsDir, sk);
|
||||||
|
if (existsSync(p)) {
|
||||||
|
rmSync(p, { recursive: true, force: true });
|
||||||
|
logOk(`Removed skill ${p}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
logWarn(`Config cleanup: ${err.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function install() {
|
||||||
|
if (options.buildOnly) { logStep(4, 6, 'Skipping install (--build-only)'); return null; }
|
||||||
|
logStep(4, 6, 'Installing...');
|
||||||
|
|
||||||
|
const openclawPath = resolveOpenclawPath();
|
||||||
|
const binDir = join(openclawPath, 'bin');
|
||||||
|
const pluginsDir = join(openclawPath, 'plugins');
|
||||||
|
const destDir = join(pluginsDir, PLUGIN_NAME);
|
||||||
|
const skillsDir = join(openclawPath, 'skills');
|
||||||
|
const distSkillsDir = join(SRC_DIST_DIR, 'skills');
|
||||||
|
|
||||||
|
log(` OpenClaw path: ${openclawPath}`, 'blue');
|
||||||
|
|
||||||
|
// update/reinstall path: remove old install first
|
||||||
|
if (existsSync(destDir) || existsSync(join(binDir, 'pass_mgr')) || existsSync(join(binDir, 'secret-mgr')) || existsSync(join(binDir, 'pcguard'))) {
|
||||||
|
logWarn('Existing install detected, uninstalling before install...');
|
||||||
|
handoffSecretIfPossible(openclawPath);
|
||||||
|
clearInstallTargets(openclawPath);
|
||||||
|
cleanupConfig(openclawPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (existsSync(destDir)) rmSync(destDir, { recursive: true, force: true });
|
||||||
|
copyDir(SRC_DIST_DIR, destDir);
|
||||||
|
|
||||||
|
copyFileSync(join(__dirname, 'plugin', 'openclaw.plugin.json'), join(destDir, 'openclaw.plugin.json'));
|
||||||
|
copyFileSync(join(__dirname, 'plugin', 'package.json'), join(destDir, 'package.json'));
|
||||||
|
logOk(`Plugin files → ${destDir}`);
|
||||||
|
|
||||||
|
exec('npm install --omit=dev', { cwd: destDir, silent: !options.verbose });
|
||||||
|
logOk('Runtime deps installed');
|
||||||
|
|
||||||
|
mkdirSync(binDir, { recursive: true });
|
||||||
|
const bins = [
|
||||||
|
{ name: 'secret-mgr', src: join(__dirname, 'secret-mgr', 'dist', 'secret-mgr') },
|
||||||
|
{ name: 'ego-mgr', src: join(__dirname, 'ego-mgr', 'dist', 'ego-mgr') },
|
||||||
|
{ name: 'pcguard', src: join(__dirname, 'pcguard', 'dist', 'pcguard') },
|
||||||
|
{ name: 'lock-mgr', src: join(__dirname, 'lock-mgr', 'dist', 'lock-mgr') },
|
||||||
|
];
|
||||||
|
for (const b of bins) {
|
||||||
|
const dest = join(binDir, b.name);
|
||||||
|
copyFileSync(b.src, dest);
|
||||||
|
chmodSync(dest, 0o755);
|
||||||
|
logOk(`${b.name} → ${dest}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only copy dist/padded-cell/skills to ~/.openclaw/skills
|
||||||
|
mkdirSync(skillsDir, { recursive: true });
|
||||||
|
if (existsSync(distSkillsDir)) {
|
||||||
|
for (const entry of readdirSync(distSkillsDir, { withFileTypes: true })) {
|
||||||
|
const s = join(distSkillsDir, entry.name);
|
||||||
|
const d = join(skillsDir, entry.name);
|
||||||
|
rmSync(d, { recursive: true, force: true });
|
||||||
|
entry.isDirectory() ? copyDir(s, d) : copyFileSync(s, d);
|
||||||
|
logOk(`skill synced → ${d}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initialize ego.json if it doesn't exist
|
||||||
|
const egoJsonPath = join(openclawPath, 'ego.json');
|
||||||
|
if (!existsSync(egoJsonPath)) {
|
||||||
|
const defaultEgo = {
|
||||||
|
columns: ['default-username', 'name', 'discord-id', 'email', 'role', 'position', 'date-of-birth', 'agent-id', 'gender'],
|
||||||
|
'public-columns': ['git-host', 'keycloak-host'],
|
||||||
|
'public-scope': {},
|
||||||
|
'agent-scope': {},
|
||||||
|
};
|
||||||
|
writeFileSync(egoJsonPath, JSON.stringify(defaultEgo, null, 2) + '\n', { mode: 0o644 });
|
||||||
|
logOk('Created ego.json');
|
||||||
|
} else {
|
||||||
|
logOk('ego.json already exists');
|
||||||
|
}
|
||||||
|
|
||||||
|
// if prior encrypted store exists, run init-from once new binary is installed
|
||||||
|
const hasStore = existsSync(join(openclawPath, 'pc-pass-store')) || existsSync(join(openclawPath, 'pc-secret-store'));
|
||||||
|
const secretFile = join(openclawPath, 'pc-pass-store.secret');
|
||||||
|
if (hasStore && existsSync(secretFile)) {
|
||||||
|
const passMgrPath = join(binDir, 'secret-mgr');
|
||||||
|
try {
|
||||||
|
exec(`${passMgrPath} admin init-from ${secretFile}`, { silent: !options.verbose });
|
||||||
|
logOk('init-from completed from handoff secret');
|
||||||
|
} catch (err) {
|
||||||
|
logWarn(`init-from failed: ${err.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { binDir, destDir };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function configure() {
|
||||||
|
if (options.buildOnly) { logStep(5, 6, 'Skipping config'); return; }
|
||||||
|
logStep(5, 6, 'Configuring OpenClaw...');
|
||||||
|
|
||||||
|
const openclawPath = resolveOpenclawPath();
|
||||||
|
const destDir = join(openclawPath, 'plugins', PLUGIN_NAME);
|
||||||
|
const secretMgrPath = join(openclawPath, 'bin', 'secret-mgr');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const paths = getOpenclawConfig('plugins.load.paths', []);
|
||||||
|
if (!paths.includes(destDir)) { paths.push(destDir); setOpenclawConfig('plugins.load.paths', paths); }
|
||||||
|
logOk(`plugins.load.paths includes ${destDir}`);
|
||||||
|
|
||||||
|
const allow = getOpenclawConfig('plugins.allow', []);
|
||||||
|
if (!allow.includes(PLUGIN_NAME)) { allow.push(PLUGIN_NAME); setOpenclawConfig('plugins.allow', allow); }
|
||||||
|
logOk(`plugins.allow includes ${PLUGIN_NAME}`);
|
||||||
|
|
||||||
|
const entryPath = `plugins.entries.${PLUGIN_NAME}`;
|
||||||
|
const existingEnabled = getOpenclawConfig(`${entryPath}.enabled`, undefined);
|
||||||
|
if (existingEnabled === undefined) setOpenclawConfig(`${entryPath}.enabled`, true);
|
||||||
|
|
||||||
|
const cfgPath = `${entryPath}.config`;
|
||||||
|
const existingCfgEnabled = getOpenclawConfig(`${cfgPath}.enabled`, undefined);
|
||||||
|
if (existingCfgEnabled === undefined) setOpenclawConfig(`${cfgPath}.enabled`, true);
|
||||||
|
|
||||||
|
const existingSecretMgr = getOpenclawConfig(`${cfgPath}.secretMgrPath`, undefined);
|
||||||
|
if (existingSecretMgr === undefined) setOpenclawConfig(`${cfgPath}.secretMgrPath`, secretMgrPath);
|
||||||
|
|
||||||
|
const existingProfile = getOpenclawConfig(`${cfgPath}.openclawProfilePath`, undefined);
|
||||||
|
if (existingProfile === undefined) setOpenclawConfig(`${cfgPath}.openclawProfilePath`, openclawPath);
|
||||||
|
|
||||||
|
logOk('Plugin entry configured (set missing defaults only)');
|
||||||
|
} catch (err) {
|
||||||
|
logWarn(`Config failed: ${err.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function summary() {
|
||||||
|
logStep(6, 6, 'Done!');
|
||||||
|
console.log('');
|
||||||
|
log('╔══════════════════════════════════════════════╗', 'cyan');
|
||||||
|
log('║ PaddedCell v0.3.0 Install Complete ║', 'cyan');
|
||||||
|
log('╚══════════════════════════════════════════════╝', 'cyan');
|
||||||
|
|
||||||
|
if (options.buildOnly) {
|
||||||
|
log('\nBuild-only — binaries not installed.', 'yellow');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('');
|
||||||
|
log('Next steps:', 'blue');
|
||||||
|
log(' 1. openclaw gateway restart', 'cyan');
|
||||||
|
console.log('');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function uninstall() {
|
||||||
|
log('Uninstalling PaddedCell...', 'cyan');
|
||||||
|
const openclawPath = resolveOpenclawPath();
|
||||||
|
handoffSecretIfPossible(openclawPath);
|
||||||
|
clearInstallTargets(openclawPath);
|
||||||
|
cleanupConfig(openclawPath);
|
||||||
|
log('\nRun: openclaw gateway restart', 'yellow');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
console.log('');
|
||||||
|
log('╔══════════════════════════════════════════════╗', 'cyan');
|
||||||
|
log('║ PaddedCell Plugin Installer v0.3.0 ║', 'cyan');
|
||||||
|
log('╚══════════════════════════════════════════════╝', 'cyan');
|
||||||
|
console.log('');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const env = detectEnvironment();
|
||||||
|
|
||||||
|
if (options.uninstall) {
|
||||||
|
await uninstall();
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
checkDeps(env);
|
||||||
|
await build();
|
||||||
|
|
||||||
|
if (!options.buildOnly) {
|
||||||
|
await install();
|
||||||
|
await configure();
|
||||||
|
}
|
||||||
|
|
||||||
|
summary();
|
||||||
|
} catch (err) {
|
||||||
|
log(`\nInstallation failed: ${err.message}`, 'red');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
main();
|
||||||
3
lock-mgr/go.mod
Normal file
3
lock-mgr/go.mod
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
module lock-mgr
|
||||||
|
|
||||||
|
go 1.24.0
|
||||||
380
lock-mgr/main.go
Normal file
380
lock-mgr/main.go
Normal file
@@ -0,0 +1,380 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"path/filepath"
|
||||||
|
"sync"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type LockEntry struct {
|
||||||
|
Locked bool `json:"locked"`
|
||||||
|
Key string `json:"key,omitempty"`
|
||||||
|
Time string `json:"time,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type LockFile map[string]*LockEntry
|
||||||
|
|
||||||
|
// heldLock tracks the meta-lock currently held by this process so it can be
|
||||||
|
// released on panic, signal, or any other unexpected exit.
|
||||||
|
var (
|
||||||
|
heldMu sync.Mutex
|
||||||
|
heldMgrPath string
|
||||||
|
heldMgrKey string
|
||||||
|
)
|
||||||
|
|
||||||
|
func setHeldLock(path, key string) {
|
||||||
|
heldMu.Lock()
|
||||||
|
heldMgrPath = path
|
||||||
|
heldMgrKey = key
|
||||||
|
heldMu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func clearHeldLock() {
|
||||||
|
heldMu.Lock()
|
||||||
|
heldMgrPath = ""
|
||||||
|
heldMgrKey = ""
|
||||||
|
heldMu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
// cleanupMgrLock releases the meta-lock if this process still holds it.
|
||||||
|
// Safe to call multiple times.
|
||||||
|
func cleanupMgrLock() {
|
||||||
|
heldMu.Lock()
|
||||||
|
path := heldMgrPath
|
||||||
|
key := heldMgrKey
|
||||||
|
heldMu.Unlock()
|
||||||
|
|
||||||
|
if path == "" || key == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
lf, err := readLockFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
entry := lf[path]
|
||||||
|
if entry != nil && entry.Key == key {
|
||||||
|
delete(lf, path)
|
||||||
|
_ = writeLockFile(path, lf)
|
||||||
|
}
|
||||||
|
clearHeldLock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func generateUUID() (string, error) {
|
||||||
|
b := make([]byte, 16)
|
||||||
|
if _, err := rand.Read(b); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
b[6] = (b[6] & 0x0f) | 0x40 // version 4
|
||||||
|
b[8] = (b[8] & 0x3f) | 0x80 // variant bits
|
||||||
|
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func readLockFile(path string) (LockFile, error) {
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
return make(LockFile), nil
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("read lock file: %w", err)
|
||||||
|
}
|
||||||
|
if len(data) == 0 {
|
||||||
|
return make(LockFile), nil
|
||||||
|
}
|
||||||
|
var lf LockFile
|
||||||
|
if err := json.Unmarshal(data, &lf); err != nil {
|
||||||
|
return make(LockFile), nil
|
||||||
|
}
|
||||||
|
if lf == nil {
|
||||||
|
return make(LockFile), nil
|
||||||
|
}
|
||||||
|
return lf, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeLockFile(path string, lf LockFile) error {
|
||||||
|
data, err := json.MarshalIndent(lf, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("marshal lock file: %w", err)
|
||||||
|
}
|
||||||
|
return os.WriteFile(path, data, 0644)
|
||||||
|
}
|
||||||
|
|
||||||
|
// acquireMgrLock implements steps 3-8: acquire the meta-lock on the JSON file itself.
|
||||||
|
// Returns the mgr-key on success.
|
||||||
|
func acquireMgrLock(mgrPath string) (string, error) {
|
||||||
|
// Step 3: generate mgr-key once
|
||||||
|
mgrKey, err := generateUUID()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
for {
|
||||||
|
// Step 4: record current time
|
||||||
|
startTime := time.Now()
|
||||||
|
|
||||||
|
// Steps 5-6: spin until the meta-lock is free or owned by us
|
||||||
|
for {
|
||||||
|
lf, err := readLockFile(mgrPath)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
entry := lf[mgrPath]
|
||||||
|
if entry == nil || !entry.Locked || entry.Key == mgrKey {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if time.Since(startTime) > 5*time.Second {
|
||||||
|
return "", fmt.Errorf("timeout waiting to acquire manager lock")
|
||||||
|
}
|
||||||
|
time.Sleep(100 * time.Millisecond)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 7: write locked=true, key=mgrKey
|
||||||
|
lf, err := readLockFile(mgrPath)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if lf[mgrPath] == nil {
|
||||||
|
lf[mgrPath] = &LockEntry{}
|
||||||
|
}
|
||||||
|
lf[mgrPath].Locked = true
|
||||||
|
lf[mgrPath].Key = mgrKey
|
||||||
|
if err := writeLockFile(mgrPath, lf); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 8: verify we actually won the race
|
||||||
|
lf2, err := readLockFile(mgrPath)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if lf2[mgrPath] != nil && lf2[mgrPath].Key == mgrKey {
|
||||||
|
setHeldLock(mgrPath, mgrKey)
|
||||||
|
return mgrKey, nil
|
||||||
|
}
|
||||||
|
// Lost the race; go back to step 4 (keep same mgrKey, reset timer)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// releaseMgrLock removes the meta-lock entry and writes the file.
|
||||||
|
func releaseMgrLock(mgrPath string) error {
|
||||||
|
lf, err := readLockFile(mgrPath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
delete(lf, mgrPath)
|
||||||
|
err = writeLockFile(mgrPath, lf)
|
||||||
|
if err == nil {
|
||||||
|
clearHeldLock()
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func cmdAcquire(mgrPath, filePath, key string) error {
|
||||||
|
// Steps 3-8: acquire meta-lock
|
||||||
|
if _, err := acquireMgrLock(mgrPath); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 9: record start time for file-lock wait timeout
|
||||||
|
startTime := time.Now()
|
||||||
|
|
||||||
|
for {
|
||||||
|
// Step 10: read current file lock state
|
||||||
|
lf, err := readLockFile(mgrPath)
|
||||||
|
if err != nil {
|
||||||
|
_ = releaseMgrLock(mgrPath)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
entry := lf[filePath]
|
||||||
|
xLocked := entry != nil && entry.Locked
|
||||||
|
xKey := ""
|
||||||
|
if entry != nil {
|
||||||
|
xKey = entry.Key
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 11: if locked by someone else, wait and retry
|
||||||
|
if xLocked && xKey != key {
|
||||||
|
if time.Since(startTime) > 30*time.Second {
|
||||||
|
_ = releaseMgrLock(mgrPath)
|
||||||
|
return fmt.Errorf("timeout waiting to acquire lock on %s", filePath)
|
||||||
|
}
|
||||||
|
// Release meta-lock while sleeping so others can proceed
|
||||||
|
if err := releaseMgrLock(mgrPath); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
time.Sleep(1 * time.Second)
|
||||||
|
// Re-acquire meta-lock before next read
|
||||||
|
if _, err := acquireMgrLock(mgrPath); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 12: not locked (or already owned by caller's key) — acquire
|
||||||
|
if lf[filePath] == nil {
|
||||||
|
lf[filePath] = &LockEntry{}
|
||||||
|
}
|
||||||
|
lf[filePath].Locked = true
|
||||||
|
lf[filePath].Key = key
|
||||||
|
lf[filePath].Time = time.Now().UTC().Format(time.RFC3339)
|
||||||
|
|
||||||
|
// Step 13: delete meta-lock entry and write atomically
|
||||||
|
delete(lf, mgrPath)
|
||||||
|
if err := writeLockFile(mgrPath, lf); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
clearHeldLock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func cmdRelease(mgrPath, filePath, key string) error {
|
||||||
|
// Steps 3-8: acquire meta-lock
|
||||||
|
if _, err := acquireMgrLock(mgrPath); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
lf, err := readLockFile(mgrPath)
|
||||||
|
if err != nil {
|
||||||
|
_ = releaseMgrLock(mgrPath)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
entry := lf[filePath]
|
||||||
|
xLocked := entry != nil && entry.Locked
|
||||||
|
xKey := ""
|
||||||
|
if entry != nil {
|
||||||
|
xKey = entry.Key
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 14: validate preconditions
|
||||||
|
if !xLocked {
|
||||||
|
_ = releaseMgrLock(mgrPath)
|
||||||
|
return fmt.Errorf("file %s is not locked", filePath)
|
||||||
|
}
|
||||||
|
if xKey != key {
|
||||||
|
_ = releaseMgrLock(mgrPath)
|
||||||
|
return fmt.Errorf("key does not match the lock key for %s", filePath)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 15: delete file lock and meta-lock, write
|
||||||
|
delete(lf, filePath)
|
||||||
|
delete(lf, mgrPath)
|
||||||
|
err = writeLockFile(mgrPath, lf)
|
||||||
|
if err == nil {
|
||||||
|
clearHeldLock()
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func cmdForceUnlock(mgrPath, filePath string) error {
|
||||||
|
// Steps 3-8: acquire meta-lock
|
||||||
|
if _, err := acquireMgrLock(mgrPath); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
lf, err := readLockFile(mgrPath)
|
||||||
|
if err != nil {
|
||||||
|
_ = releaseMgrLock(mgrPath)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove file lock and meta-lock unconditionally
|
||||||
|
delete(lf, filePath)
|
||||||
|
delete(lf, mgrPath)
|
||||||
|
err = writeLockFile(mgrPath, lf)
|
||||||
|
if err == nil {
|
||||||
|
clearHeldLock()
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func run() error {
|
||||||
|
// cleanupMgrLock runs on normal return AND on panic (defer unwinds through panics).
|
||||||
|
// os.Exit bypasses defer, so we keep os.Exit only in main() after run() returns.
|
||||||
|
defer cleanupMgrLock()
|
||||||
|
|
||||||
|
action := ""
|
||||||
|
if len(os.Args) >= 2 {
|
||||||
|
action = os.Args[1]
|
||||||
|
}
|
||||||
|
|
||||||
|
if action == "force-unlock" && len(os.Args) < 3 {
|
||||||
|
return fmt.Errorf("usage: lock-mgr force-unlock <file>")
|
||||||
|
}
|
||||||
|
if (action == "acquire" || action == "release") && len(os.Args) < 4 {
|
||||||
|
return fmt.Errorf("usage: lock-mgr %s <file> <key>", action)
|
||||||
|
}
|
||||||
|
if action == "" || (action != "acquire" && action != "release" && action != "force-unlock") {
|
||||||
|
return fmt.Errorf("usage: lock-mgr <acquire|release> <file> <key>\n lock-mgr force-unlock <file>")
|
||||||
|
}
|
||||||
|
|
||||||
|
fileArg := os.Args[2]
|
||||||
|
key := ""
|
||||||
|
if action != "force-unlock" {
|
||||||
|
key = os.Args[3]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 1: resolve tool directory and locate (or create) the lock file
|
||||||
|
execPath, err := os.Executable()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("cannot determine executable path: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
toolDir := filepath.Dir(execPath)
|
||||||
|
rawMgrPath := filepath.Join(toolDir, "..", ".lock-mgr.json")
|
||||||
|
|
||||||
|
// Step 2: get absolute paths
|
||||||
|
mgrPath, err := filepath.Abs(rawMgrPath)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("cannot resolve lock file path: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
filePath, err := filepath.Abs(fileArg)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("cannot resolve file path: %w", err)
|
||||||
|
}
|
||||||
|
if _, statErr := os.Stat(filePath); os.IsNotExist(statErr) {
|
||||||
|
filePath = fileArg
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure lock file exists
|
||||||
|
if _, statErr := os.Stat(mgrPath); os.IsNotExist(statErr) {
|
||||||
|
if writeErr := os.WriteFile(mgrPath, []byte("{}"), 0644); writeErr != nil {
|
||||||
|
return fmt.Errorf("cannot create lock file: %w", writeErr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
switch action {
|
||||||
|
case "acquire":
|
||||||
|
return cmdAcquire(mgrPath, filePath, key)
|
||||||
|
case "release":
|
||||||
|
return cmdRelease(mgrPath, filePath, key)
|
||||||
|
case "force-unlock":
|
||||||
|
return cmdForceUnlock(mgrPath, filePath)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// Signal handler: release meta-lock on SIGINT / SIGTERM before exiting.
|
||||||
|
// This covers Ctrl+C and process termination while the lock is held.
|
||||||
|
sigCh := make(chan os.Signal, 1)
|
||||||
|
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
|
||||||
|
go func() {
|
||||||
|
<-sigCh
|
||||||
|
cleanupMgrLock()
|
||||||
|
os.Exit(130)
|
||||||
|
}()
|
||||||
|
|
||||||
|
if err := run(); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
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)
|
||||||
|
}
|
||||||
83
plans/PROXY_PC_EXEC.md
Normal file
83
plans/PROXY_PC_EXEC.md
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
# PROXY_PC_EXEC
|
||||||
|
|
||||||
|
## 背景
|
||||||
|
新增一个可代理执行的安全命令工具,整体行为尽量保持与现有 `pcexec` 一致,但允许在受控条件下以指定的代理身份注入 `AGENT_ID`。
|
||||||
|
|
||||||
|
## 开发想法整理
|
||||||
|
|
||||||
|
### 1. 新建工具 `proxy-pcexec`
|
||||||
|
- 新增一个工具:`proxy-pcexec`
|
||||||
|
- 目标是复用或对齐现有 `pcexec` 的能力与行为
|
||||||
|
- 预期执行语义与安全边界尽量和 `pcexec` 保持一致,避免出现两套不同标准
|
||||||
|
|
||||||
|
### 2. 扩展 `openclaw.plugin.json`
|
||||||
|
需要在 `openclaw.plugin.json` 中新增配置字段:
|
||||||
|
- `config.proxyAllowlist`
|
||||||
|
|
||||||
|
兼容性说明:
|
||||||
|
- 如有需要,也可兼容读取 `proxy-allowlist` 作为别名
|
||||||
|
|
||||||
|
用途:
|
||||||
|
- 用于声明哪些 agent 允许调用 `proxy-pcexec`
|
||||||
|
- 只有在该 allowlist 中的 agent,才具备调用该工具的权限
|
||||||
|
|
||||||
|
建议约束:
|
||||||
|
- `config.proxyAllowlist` 应为 agent 标识列表
|
||||||
|
- `allowlist` 仅支持精确匹配,不支持通配、分组或模糊匹配
|
||||||
|
- 若调用方不在 allowlist 中,应直接拒绝调用
|
||||||
|
- 默认配置应偏保守;未配置时建议视为不允许任何 agent 调用
|
||||||
|
- 一旦调用方 agent 在 allowlist 中,则允许其代理任意 `proxy-for` 值
|
||||||
|
|
||||||
|
### 3. `proxy-pcexec` 与 `pcexec` 的关键区别
|
||||||
|
`proxy-pcexec` 的功能与 `pcexec` 基本一致,核心差异如下:
|
||||||
|
|
||||||
|
#### `pcexec`
|
||||||
|
- 直接将调用者的 `agent-id` 注入环境变量 `AGENT_ID`
|
||||||
|
|
||||||
|
#### `proxy-pcexec`
|
||||||
|
- 不直接使用调用者的 `agent-id` 作为 `AGENT_ID`
|
||||||
|
- 增加一个**必填**工具参数:`proxy-for`
|
||||||
|
- 实际注入到环境变量 `AGENT_ID` 中的值,取自 `proxy-for`
|
||||||
|
|
||||||
|
## 建议的行为规则
|
||||||
|
|
||||||
|
### 调用参数
|
||||||
|
`proxy-pcexec` 至少包含:
|
||||||
|
- `command`
|
||||||
|
- `proxy-for`(必填)
|
||||||
|
- 其他参数可尽量与 `pcexec` 保持一致
|
||||||
|
|
||||||
|
### 权限校验
|
||||||
|
调用 `proxy-pcexec` 时应至少进行以下校验:
|
||||||
|
1. 校验调用方 agent 是否在 `config.proxyAllowlist` 中(精确匹配)
|
||||||
|
2. 校验 `proxy-for` 是否存在且非空
|
||||||
|
3. 不要求 `proxy-for` 必须是已注册或已知 agent-id,可自由填写
|
||||||
|
4. 通过校验后,再执行与 `pcexec` 等价的命令执行流程
|
||||||
|
|
||||||
|
说明:
|
||||||
|
- allowlist 控制的是“谁可以发起代理执行”
|
||||||
|
- 只要调用方 agent 在 allowlist 中,就允许其代理任意 agent
|
||||||
|
|
||||||
|
### 环境变量注入
|
||||||
|
- `AGENT_ID` = `proxy-for`
|
||||||
|
- `PROXY_PCEXEC_EXECUTOR` = 调用方真实 `agent-id`
|
||||||
|
- `PCEXEC_PROXIED` = `true`
|
||||||
|
- 不应再把原始调用者的 `agent-id` 直接写入 `AGENT_ID`
|
||||||
|
|
||||||
|
## 设计目标
|
||||||
|
- 保持与 `pcexec` 尽可能一致,降低维护成本
|
||||||
|
- 通过 allowlist 控制谁可以发起代理执行
|
||||||
|
- 通过显式 `proxy-for` 参数,避免隐式身份继承
|
||||||
|
- 让代理身份切换是显式、可审计、可配置的
|
||||||
|
|
||||||
|
## 日志与审计
|
||||||
|
建议日志至少记录:
|
||||||
|
- `executor`(调用方真实 agent-id)
|
||||||
|
- `proxy-for`
|
||||||
|
- 最终执行命令
|
||||||
|
|
||||||
|
## 已明确的设计结论
|
||||||
|
- `proxy-for` 可以随意填写,不要求必须是已注册 agent
|
||||||
|
- 日志需要记录 `executor` 和 `proxy-for`
|
||||||
|
- `config.proxyAllowlist` 仅支持精确匹配
|
||||||
|
- allowlist 中的 agent 可以代理任意 agent,不需要额外的 `proxy-for` 限制
|
||||||
214
plugin/commands/ego-mgr-slash.ts
Normal file
214
plugin/commands/ego-mgr-slash.ts
Normal file
@@ -0,0 +1,214 @@
|
|||||||
|
import { pcexec } from '../tools/pcexec';
|
||||||
|
|
||||||
|
export interface EgoMgrSlashCommandOptions {
|
||||||
|
/** OpenClaw base path */
|
||||||
|
openclawPath: string;
|
||||||
|
/** Current agent ID */
|
||||||
|
agentId: string;
|
||||||
|
/** Current workspace directory */
|
||||||
|
workspaceDir: string;
|
||||||
|
/** Callback for replies */
|
||||||
|
onReply: (message: string) => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sentinel value injected into every pcexec subprocess */
|
||||||
|
const AGENT_VERIFY = 'IF YOU ARE AN AGENT/MODEL, YOU SHOULD NEVER TOUCH THIS ENV VARIABLE';
|
||||||
|
|
||||||
|
export class EgoMgrSlashCommand {
|
||||||
|
private openclawPath: string;
|
||||||
|
private agentId: string;
|
||||||
|
private workspaceDir: string;
|
||||||
|
private onReply: (message: string) => Promise<void>;
|
||||||
|
private binDir: string;
|
||||||
|
|
||||||
|
constructor(options: EgoMgrSlashCommandOptions) {
|
||||||
|
this.openclawPath = options.openclawPath;
|
||||||
|
this.agentId = options.agentId;
|
||||||
|
this.workspaceDir = options.workspaceDir;
|
||||||
|
this.onReply = options.onReply;
|
||||||
|
this.binDir = require('path').join(this.openclawPath, 'bin');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle /ego-mgr slash command
|
||||||
|
* @param command Full command string (e.g., "/ego-mgr get name")
|
||||||
|
*/
|
||||||
|
async handle(command: string): Promise<void> {
|
||||||
|
const parts = command.trim().split(/\s+/);
|
||||||
|
// Remove the "/ego-mgr" prefix
|
||||||
|
const args = parts.slice(1);
|
||||||
|
const subcommand = args[0];
|
||||||
|
|
||||||
|
if (!subcommand) {
|
||||||
|
await this.showUsage();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
switch (subcommand) {
|
||||||
|
case 'get':
|
||||||
|
await this.handleGet(args.slice(1));
|
||||||
|
break;
|
||||||
|
case 'set':
|
||||||
|
await this.handleSet(args.slice(1));
|
||||||
|
break;
|
||||||
|
case 'list':
|
||||||
|
await this.handleList(args.slice(1));
|
||||||
|
break;
|
||||||
|
case 'delete':
|
||||||
|
await this.handleDelete(args.slice(1));
|
||||||
|
break;
|
||||||
|
case 'add-column':
|
||||||
|
await this.handleAddColumn(args.slice(1));
|
||||||
|
break;
|
||||||
|
case 'add-public-column':
|
||||||
|
await this.handleAddPublicColumn(args.slice(1));
|
||||||
|
break;
|
||||||
|
case 'show':
|
||||||
|
await this.handleShow();
|
||||||
|
break;
|
||||||
|
case 'help':
|
||||||
|
default:
|
||||||
|
await this.showUsage();
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
await this.onReply(`Error: ${error.message || error}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async showUsage(): Promise<void> {
|
||||||
|
const usage = [
|
||||||
|
'**ego-mgr Commands**',
|
||||||
|
'',
|
||||||
|
'`/ego-mgr get <column-name>` - Get field value',
|
||||||
|
'`/ego-mgr set <column-name> <value>` - Set field value',
|
||||||
|
'`/ego-mgr list` - List all field names',
|
||||||
|
'`/ego-mgr delete <column-name>` - Delete a field',
|
||||||
|
'`/ego-mgr add-column <column-name>` - Add an Agent Scope field',
|
||||||
|
'`/ego-mgr add-public-column <column-name>` - Add a Public Scope field',
|
||||||
|
'`/ego-mgr show` - Show all fields and values',
|
||||||
|
'',
|
||||||
|
'Examples:',
|
||||||
|
'`/ego-mgr get name`',
|
||||||
|
'`/ego-mgr set timezone Asia/Shanghai`',
|
||||||
|
].join('\n');
|
||||||
|
await this.onReply(usage);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleGet(args: string[]): Promise<void> {
|
||||||
|
if (args.length < 1) {
|
||||||
|
await this.onReply('Usage: `/ego-mgr get <column-name>`');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const columnName = args[0];
|
||||||
|
const result = await this.execEgoMgr(['get', columnName]);
|
||||||
|
await this.onReply(`**${columnName}**: ${result || '(empty)'}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleSet(args: string[]): Promise<void> {
|
||||||
|
if (args.length < 2) {
|
||||||
|
await this.onReply('Usage: `/ego-mgr set <column-name> <value>`');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const columnName = args[0];
|
||||||
|
const value = args.slice(1).join(' '); // Support values with spaces
|
||||||
|
await this.execEgoMgr(['set', columnName, value]);
|
||||||
|
await this.onReply(`Set **${columnName}** = \`${value}\``);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleList(args: string[]): Promise<void> {
|
||||||
|
const result = await this.execEgoMgr(['list', 'columns']);
|
||||||
|
if (!result.trim()) {
|
||||||
|
await this.onReply('No fields defined');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const columns = result.split('\n').filter(Boolean);
|
||||||
|
const lines = ['**Fields**:', ''];
|
||||||
|
for (const col of columns) {
|
||||||
|
lines.push(`• ${col}`);
|
||||||
|
}
|
||||||
|
await this.onReply(lines.join('\n'));
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleDelete(args: string[]): Promise<void> {
|
||||||
|
if (args.length < 1) {
|
||||||
|
await this.onReply('Usage: `/ego-mgr delete <column-name>`');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const columnName = args[0];
|
||||||
|
await this.execEgoMgr(['delete', columnName]);
|
||||||
|
await this.onReply(`Deleted field **${columnName}**`);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleAddColumn(args: string[]): Promise<void> {
|
||||||
|
if (args.length < 1) {
|
||||||
|
await this.onReply('Usage: `/ego-mgr add-column <column-name>`');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const columnName = args[0];
|
||||||
|
await this.execEgoMgr(['add', 'column', columnName]);
|
||||||
|
await this.onReply(`Added Agent Scope field **${columnName}**`);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleAddPublicColumn(args: string[]): Promise<void> {
|
||||||
|
if (args.length < 1) {
|
||||||
|
await this.onReply('Usage: `/ego-mgr add-public-column <column-name>`');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const columnName = args[0];
|
||||||
|
await this.execEgoMgr(['add', 'public-column', columnName]);
|
||||||
|
await this.onReply(`Added Public Scope field **${columnName}**`);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleShow(): Promise<void> {
|
||||||
|
const result = await this.execEgoMgr(['show']);
|
||||||
|
if (!result.trim()) {
|
||||||
|
await this.onReply('No field data');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const lines = ['**Field Data**:', ''];
|
||||||
|
lines.push('```');
|
||||||
|
lines.push(result);
|
||||||
|
lines.push('```');
|
||||||
|
await this.onReply(lines.join('\n'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute ego-mgr binary via pc-exec
|
||||||
|
*/
|
||||||
|
private async execEgoMgr(args: string[]): Promise<string> {
|
||||||
|
const currentPath = process.env.PATH || '';
|
||||||
|
const newPath = currentPath.includes(this.binDir)
|
||||||
|
? currentPath
|
||||||
|
: `${currentPath}:${this.binDir}`;
|
||||||
|
|
||||||
|
const command = `ego-mgr ${args.map(a => this.shellEscape(a)).join(' ')}`;
|
||||||
|
|
||||||
|
const result = await pcexec(command, {
|
||||||
|
cwd: this.workspaceDir,
|
||||||
|
env: {
|
||||||
|
AGENT_ID: this.agentId,
|
||||||
|
AGENT_WORKSPACE: this.workspaceDir,
|
||||||
|
AGENT_VERIFY,
|
||||||
|
PATH: newPath,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result.exitCode !== 0 && result.stderr) {
|
||||||
|
throw new Error(result.stderr);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result.stdout;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Escape a string for shell usage
|
||||||
|
*/
|
||||||
|
private shellEscape(str: string): string {
|
||||||
|
// Simple escaping for common cases
|
||||||
|
if (/^[a-zA-Z0-9._-]+$/.test(str)) {
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
return `'${str.replace(/'/g, "'\"'\"'")}'`;
|
||||||
|
}
|
||||||
|
}
|
||||||
182
plugin/commands/slash-commands.ts
Normal file
182
plugin/commands/slash-commands.ts
Normal file
@@ -0,0 +1,182 @@
|
|||||||
|
import { StatusManager } from '../core/status-manager';
|
||||||
|
|
||||||
|
export interface SlashCommandOptions {
|
||||||
|
statusManager: StatusManager;
|
||||||
|
/** List of authorized user IDs */
|
||||||
|
authorizedUsers: string[];
|
||||||
|
/** Cooldown duration in seconds */
|
||||||
|
cooldownSeconds?: number;
|
||||||
|
/** Callback for replies */
|
||||||
|
onReply: (message: string) => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CommandState {
|
||||||
|
passMgrEnabled: boolean;
|
||||||
|
safeRestartEnabled: boolean;
|
||||||
|
lastToggle: {
|
||||||
|
'pass-mgr': number;
|
||||||
|
'safe-restart': number;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export class SlashCommandHandler {
|
||||||
|
private statusManager: StatusManager;
|
||||||
|
private authorizedUsers: string[];
|
||||||
|
private cooldownMs: number;
|
||||||
|
private onReply: (message: string) => Promise<void>;
|
||||||
|
private state: CommandState;
|
||||||
|
|
||||||
|
constructor(options: SlashCommandOptions) {
|
||||||
|
this.statusManager = options.statusManager;
|
||||||
|
this.authorizedUsers = options.authorizedUsers;
|
||||||
|
this.cooldownMs = (options.cooldownSeconds || 10) * 1000;
|
||||||
|
this.onReply = options.onReply;
|
||||||
|
|
||||||
|
this.state = {
|
||||||
|
passMgrEnabled: true,
|
||||||
|
safeRestartEnabled: true,
|
||||||
|
lastToggle: {
|
||||||
|
'pass-mgr': 0,
|
||||||
|
'safe-restart': 0,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle a slash command
|
||||||
|
*/
|
||||||
|
async handle(command: string, userId: string): Promise<void> {
|
||||||
|
// Check authorization
|
||||||
|
if (!this.authorizedUsers.includes(userId)) {
|
||||||
|
await this.onReply('Unauthorized');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const parts = command.trim().split(/\s+/);
|
||||||
|
const subcommand = parts[1];
|
||||||
|
const feature = parts[2] as 'pass-mgr' | 'safe-restart';
|
||||||
|
|
||||||
|
switch (subcommand) {
|
||||||
|
case 'status':
|
||||||
|
await this.handleStatus();
|
||||||
|
break;
|
||||||
|
case 'enable':
|
||||||
|
await this.handleEnable(feature);
|
||||||
|
break;
|
||||||
|
case 'disable':
|
||||||
|
await this.handleDisable(feature);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
await this.onReply(
|
||||||
|
'Usage:\n' +
|
||||||
|
'`/padded-cell-ctrl status` - Show status\n' +
|
||||||
|
'`/padded-cell-ctrl enable pass-mgr|safe-restart` - Enable feature\n' +
|
||||||
|
'`/padded-cell-ctrl disable pass-mgr|safe-restart` - Disable feature'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleStatus(): Promise<void> {
|
||||||
|
const global = this.statusManager.getGlobalStatus();
|
||||||
|
const agents = this.statusManager.getAllAgents();
|
||||||
|
|
||||||
|
const lines = [
|
||||||
|
'**PaddedCell Status**',
|
||||||
|
'',
|
||||||
|
`Secret Manager: ${this.state.passMgrEnabled ? 'Enabled' : 'Disabled'}`,
|
||||||
|
`Safe Restart: ${this.state.safeRestartEnabled ? 'Enabled' : 'Disabled'}`,
|
||||||
|
'',
|
||||||
|
'**Agent Status:**',
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const agent of agents) {
|
||||||
|
const emoji = this.getStateEmoji(agent.state);
|
||||||
|
lines.push(`${emoji} ${agent.agentId}: ${agent.state}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (agents.length === 0) {
|
||||||
|
lines.push('(No agents registered)');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (global.restartStatus !== 'idle') {
|
||||||
|
lines.push('');
|
||||||
|
lines.push(`Restart Status: ${global.restartStatus}`);
|
||||||
|
if (global.restartScheduledBy) {
|
||||||
|
lines.push(` Initiated by ${global.restartScheduledBy}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.onReply(lines.join('\n'));
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleEnable(feature: 'pass-mgr' | 'safe-restart'): Promise<void> {
|
||||||
|
if (!this.isValidFeature(feature)) {
|
||||||
|
await this.onReply('Unknown feature. Available: pass-mgr, safe-restart');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.isOnCooldown(feature)) {
|
||||||
|
await this.onReply('This feature was recently modified. Please try again later.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (feature === 'pass-mgr') {
|
||||||
|
this.state.passMgrEnabled = true;
|
||||||
|
} else {
|
||||||
|
this.state.safeRestartEnabled = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.state.lastToggle[feature] = Date.now();
|
||||||
|
await this.onReply(`Enabled ${feature}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleDisable(feature: 'pass-mgr' | 'safe-restart'): Promise<void> {
|
||||||
|
if (!this.isValidFeature(feature)) {
|
||||||
|
await this.onReply('Unknown feature. Available: pass-mgr, safe-restart');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.isOnCooldown(feature)) {
|
||||||
|
await this.onReply('This feature was recently modified. Please try again later.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (feature === 'pass-mgr') {
|
||||||
|
this.state.passMgrEnabled = false;
|
||||||
|
} else {
|
||||||
|
this.state.safeRestartEnabled = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.state.lastToggle[feature] = Date.now();
|
||||||
|
await this.onReply(`Disabled ${feature}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
private isValidFeature(feature: string): feature is 'pass-mgr' | 'safe-restart' {
|
||||||
|
return feature === 'pass-mgr' || feature === 'safe-restart';
|
||||||
|
}
|
||||||
|
|
||||||
|
private isOnCooldown(feature: 'pass-mgr' | 'safe-restart'): boolean {
|
||||||
|
const lastToggle = this.state.lastToggle[feature];
|
||||||
|
return Date.now() - lastToggle < this.cooldownMs;
|
||||||
|
}
|
||||||
|
|
||||||
|
private getStateEmoji(state: string): string {
|
||||||
|
switch (state) {
|
||||||
|
case 'idle': return '💤';
|
||||||
|
case 'busy': return '⚡';
|
||||||
|
case 'focus': return '🎯';
|
||||||
|
case 'freeze': return '🧊';
|
||||||
|
case 'pre-freeze': return '⏳';
|
||||||
|
case 'pre-freeze-focus': return '📝';
|
||||||
|
default: return '❓';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
isPassMgrEnabled(): boolean {
|
||||||
|
return this.state.passMgrEnabled;
|
||||||
|
}
|
||||||
|
|
||||||
|
isSafeRestartEnabled(): boolean {
|
||||||
|
return this.state.safeRestartEnabled;
|
||||||
|
}
|
||||||
|
}
|
||||||
100
plugin/core/api.ts
Normal file
100
plugin/core/api.ts
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
import express from 'express';
|
||||||
|
import { StatusManager } from './status-manager';
|
||||||
|
|
||||||
|
export interface ApiOptions {
|
||||||
|
port?: number;
|
||||||
|
statusManager: StatusManager;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates and starts the REST API server for query-restart
|
||||||
|
*/
|
||||||
|
export function createApiServer(options: ApiOptions): express.Application {
|
||||||
|
const { port = 8765, statusManager } = options;
|
||||||
|
const app = express();
|
||||||
|
|
||||||
|
app.use(express.json());
|
||||||
|
|
||||||
|
// POST /query-restart
|
||||||
|
app.post('/query-restart', (req, res) => {
|
||||||
|
const { requesterAgentId, requesterSessionKey } = req.body;
|
||||||
|
|
||||||
|
if (!requesterAgentId || !requesterSessionKey) {
|
||||||
|
return res.status(400).json({
|
||||||
|
error: 'Missing required fields: requesterAgentId, requesterSessionKey',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = statusManager.queryRestart(requesterAgentId, requesterSessionKey);
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
status: result,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// POST /restart-result
|
||||||
|
app.post('/restart-result', (req, res) => {
|
||||||
|
const { status, log } = req.body;
|
||||||
|
|
||||||
|
if (!status || !['ok', 'failed'].includes(status)) {
|
||||||
|
return res.status(400).json({
|
||||||
|
error: 'Invalid status. Must be "ok" or "failed"',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
statusManager.completeRestart(status === 'ok', log);
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
success: true,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// GET /status
|
||||||
|
app.get('/status', (req, res) => {
|
||||||
|
const agents = statusManager.getAllAgents();
|
||||||
|
const global = statusManager.getGlobalStatus();
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
agents,
|
||||||
|
global,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// GET /agent/:agentId
|
||||||
|
app.get('/agent/:agentId', (req, res) => {
|
||||||
|
const { agentId } = req.params;
|
||||||
|
const agent = statusManager.getAgent(agentId);
|
||||||
|
|
||||||
|
if (!agent) {
|
||||||
|
return res.status(404).json({
|
||||||
|
error: `Agent ${agentId} not found`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
agent,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return app;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function startApiServer(options: ApiOptions): Promise<void> {
|
||||||
|
const { port = 8765 } = options;
|
||||||
|
const app = createApiServer(options);
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const server = app.listen(port, () => {
|
||||||
|
console.log(`Safe-restart API server listening on port ${port}`);
|
||||||
|
resolve();
|
||||||
|
});
|
||||||
|
|
||||||
|
server.on('error', (err) => {
|
||||||
|
reject(err);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
4
plugin/core/index.ts
Normal file
4
plugin/core/index.ts
Normal file
@@ -0,0 +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 '../commands/slash-commands';
|
||||||
288
plugin/core/safe-restart.ts
Normal file
288
plugin/core/safe-restart.ts
Normal file
@@ -0,0 +1,288 @@
|
|||||||
|
import { spawn } from 'child_process';
|
||||||
|
import * as fs from 'fs';
|
||||||
|
import { promisify } from 'util';
|
||||||
|
import { StatusManager } from './status-manager';
|
||||||
|
|
||||||
|
const sleep = promisify(setTimeout);
|
||||||
|
|
||||||
|
export interface SafeRestartOptions {
|
||||||
|
/** Agent ID performing the restart */
|
||||||
|
agentId: string;
|
||||||
|
/** Session key for notifications */
|
||||||
|
sessionKey: string;
|
||||||
|
/** API endpoint for query-restart */
|
||||||
|
apiEndpoint?: string;
|
||||||
|
/** Rollback script path */
|
||||||
|
rollback?: string;
|
||||||
|
/** Log file path */
|
||||||
|
log?: string;
|
||||||
|
/** Polling interval in ms (default: 5000) */
|
||||||
|
pollInterval?: number;
|
||||||
|
/** Maximum wait time in ms (default: 300000 = 5min) */
|
||||||
|
maxWaitTime?: number;
|
||||||
|
/** Restart script/command */
|
||||||
|
restartScript?: string;
|
||||||
|
/** Callback for notifications */
|
||||||
|
onNotify?: (sessionKey: string, message: string) => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SafeRestartResult {
|
||||||
|
success: boolean;
|
||||||
|
message: string;
|
||||||
|
log?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Performs a safe restart with polling and rollback support
|
||||||
|
*/
|
||||||
|
export async function safeRestart(options: SafeRestartOptions): Promise<SafeRestartResult> {
|
||||||
|
const {
|
||||||
|
agentId,
|
||||||
|
sessionKey,
|
||||||
|
apiEndpoint = 'http://localhost:8765',
|
||||||
|
rollback,
|
||||||
|
log: logPath,
|
||||||
|
pollInterval = 5000,
|
||||||
|
maxWaitTime = 300000,
|
||||||
|
restartScript = 'openclaw gateway restart',
|
||||||
|
onNotify,
|
||||||
|
} = options;
|
||||||
|
|
||||||
|
const logs: string[] = [];
|
||||||
|
const log = (msg: string) => {
|
||||||
|
const entry = `[${new Date().toISOString()}] ${msg}`;
|
||||||
|
logs.push(entry);
|
||||||
|
console.log(entry);
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
log(`Starting safe restart. Agent: ${agentId}, Session: ${sessionKey}`);
|
||||||
|
|
||||||
|
// Step 1: Poll query-restart until OK or timeout
|
||||||
|
const startTime = Date.now();
|
||||||
|
let restartApproved = false;
|
||||||
|
|
||||||
|
while (Date.now() - startTime < maxWaitTime) {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${apiEndpoint}/query-restart`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
requesterAgentId: agentId,
|
||||||
|
requesterSessionKey: sessionKey,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await response.json() as { status: string };
|
||||||
|
|
||||||
|
if (data.status === 'OK') {
|
||||||
|
log('All agents ready for restart');
|
||||||
|
restartApproved = true;
|
||||||
|
break;
|
||||||
|
} else if (data.status === 'ALREADY_SCHEDULED') {
|
||||||
|
log('Restart already scheduled by another agent');
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: 'ALREADY_SCHEDULED',
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
log(`Waiting for agents to be ready... (${data.status})`);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
log(`Error polling query-restart: ${err}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
await sleep(pollInterval);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!restartApproved) {
|
||||||
|
const msg = 'Timeout waiting for agents to be ready';
|
||||||
|
log(msg);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: msg,
|
||||||
|
log: logs.join('\n'),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 2: Report restart starting
|
||||||
|
log('Executing restart...');
|
||||||
|
|
||||||
|
// Step 3: Start restart in background process
|
||||||
|
const restartProcess = startBackgroundRestart(restartScript, logPath);
|
||||||
|
|
||||||
|
// Wait a moment for restart to initiate
|
||||||
|
await sleep(2000);
|
||||||
|
|
||||||
|
// Step 4: Check if gateway comes back
|
||||||
|
log('Waiting for gateway to restart...');
|
||||||
|
await sleep(60000); // Wait 60s as specified
|
||||||
|
|
||||||
|
// Check gateway status
|
||||||
|
const gatewayOk = await checkGatewayStatus();
|
||||||
|
|
||||||
|
if (gatewayOk) {
|
||||||
|
log('Gateway restarted successfully');
|
||||||
|
|
||||||
|
// Report success
|
||||||
|
await fetch(`${apiEndpoint}/restart-result`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
status: 'ok',
|
||||||
|
log: logPath || logs.join('\n'),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Notify resumption
|
||||||
|
if (onNotify) {
|
||||||
|
await onNotify(sessionKey, 'restart 结束了,我们继续');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: 'Restart completed successfully',
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
log('Gateway restart failed');
|
||||||
|
|
||||||
|
// Execute rollback if provided
|
||||||
|
if (rollback) {
|
||||||
|
log(`Executing rollback: ${rollback}`);
|
||||||
|
try {
|
||||||
|
await executeRollback(rollback);
|
||||||
|
log('Rollback completed');
|
||||||
|
} catch (err) {
|
||||||
|
log(`Rollback failed: ${err}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Report failure
|
||||||
|
await fetch(`${apiEndpoint}/restart-result`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
status: 'failed',
|
||||||
|
log: logPath || logs.join('\n'),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Notify failure
|
||||||
|
if (onNotify) {
|
||||||
|
await onNotify(sessionKey, 'restart 失败,已经 rollback,请参考 log 调查。');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: 'Restart failed',
|
||||||
|
log: logs.join('\n'),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
const errorMsg = `Unexpected error: ${err}`;
|
||||||
|
log(errorMsg);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: errorMsg,
|
||||||
|
log: logs.join('\n'),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function startBackgroundRestart(restartScript: string, logPath?: string): void {
|
||||||
|
const script = `
|
||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
sleep 60
|
||||||
|
${restartScript}
|
||||||
|
openclaw gateway status
|
||||||
|
`;
|
||||||
|
|
||||||
|
const child = spawn('bash', ['-c', script], {
|
||||||
|
detached: true,
|
||||||
|
stdio: logPath ? ['ignore', fs.openSync(logPath, 'w'), fs.openSync(logPath, 'w+')] : 'ignore',
|
||||||
|
});
|
||||||
|
|
||||||
|
child.unref();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function checkGatewayStatus(): Promise<boolean> {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const child = spawn('openclaw', ['gateway', 'status'], {
|
||||||
|
timeout: 10000,
|
||||||
|
});
|
||||||
|
|
||||||
|
let output = '';
|
||||||
|
child.stdout?.on('data', (data) => {
|
||||||
|
output += data.toString();
|
||||||
|
});
|
||||||
|
|
||||||
|
child.on('close', (code) => {
|
||||||
|
resolve(code === 0 && output.includes('running'));
|
||||||
|
});
|
||||||
|
|
||||||
|
child.on('error', () => {
|
||||||
|
resolve(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function executeRollback(rollbackScript: string): Promise<void> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const child = spawn('bash', ['-c', rollbackScript], {
|
||||||
|
timeout: 120000,
|
||||||
|
});
|
||||||
|
|
||||||
|
child.on('close', (code) => {
|
||||||
|
if (code === 0) {
|
||||||
|
resolve();
|
||||||
|
} else {
|
||||||
|
reject(new Error(`Rollback script exited with code ${code}`));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
child.on('error', (err) => {
|
||||||
|
reject(err);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Safe restart tool that can be registered with OpenClaw
|
||||||
|
*/
|
||||||
|
export function createSafeRestartTool(statusManager: StatusManager) {
|
||||||
|
return {
|
||||||
|
name: 'safe_restart',
|
||||||
|
description: 'Perform a safe restart of OpenClaw gateway with agent coordination',
|
||||||
|
parameters: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
rollback: {
|
||||||
|
type: 'string',
|
||||||
|
description: 'Path to rollback script',
|
||||||
|
},
|
||||||
|
log: {
|
||||||
|
type: 'string',
|
||||||
|
description: 'Path to log file',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
handler: async (params: { rollback?: string; log?: string }, context: { agentId: string; sessionKey: string }) => {
|
||||||
|
const result = await safeRestart({
|
||||||
|
agentId: context.agentId,
|
||||||
|
sessionKey: context.sessionKey,
|
||||||
|
rollback: params.rollback,
|
||||||
|
log: params.log,
|
||||||
|
async onNotify(sessionKey, message) {
|
||||||
|
// This would be connected to the messaging system
|
||||||
|
console.log(`[${sessionKey}] ${message}`);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: result.success,
|
||||||
|
message: result.message,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
396
plugin/core/status-manager.ts
Normal file
396
plugin/core/status-manager.ts
Normal file
@@ -0,0 +1,396 @@
|
|||||||
|
import * as fs from 'fs';
|
||||||
|
import * as path from 'path';
|
||||||
|
import { EventEmitter } from 'events';
|
||||||
|
|
||||||
|
export type AgentState =
|
||||||
|
'idle' |
|
||||||
|
'busy' |
|
||||||
|
'focus' |
|
||||||
|
'freeze' |
|
||||||
|
'pre-freeze' |
|
||||||
|
'pre-freeze-focus';
|
||||||
|
|
||||||
|
export interface AgentStatus {
|
||||||
|
agentId: string;
|
||||||
|
state: AgentState;
|
||||||
|
workflow: string | null;
|
||||||
|
activeSessions: string[];
|
||||||
|
lastSessions: string[];
|
||||||
|
updatedAt: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GlobalStatus {
|
||||||
|
restartScheduledBy: string | null;
|
||||||
|
restartSession: string | null;
|
||||||
|
restartStatus: 'idle' | 'waiting' | 'restarting' | 'rollback';
|
||||||
|
updatedAt: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface StatusManagerOptions {
|
||||||
|
dataDir?: string;
|
||||||
|
persistenceInterval?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Manages agent states and global restart status
|
||||||
|
*/
|
||||||
|
export class StatusManager extends EventEmitter {
|
||||||
|
private agents: Map<string, AgentStatus> = new Map();
|
||||||
|
private global: GlobalStatus;
|
||||||
|
private dataDir: string;
|
||||||
|
private persistenceInterval: number;
|
||||||
|
private persistenceTimer: NodeJS.Timeout | null = null;
|
||||||
|
|
||||||
|
constructor(options: StatusManagerOptions = {}) {
|
||||||
|
super();
|
||||||
|
this.dataDir = options.dataDir || path.join(process.env.HOME || '.', '.paddedcell');
|
||||||
|
this.persistenceInterval = options.persistenceInterval || 5000;
|
||||||
|
|
||||||
|
this.global = {
|
||||||
|
restartScheduledBy: null,
|
||||||
|
restartSession: null,
|
||||||
|
restartStatus: 'idle',
|
||||||
|
updatedAt: Date.now(),
|
||||||
|
};
|
||||||
|
|
||||||
|
this.ensureDataDir();
|
||||||
|
this.loadFromDisk();
|
||||||
|
this.startPersistence();
|
||||||
|
}
|
||||||
|
|
||||||
|
private ensureDataDir(): void {
|
||||||
|
if (!fs.existsSync(this.dataDir)) {
|
||||||
|
fs.mkdirSync(this.dataDir, { recursive: true, mode: 0o700 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private getAgentFilePath(agentId: string): string {
|
||||||
|
return path.join(this.dataDir, `agent_${agentId}.json`);
|
||||||
|
}
|
||||||
|
|
||||||
|
private getGlobalFilePath(): string {
|
||||||
|
return path.join(this.dataDir, 'global.json');
|
||||||
|
}
|
||||||
|
|
||||||
|
private loadFromDisk(): void {
|
||||||
|
// Load global status
|
||||||
|
const globalPath = this.getGlobalFilePath();
|
||||||
|
if (fs.existsSync(globalPath)) {
|
||||||
|
try {
|
||||||
|
const data = fs.readFileSync(globalPath, 'utf8');
|
||||||
|
this.global = JSON.parse(data);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to load global status:', err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load agent statuses
|
||||||
|
try {
|
||||||
|
const files = fs.readdirSync(this.dataDir);
|
||||||
|
for (const file of files) {
|
||||||
|
if (file.startsWith('agent_') && file.endsWith('.json')) {
|
||||||
|
try {
|
||||||
|
const data = fs.readFileSync(path.join(this.dataDir, file), 'utf8');
|
||||||
|
const agent = JSON.parse(data) as AgentStatus;
|
||||||
|
this.agents.set(agent.agentId, agent);
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`Failed to load agent status from ${file}:`, err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to read data directory:', err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private saveToDisk(): void {
|
||||||
|
// Save global status
|
||||||
|
try {
|
||||||
|
fs.writeFileSync(
|
||||||
|
this.getGlobalFilePath(),
|
||||||
|
JSON.stringify(this.global, null, 2),
|
||||||
|
{ mode: 0o600 }
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to save global status:', err);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save agent statuses
|
||||||
|
for (const [agentId, agent] of this.agents) {
|
||||||
|
try {
|
||||||
|
fs.writeFileSync(
|
||||||
|
this.getAgentFilePath(agentId),
|
||||||
|
JSON.stringify(agent, null, 2),
|
||||||
|
{ mode: 0o600 }
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`Failed to save agent status for ${agentId}:`, err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private startPersistence(): void {
|
||||||
|
this.persistenceTimer = setInterval(() => {
|
||||||
|
this.saveToDisk();
|
||||||
|
}, this.persistenceInterval);
|
||||||
|
}
|
||||||
|
|
||||||
|
stopPersistence(): void {
|
||||||
|
if (this.persistenceTimer) {
|
||||||
|
clearInterval(this.persistenceTimer);
|
||||||
|
this.persistenceTimer = null;
|
||||||
|
}
|
||||||
|
this.saveToDisk();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Agent state management
|
||||||
|
|
||||||
|
getOrCreateAgent(agentId: string): AgentStatus {
|
||||||
|
if (!this.agents.has(agentId)) {
|
||||||
|
const agent: AgentStatus = {
|
||||||
|
agentId,
|
||||||
|
state: 'idle',
|
||||||
|
workflow: null,
|
||||||
|
activeSessions: [],
|
||||||
|
lastSessions: [],
|
||||||
|
updatedAt: Date.now(),
|
||||||
|
};
|
||||||
|
this.agents.set(agentId, agent);
|
||||||
|
this.emit('agentCreated', agent);
|
||||||
|
}
|
||||||
|
return this.agents.get(agentId)!;
|
||||||
|
}
|
||||||
|
|
||||||
|
getAgent(agentId: string): AgentStatus | undefined {
|
||||||
|
return this.agents.get(agentId);
|
||||||
|
}
|
||||||
|
|
||||||
|
getAllAgents(): AgentStatus[] {
|
||||||
|
return Array.from(this.agents.values());
|
||||||
|
}
|
||||||
|
|
||||||
|
onMessageStart(session: string, agentId: string): void {
|
||||||
|
const agent = this.getOrCreateAgent(agentId);
|
||||||
|
|
||||||
|
// Don't update state for heartbeat sessions
|
||||||
|
if (this.isHeartbeatSession(session)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (agent.state === 'idle') {
|
||||||
|
agent.state = 'busy';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!agent.activeSessions.includes(session)) {
|
||||||
|
agent.activeSessions.push(session);
|
||||||
|
}
|
||||||
|
|
||||||
|
agent.updatedAt = Date.now();
|
||||||
|
this.emit('stateChanged', agent);
|
||||||
|
}
|
||||||
|
|
||||||
|
onMessageEnd(session: string, agentId: string): void {
|
||||||
|
const agent = this.getOrCreateAgent(agentId);
|
||||||
|
|
||||||
|
// Remove from active sessions
|
||||||
|
agent.activeSessions = agent.activeSessions.filter(s => s !== session);
|
||||||
|
|
||||||
|
// Add to last sessions if not already there
|
||||||
|
if (!agent.lastSessions.includes(session)) {
|
||||||
|
agent.lastSessions.unshift(session);
|
||||||
|
if (agent.lastSessions.length > 10) {
|
||||||
|
agent.lastSessions = agent.lastSessions.slice(0, 10);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// State transitions
|
||||||
|
if (agent.activeSessions.length === 0) {
|
||||||
|
if (agent.state === 'busy') {
|
||||||
|
agent.state = 'idle';
|
||||||
|
} else if (agent.state === 'pre-freeze' || agent.state === 'pre-freeze-focus') {
|
||||||
|
agent.state = 'freeze';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
agent.updatedAt = Date.now();
|
||||||
|
this.emit('stateChanged', agent);
|
||||||
|
|
||||||
|
// Check if all agents are frozen (for restart completion)
|
||||||
|
if (agent.state === 'freeze') {
|
||||||
|
this.checkAllFrozen();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setWorkflow(agentId: string, workflow: string | null): void {
|
||||||
|
const agent = this.getOrCreateAgent(agentId);
|
||||||
|
agent.workflow = workflow;
|
||||||
|
|
||||||
|
if (workflow) {
|
||||||
|
agent.state = 'focus';
|
||||||
|
} else {
|
||||||
|
// Transition from focus to idle or busy
|
||||||
|
if (agent.activeSessions.length === 0) {
|
||||||
|
agent.state = 'idle';
|
||||||
|
} else {
|
||||||
|
agent.state = 'busy';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
agent.updatedAt = Date.now();
|
||||||
|
this.emit('stateChanged', agent);
|
||||||
|
}
|
||||||
|
|
||||||
|
isHeartbeatSession(session: string): boolean {
|
||||||
|
// Check if session is a heartbeat session
|
||||||
|
// This can be customized based on naming convention or metadata
|
||||||
|
return session.includes('heartbeat') || session.includes('poll');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Query restart logic
|
||||||
|
|
||||||
|
queryRestart(requesterAgentId: string, requesterSessionKey: string): 'OK' | 'NOT_READY' | 'ALREADY_SCHEDULED' {
|
||||||
|
// Check if restart is already scheduled
|
||||||
|
if (this.global.restartStatus !== 'idle') {
|
||||||
|
// If same agent is requesting, allow continuation
|
||||||
|
if (this.global.restartScheduledBy === requesterAgentId) {
|
||||||
|
return this.allAgentsFrozen() ? 'OK' : 'NOT_READY';
|
||||||
|
}
|
||||||
|
return 'ALREADY_SCHEDULED';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Schedule restart
|
||||||
|
this.global.restartScheduledBy = requesterAgentId;
|
||||||
|
this.global.restartSession = requesterSessionKey;
|
||||||
|
this.global.restartStatus = 'waiting';
|
||||||
|
this.global.updatedAt = Date.now();
|
||||||
|
|
||||||
|
// Transition agents to freeze/pre-freeze states
|
||||||
|
for (const [agentId, agent] of this.agents) {
|
||||||
|
if (agentId === requesterAgentId) {
|
||||||
|
// Don't freeze the requester agent
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (agent.state) {
|
||||||
|
case 'idle':
|
||||||
|
agent.state = 'freeze';
|
||||||
|
break;
|
||||||
|
case 'busy':
|
||||||
|
agent.state = 'pre-freeze';
|
||||||
|
break;
|
||||||
|
case 'focus':
|
||||||
|
agent.state = 'pre-freeze-focus';
|
||||||
|
// Notify agent to prepare for restart
|
||||||
|
this.emit('preparingRestart', agent);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
agent.updatedAt = Date.now();
|
||||||
|
this.emit('stateChanged', agent);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.saveToDisk();
|
||||||
|
|
||||||
|
// Check if all are frozen immediately
|
||||||
|
if (this.allAgentsFrozen()) {
|
||||||
|
return 'OK';
|
||||||
|
}
|
||||||
|
|
||||||
|
return 'NOT_READY';
|
||||||
|
}
|
||||||
|
|
||||||
|
allAgentsFrozen(): boolean {
|
||||||
|
for (const [agentId, agent] of this.agents) {
|
||||||
|
// Skip the agent that scheduled the restart
|
||||||
|
if (agentId === this.global.restartScheduledBy) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (agent.state !== 'freeze') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private checkAllFrozen(): void {
|
||||||
|
if (this.allAgentsFrozen() && this.global.restartStatus === 'waiting') {
|
||||||
|
this.emit('allFrozen');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Restart completion
|
||||||
|
|
||||||
|
completeRestart(success: boolean, log?: string): void {
|
||||||
|
if (success) {
|
||||||
|
this.global.restartStatus = 'idle';
|
||||||
|
|
||||||
|
// Unfreeze all agents
|
||||||
|
for (const agent of this.agents.values()) {
|
||||||
|
if (agent.state === 'freeze') {
|
||||||
|
// Restore previous state from lastSessions
|
||||||
|
agent.state = agent.activeSessions.length > 0 ? 'busy' : 'idle';
|
||||||
|
agent.updatedAt = Date.now();
|
||||||
|
this.emit('stateChanged', agent);
|
||||||
|
this.emit('unfrozen', agent);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.emit('restartCompleted');
|
||||||
|
} else {
|
||||||
|
this.global.restartStatus = 'rollback';
|
||||||
|
this.emit('restartFailed', log);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.global.restartScheduledBy = null;
|
||||||
|
this.global.restartSession = null;
|
||||||
|
this.global.updatedAt = Date.now();
|
||||||
|
this.saveToDisk();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Global status getters
|
||||||
|
|
||||||
|
getGlobalStatus(): GlobalStatus {
|
||||||
|
return { ...this.global };
|
||||||
|
}
|
||||||
|
|
||||||
|
isRestartScheduled(): boolean {
|
||||||
|
return this.global.restartStatus !== 'idle';
|
||||||
|
}
|
||||||
|
|
||||||
|
// For focus mode: check if agent should respond
|
||||||
|
|
||||||
|
shouldRespond(agentId: string, session: string): boolean {
|
||||||
|
const agent = this.getAgent(agentId);
|
||||||
|
if (!agent) return true;
|
||||||
|
|
||||||
|
// In focus mode, only respond to workflow sessions
|
||||||
|
if (agent.state === 'focus' || agent.state === 'pre-freeze-focus') {
|
||||||
|
return agent.workflow !== null && session.includes(agent.workflow);
|
||||||
|
}
|
||||||
|
|
||||||
|
// In freeze/pre-freeze states, don't accept new messages
|
||||||
|
if (agent.state === 'freeze' || agent.state === 'pre-freeze') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
getBusyMessage(agentId: string): string {
|
||||||
|
const agent = this.getAgent(agentId);
|
||||||
|
if (!agent) return '在忙,无法应答';
|
||||||
|
|
||||||
|
switch (agent.state) {
|
||||||
|
case 'focus':
|
||||||
|
case 'pre-freeze-focus':
|
||||||
|
return '当前处于专注模式,无法应答非工作流消息';
|
||||||
|
case 'freeze':
|
||||||
|
case 'pre-freeze':
|
||||||
|
return '系统正在准备重启,请稍后再试';
|
||||||
|
case 'busy':
|
||||||
|
return '正在处理其他消息,请稍后再试';
|
||||||
|
default:
|
||||||
|
return '在忙,无法应答';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
1
plugin/hooks/.gitkeep
Normal file
1
plugin/hooks/.gitkeep
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# placeholder
|
||||||
227
plugin/index.ts
Normal file
227
plugin/index.ts
Normal file
@@ -0,0 +1,227 @@
|
|||||||
|
// PaddedCell Plugin for OpenClaw
|
||||||
|
// Registers pcexec and safe_restart tools
|
||||||
|
|
||||||
|
import { pcexec, pcexecSync } from './tools/pcexec';
|
||||||
|
import {
|
||||||
|
safeRestart,
|
||||||
|
createSafeRestartTool,
|
||||||
|
StatusManager,
|
||||||
|
createApiServer,
|
||||||
|
startApiServer,
|
||||||
|
} from './core/index';
|
||||||
|
import { SlashCommandHandler } from './commands/slash-commands';
|
||||||
|
import { EgoMgrSlashCommand } from './commands/ego-mgr-slash';
|
||||||
|
|
||||||
|
/** 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');
|
||||||
|
}
|
||||||
|
|
||||||
|
function getPluginConfig(api: any): Record<string, unknown> {
|
||||||
|
return ((api?.pluginConfig as Record<string, unknown> | undefined) || {});
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveProxyAllowlist(config?: { proxyAllowlist?: unknown; 'proxy-allowlist'?: unknown }): string[] {
|
||||||
|
const value = config?.proxyAllowlist ?? config?.['proxy-allowlist'];
|
||||||
|
if (!Array.isArray(value)) return [];
|
||||||
|
return value.filter((item): item is string => typeof item === 'string');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Plugin registration function
|
||||||
|
function register(api: any) {
|
||||||
|
const logger = api.logger || { info: console.log, error: console.error };
|
||||||
|
|
||||||
|
logger.info('PaddedCell plugin initializing...');
|
||||||
|
|
||||||
|
const pluginConfig = getPluginConfig(api);
|
||||||
|
const openclawPath = resolveOpenclawPath(pluginConfig as { openclawProfilePath?: string });
|
||||||
|
const proxyAllowlist = resolveProxyAllowlist(pluginConfig as { proxyAllowlist?: unknown; 'proxy-allowlist'?: unknown });
|
||||||
|
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;
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: 'pcexec',
|
||||||
|
description: 'Safe exec with password sanitization',
|
||||||
|
parameters: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
command: { type: 'string', description: 'Command to execute' },
|
||||||
|
cwd: { type: 'string', description: 'Working directory' },
|
||||||
|
timeout: { type: 'number', description: 'Timeout in milliseconds' },
|
||||||
|
},
|
||||||
|
required: ['command'],
|
||||||
|
},
|
||||||
|
async execute(_id: string, params: any) {
|
||||||
|
const command = params.command;
|
||||||
|
if (!command) {
|
||||||
|
throw new Error('Missing required parameter: command');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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) {
|
||||||
|
output += result.stderr;
|
||||||
|
}
|
||||||
|
return { content: [{ type: 'text', text: output }] };
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
api.registerTool((ctx: any) => {
|
||||||
|
const agentId = ctx.agentId;
|
||||||
|
const workspaceDir = ctx.workspaceDir;
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: 'proxy-pcexec',
|
||||||
|
description: 'Safe exec with password sanitization using a proxied AGENT_ID',
|
||||||
|
parameters: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
command: { type: 'string', description: 'Command to execute' },
|
||||||
|
cwd: { type: 'string', description: 'Working directory' },
|
||||||
|
timeout: { type: 'number', description: 'Timeout in milliseconds' },
|
||||||
|
'proxy-for': { type: 'string', description: 'AGENT_ID value to inject for the subprocess' },
|
||||||
|
},
|
||||||
|
required: ['command', 'proxy-for'],
|
||||||
|
},
|
||||||
|
async execute(_id: string, params: any) {
|
||||||
|
const command = params.command;
|
||||||
|
const proxyFor = params['proxy-for'];
|
||||||
|
if (!command) {
|
||||||
|
throw new Error('Missing required parameter: command');
|
||||||
|
}
|
||||||
|
if (!proxyFor) {
|
||||||
|
throw new Error('Missing required parameter: proxy-for');
|
||||||
|
}
|
||||||
|
if (!agentId || !proxyAllowlist.includes(agentId)) {
|
||||||
|
throw new Error('Current agent is not allowed to call proxy-pcexec');
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info('proxy-pcexec invoked', {
|
||||||
|
executor: agentId,
|
||||||
|
proxyFor,
|
||||||
|
command,
|
||||||
|
});
|
||||||
|
|
||||||
|
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: String(proxyFor),
|
||||||
|
AGENT_WORKSPACE: workspaceDir || '',
|
||||||
|
AGENT_VERIFY,
|
||||||
|
PROXY_PCEXEC_EXECUTOR: agentId || '',
|
||||||
|
PCEXEC_PROXIED: 'true',
|
||||||
|
PATH: newPath,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
let output = result.stdout;
|
||||||
|
if (result.stderr) {
|
||||||
|
output += result.stderr;
|
||||||
|
}
|
||||||
|
return { content: [{ type: 'text', text: output }] };
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
// Register safe_restart tool
|
||||||
|
api.registerTool((ctx: any) => {
|
||||||
|
const agentId = ctx.agentId;
|
||||||
|
const sessionKey = ctx.sessionKey;
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: 'safe_restart',
|
||||||
|
description: 'Safe coordinated restart of OpenClaw gateway',
|
||||||
|
parameters: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
rollback: { type: 'string', description: 'Rollback script path' },
|
||||||
|
log: { type: 'string', description: 'Log file path' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
async execute(_id: string, params: any) {
|
||||||
|
return await safeRestart({
|
||||||
|
agentId,
|
||||||
|
sessionKey,
|
||||||
|
rollback: params.rollback,
|
||||||
|
log: params.log,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
// Register /ego-mgr slash command
|
||||||
|
if (api.registerSlashCommand) {
|
||||||
|
api.registerSlashCommand({
|
||||||
|
name: 'ego-mgr',
|
||||||
|
description: 'Manage agent identity/profile fields',
|
||||||
|
handler: async (ctx: any, command: string) => {
|
||||||
|
const egoMgrSlash = new EgoMgrSlashCommand({
|
||||||
|
openclawPath,
|
||||||
|
agentId: ctx.agentId || '',
|
||||||
|
workspaceDir: ctx.workspaceDir || '',
|
||||||
|
onReply: async (message: string) => {
|
||||||
|
if (ctx.reply) {
|
||||||
|
await ctx.reply(message);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await egoMgrSlash.handle(command);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
logger.info('Registered /ego-mgr slash command');
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info('PaddedCell plugin initialized');
|
||||||
|
}
|
||||||
|
|
||||||
|
// CommonJS export for OpenClaw
|
||||||
|
module.exports = { register };
|
||||||
|
|
||||||
|
// Also export individual modules for direct use
|
||||||
|
module.exports.pcexec = pcexec;
|
||||||
|
module.exports.pcexecSync = pcexecSync;
|
||||||
|
module.exports.safeRestart = safeRestart;
|
||||||
|
module.exports.createSafeRestartTool = createSafeRestartTool;
|
||||||
|
module.exports.StatusManager = StatusManager;
|
||||||
|
module.exports.createApiServer = createApiServer;
|
||||||
|
module.exports.startApiServer = startApiServer;
|
||||||
|
module.exports.SlashCommandHandler = SlashCommandHandler;
|
||||||
|
module.exports.EgoMgrSlashCommand = EgoMgrSlashCommand;
|
||||||
|
module.exports.AGENT_VERIFY = AGENT_VERIFY;
|
||||||
20
plugin/openclaw.plugin.json
Normal file
20
plugin/openclaw.plugin.json
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"id": "padded-cell",
|
||||||
|
"name": "PaddedCell",
|
||||||
|
"version": "0.2.0",
|
||||||
|
"description": "Secure secret management, agent identity management, safe execution, and coordinated agent restart",
|
||||||
|
"entry": "./index.js",
|
||||||
|
"configSchema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"enabled": { "type": "boolean", "default": true },
|
||||||
|
"secretMgrPath": { "type": "string", "default": "" },
|
||||||
|
"openclawProfilePath": { "type": "string", "default": "" },
|
||||||
|
"proxyAllowlist": {
|
||||||
|
"type": "array",
|
||||||
|
"items": { "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"
|
||||||
|
}
|
||||||
|
}
|
||||||
339
plugin/tools/pcexec.ts
Normal file
339
plugin/tools/pcexec.ts
Normal file
@@ -0,0 +1,339 @@
|
|||||||
|
import { spawn, SpawnOptions } from 'child_process';
|
||||||
|
|
||||||
|
export interface PcExecOptions {
|
||||||
|
/** Current working directory */
|
||||||
|
cwd?: string;
|
||||||
|
/** Environment variables */
|
||||||
|
env?: Record<string, string>;
|
||||||
|
/** Timeout in milliseconds */
|
||||||
|
timeout?: number;
|
||||||
|
/** Maximum buffer size for stdout/stderr */
|
||||||
|
maxBuffer?: number;
|
||||||
|
/** Kill signal */
|
||||||
|
killSignal?: NodeJS.Signals;
|
||||||
|
/** Shell to use */
|
||||||
|
shell?: string | boolean;
|
||||||
|
/** UID to run as */
|
||||||
|
uid?: number;
|
||||||
|
/** GID to run as */
|
||||||
|
gid?: number;
|
||||||
|
/** Window style (Windows only) */
|
||||||
|
windowsHide?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PcExecResult {
|
||||||
|
/** Standard output */
|
||||||
|
stdout: string;
|
||||||
|
/** Standard error */
|
||||||
|
stderr: string;
|
||||||
|
/** Exit code */
|
||||||
|
exitCode: number;
|
||||||
|
/** Command that was executed */
|
||||||
|
command: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PcExecError extends Error {
|
||||||
|
/** Exit code */
|
||||||
|
code?: number;
|
||||||
|
/** Signal that terminated the process */
|
||||||
|
signal?: string;
|
||||||
|
/** Standard output */
|
||||||
|
stdout: string;
|
||||||
|
/** Standard error */
|
||||||
|
stderr: string;
|
||||||
|
/** Killed by timeout */
|
||||||
|
killed?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extract secret-mgr (and legacy pass_mgr) invocations from a command string.
|
||||||
|
*
|
||||||
|
* Supports:
|
||||||
|
* Current: $(secret-mgr get-secret --key <key>) / `secret-mgr get-secret --key <key>`
|
||||||
|
* Legacy: $(pass_mgr get-secret --key <key>) / `pass_mgr get-secret --key <key>`
|
||||||
|
* Legacy: $(pass_mgr get <key>) / `pass_mgr get <key>`
|
||||||
|
*
|
||||||
|
* Returns array of { fullMatch, subcommand, key, binary } where subcommand is
|
||||||
|
* "get" | "get-secret".
|
||||||
|
*/
|
||||||
|
function extractSecretMgrGets(
|
||||||
|
command: string,
|
||||||
|
): Array<{ key: string; fullMatch: string; subcommand: string; binary: string }> {
|
||||||
|
const results: Array<{ key: string; fullMatch: string; subcommand: string; binary: string }> = [];
|
||||||
|
const seen = new Set<string>();
|
||||||
|
|
||||||
|
// secret-mgr get-secret --key <key>
|
||||||
|
const secretMgrPatterns = [
|
||||||
|
/\$\(\s*secret-mgr\s+get-secret\s+--key\s+(\S+)\s*\)/g,
|
||||||
|
/`\s*secret-mgr\s+get-secret\s+--key\s+(\S+)\s*`/g,
|
||||||
|
];
|
||||||
|
|
||||||
|
// Legacy pass_mgr get-secret --key <key>
|
||||||
|
const newPatterns = [
|
||||||
|
/\$\(\s*pass_mgr\s+get-secret\s+--key\s+(\S+)\s*\)/g,
|
||||||
|
/`\s*pass_mgr\s+get-secret\s+--key\s+(\S+)\s*`/g,
|
||||||
|
];
|
||||||
|
|
||||||
|
// Legacy pass_mgr get <key>
|
||||||
|
const legacyPatterns = [
|
||||||
|
/\$\(\s*pass_mgr\s+get\s+(\S+)\s*\)/g,
|
||||||
|
/`\s*pass_mgr\s+get\s+(\S+)\s*`/g,
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const pattern of secretMgrPatterns) {
|
||||||
|
let match;
|
||||||
|
while ((match = pattern.exec(command)) !== null) {
|
||||||
|
if (!seen.has(match[0])) {
|
||||||
|
seen.add(match[0]);
|
||||||
|
results.push({
|
||||||
|
key: match[1],
|
||||||
|
fullMatch: match[0],
|
||||||
|
subcommand: 'get-secret',
|
||||||
|
binary: 'secret-mgr',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const pattern of newPatterns) {
|
||||||
|
let match;
|
||||||
|
while ((match = pattern.exec(command)) !== null) {
|
||||||
|
if (!seen.has(match[0])) {
|
||||||
|
seen.add(match[0]);
|
||||||
|
results.push({
|
||||||
|
key: match[1],
|
||||||
|
fullMatch: match[0],
|
||||||
|
subcommand: 'get-secret',
|
||||||
|
binary: 'pass_mgr',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const pattern of legacyPatterns) {
|
||||||
|
let match;
|
||||||
|
while ((match = pattern.exec(command)) !== null) {
|
||||||
|
if (!seen.has(match[0])) {
|
||||||
|
seen.add(match[0]);
|
||||||
|
results.push({
|
||||||
|
key: match[1],
|
||||||
|
fullMatch: match[0],
|
||||||
|
subcommand: 'get',
|
||||||
|
binary: 'pass_mgr',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute secret-mgr (or legacy pass_mgr) to retrieve a secret.
|
||||||
|
* Uses the same env vars that the caller passes so pcguard checks pass.
|
||||||
|
*/
|
||||||
|
async function fetchPassword(
|
||||||
|
subcommand: string,
|
||||||
|
key: string,
|
||||||
|
env: Record<string, string>,
|
||||||
|
binary: string = 'secret-mgr',
|
||||||
|
): Promise<string> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
// Prefer SECRET_MGR_PATH, fall back to PASS_MGR_PATH for legacy compat
|
||||||
|
const binaryPath = env.SECRET_MGR_PATH || env.PASS_MGR_PATH || process.env.SECRET_MGR_PATH || process.env.PASS_MGR_PATH || 'secret-mgr';
|
||||||
|
const args =
|
||||||
|
subcommand === 'get-secret'
|
||||||
|
? ['get-secret', '--key', key]
|
||||||
|
: ['get', key];
|
||||||
|
|
||||||
|
const child = spawn(binaryPath, args, {
|
||||||
|
stdio: ['ignore', 'pipe', 'pipe'],
|
||||||
|
env: { ...process.env, ...env },
|
||||||
|
});
|
||||||
|
|
||||||
|
let stdout = '';
|
||||||
|
let stderr = '';
|
||||||
|
child.stdout.on('data', (d) => (stdout += d.toString()));
|
||||||
|
child.stderr.on('data', (d) => (stderr += d.toString()));
|
||||||
|
child.on('close', (code) => {
|
||||||
|
if (code !== 0) {
|
||||||
|
reject(new Error(`secret-mgr ${subcommand} failed: ${stderr || stdout}`));
|
||||||
|
} else {
|
||||||
|
resolve(stdout.trim());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
child.on('error', reject);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sanitize output by replacing passwords with ######
|
||||||
|
*/
|
||||||
|
function sanitizeOutput(output: string, passwords: string[]): string {
|
||||||
|
let sanitized = output;
|
||||||
|
for (const password of passwords) {
|
||||||
|
if (password) {
|
||||||
|
const escaped = password.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||||
|
sanitized = sanitized.replace(new RegExp(escaped, 'g'), '######');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sanitized;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pre-resolve secret-mgr (and legacy pass_mgr) invocations, replace them inline, and collect passwords.
|
||||||
|
*/
|
||||||
|
async function replaceSecretMgrGets(
|
||||||
|
command: string,
|
||||||
|
env: Record<string, string>,
|
||||||
|
): Promise<{ command: string; passwords: string[] }> {
|
||||||
|
const matches = extractSecretMgrGets(command);
|
||||||
|
const passwords: string[] = [];
|
||||||
|
let replaced = command;
|
||||||
|
|
||||||
|
for (const { key, fullMatch, subcommand, binary } of matches) {
|
||||||
|
const pw = await fetchPassword(subcommand, key, env, binary);
|
||||||
|
passwords.push(pw);
|
||||||
|
replaced = replaced.split(fullMatch).join(pw);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { command: replaced, passwords };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Safe exec wrapper that handles secret-mgr get commands and sanitizes output.
|
||||||
|
*/
|
||||||
|
export async function pcexec(
|
||||||
|
command: string,
|
||||||
|
options: PcExecOptions = {},
|
||||||
|
): Promise<PcExecResult> {
|
||||||
|
// Build environment
|
||||||
|
const env: Record<string, string> = {};
|
||||||
|
|
||||||
|
for (const [k, v] of Object.entries(process.env)) {
|
||||||
|
if (v !== undefined) env[k] = v;
|
||||||
|
}
|
||||||
|
if (options.env) Object.assign(env, options.env);
|
||||||
|
|
||||||
|
// Pre-resolve passwords
|
||||||
|
let finalCommand = command;
|
||||||
|
let passwords: string[] = [];
|
||||||
|
|
||||||
|
const resolved = await replaceSecretMgrGets(command, env);
|
||||||
|
finalCommand = resolved.command;
|
||||||
|
passwords = resolved.passwords;
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const spawnOptions: SpawnOptions = {
|
||||||
|
cwd: options.cwd,
|
||||||
|
env,
|
||||||
|
shell: options.shell,
|
||||||
|
windowsHide: options.windowsHide,
|
||||||
|
uid: options.uid,
|
||||||
|
gid: options.gid,
|
||||||
|
};
|
||||||
|
|
||||||
|
const child = spawn('bash', ['-c', finalCommand], spawnOptions);
|
||||||
|
|
||||||
|
let stdout = '';
|
||||||
|
let stderr = '';
|
||||||
|
let killed = false;
|
||||||
|
let timeoutId: NodeJS.Timeout | null = null;
|
||||||
|
|
||||||
|
if (options.timeout && options.timeout > 0) {
|
||||||
|
timeoutId = setTimeout(() => {
|
||||||
|
killed = true;
|
||||||
|
child.kill(options.killSignal || 'SIGTERM');
|
||||||
|
}, options.timeout);
|
||||||
|
}
|
||||||
|
|
||||||
|
child.stdout?.on('data', (data) => {
|
||||||
|
stdout += data.toString();
|
||||||
|
if (options.maxBuffer && stdout.length > options.maxBuffer) {
|
||||||
|
child.kill(options.killSignal || 'SIGTERM');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
child.stderr?.on('data', (data) => {
|
||||||
|
stderr += data.toString();
|
||||||
|
if (options.maxBuffer && stderr.length > options.maxBuffer) {
|
||||||
|
child.kill(options.killSignal || 'SIGTERM');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
child.on('close', (code, signal) => {
|
||||||
|
if (timeoutId) clearTimeout(timeoutId);
|
||||||
|
|
||||||
|
const sanitizedStdout = sanitizeOutput(stdout, passwords);
|
||||||
|
const sanitizedStderr = sanitizeOutput(stderr, passwords);
|
||||||
|
|
||||||
|
if (code === 0) {
|
||||||
|
resolve({
|
||||||
|
stdout: sanitizedStdout,
|
||||||
|
stderr: sanitizedStderr,
|
||||||
|
exitCode: 0,
|
||||||
|
command: finalCommand,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
const error = new Error(`Command failed: ${command}\n${stderr}`) as PcExecError;
|
||||||
|
error.code = code ?? undefined;
|
||||||
|
error.signal = signal ?? undefined;
|
||||||
|
error.stdout = sanitizedStdout;
|
||||||
|
error.stderr = sanitizedStderr;
|
||||||
|
error.killed = killed;
|
||||||
|
reject(error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
child.on('error', (err) => {
|
||||||
|
if (timeoutId) clearTimeout(timeoutId);
|
||||||
|
const error = new Error(`Failed to execute command: ${err.message}`) as PcExecError;
|
||||||
|
error.stdout = sanitizeOutput(stdout, passwords);
|
||||||
|
error.stderr = sanitizeOutput(stderr, passwords);
|
||||||
|
reject(error);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Synchronous version — password substitution is NOT supported here
|
||||||
|
* (use async pcexec for secret-mgr integration).
|
||||||
|
*/
|
||||||
|
export function pcexecSync(
|
||||||
|
command: string,
|
||||||
|
options: PcExecOptions = {},
|
||||||
|
): PcExecResult {
|
||||||
|
const { execSync } = require('child_process');
|
||||||
|
|
||||||
|
const env: Record<string, string> = {};
|
||||||
|
for (const [k, v] of Object.entries(process.env)) {
|
||||||
|
if (v !== undefined) env[k] = v;
|
||||||
|
}
|
||||||
|
if (options.env) Object.assign(env, options.env);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const stdout = execSync(command, {
|
||||||
|
cwd: options.cwd,
|
||||||
|
env,
|
||||||
|
shell: options.shell as any,
|
||||||
|
encoding: 'utf8',
|
||||||
|
windowsHide: options.windowsHide,
|
||||||
|
uid: options.uid,
|
||||||
|
gid: options.gid,
|
||||||
|
maxBuffer: options.maxBuffer,
|
||||||
|
timeout: options.timeout,
|
||||||
|
killSignal: options.killSignal,
|
||||||
|
});
|
||||||
|
|
||||||
|
return { stdout: stdout.toString(), stderr: '', exitCode: 0, command };
|
||||||
|
} catch (err: any) {
|
||||||
|
const error = new Error(`Command failed: ${command}`) as PcExecError;
|
||||||
|
error.code = err.status;
|
||||||
|
error.signal = err.signal;
|
||||||
|
error.stdout = err.stdout?.toString() || '';
|
||||||
|
error.stderr = err.stderr?.toString() || '';
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default pcexec;
|
||||||
19
plugin/tsconfig.json
Normal file
19
plugin/tsconfig.json
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2020",
|
||||||
|
"module": "commonjs",
|
||||||
|
"lib": ["ES2020"],
|
||||||
|
"outDir": "../dist/padded-cell",
|
||||||
|
"rootDir": ".",
|
||||||
|
"strict": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"declaration": true,
|
||||||
|
"declarationMap": true,
|
||||||
|
"sourceMap": true,
|
||||||
|
"resolveJsonModule": true
|
||||||
|
},
|
||||||
|
"include": ["./**/*.ts"],
|
||||||
|
"exclude": ["node_modules", "../dist", "**/*.test.ts"]
|
||||||
|
}
|
||||||
10
secret-mgr/go.mod
Normal file
10
secret-mgr/go.mod
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
module secret-mgr
|
||||||
|
|
||||||
|
go 1.24.0
|
||||||
|
|
||||||
|
require github.com/spf13/cobra v1.8.0
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||||
|
github.com/spf13/pflag v1.0.5 // indirect
|
||||||
|
)
|
||||||
10
secret-mgr/go.sum
Normal file
10
secret-mgr/go.sum
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
||||||
|
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||||
|
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||||
|
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||||
|
github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0=
|
||||||
|
github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho=
|
||||||
|
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
||||||
|
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
541
secret-mgr/src/main.go
Normal file
541
secret-mgr/src/main.go
Normal file
@@ -0,0 +1,541 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/aes"
|
||||||
|
"crypto/cipher"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
)
|
||||||
|
|
||||||
|
// buildSecret is injected at compile time via -ldflags "-X main.buildSecret=<hex>"
|
||||||
|
var buildSecret string
|
||||||
|
|
||||||
|
const (
|
||||||
|
PassStoreDirName = "pc-pass-store"
|
||||||
|
PublicDirName = ".public"
|
||||||
|
|
||||||
|
// Must match pcguard sentinel
|
||||||
|
expectedAgentVerify = "IF YOU ARE AN AGENT/MODEL, YOU SHOULD NEVER TOUCH THIS ENV VARIABLE"
|
||||||
|
)
|
||||||
|
|
||||||
|
// EncryptedFile is the on-disk format for .gpg files
|
||||||
|
// (kept for compatibility with existing files)
|
||||||
|
type EncryptedFile struct {
|
||||||
|
Nonce string `json:"nonce"`
|
||||||
|
Data string `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Entry is the plaintext content inside an encrypted file
|
||||||
|
type Entry struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
Secret string `json:"secret"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolveOpenclawPath() string {
|
||||||
|
if p := os.Getenv("OPENCLAW_PATH"); p != "" {
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
home, _ := os.UserHomeDir()
|
||||||
|
return filepath.Join(home, ".openclaw")
|
||||||
|
}
|
||||||
|
|
||||||
|
func passStoreBase() string { return filepath.Join(resolveOpenclawPath(), PassStoreDirName) }
|
||||||
|
func publicStoreDir() string { return filepath.Join(passStoreBase(), PublicDirName) }
|
||||||
|
func agentStoreDir(agentID string) string { return filepath.Join(passStoreBase(), agentID) }
|
||||||
|
func currentAgentID() string { return os.Getenv("AGENT_ID") }
|
||||||
|
func resolveStoreDir(public bool) string {
|
||||||
|
if public {
|
||||||
|
return publicStoreDir()
|
||||||
|
}
|
||||||
|
return agentStoreDir(currentAgentID())
|
||||||
|
}
|
||||||
|
func ensurePublicStoreDir() error { return os.MkdirAll(publicStoreDir(), 0700) }
|
||||||
|
func deriveKey(secret string) []byte { h := sha256.Sum256([]byte(secret)); return h[:] }
|
||||||
|
func anyAgentEnvSet() bool {
|
||||||
|
return os.Getenv("AGENT_ID") != "" || os.Getenv("AGENT_WORKSPACE") != "" || os.Getenv("AGENT_VERIFY") != ""
|
||||||
|
}
|
||||||
|
func rejectIfAgent(cmdName string) {
|
||||||
|
if anyAgentEnvSet() {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: '%s' can only be run by a human (AGENT_* env vars detected)\n", cmdName)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func currentKey() ([]byte, error) {
|
||||||
|
if buildSecret == "" {
|
||||||
|
return nil, fmt.Errorf("secret-mgr was built without a build secret; re-run install.mjs")
|
||||||
|
}
|
||||||
|
return deriveKey(buildSecret), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func encrypt(plaintext, key []byte) (*EncryptedFile, error) {
|
||||||
|
block, err := aes.NewCipher(key)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
gcm, err := cipher.NewGCM(block)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
nonce := make([]byte, gcm.NonceSize())
|
||||||
|
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
ciphertext := gcm.Seal(nil, nonce, plaintext, nil)
|
||||||
|
return &EncryptedFile{Nonce: base64.StdEncoding.EncodeToString(nonce), Data: base64.StdEncoding.EncodeToString(ciphertext)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func decrypt(ef *EncryptedFile, key []byte) ([]byte, error) {
|
||||||
|
nonce, err := base64.StdEncoding.DecodeString(ef.Nonce)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid nonce: %w", err)
|
||||||
|
}
|
||||||
|
ciphertext, err := base64.StdEncoding.DecodeString(ef.Data)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid data: %w", err)
|
||||||
|
}
|
||||||
|
block, err := aes.NewCipher(key)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
gcm, err := cipher.NewGCM(block)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return gcm.Open(nil, nonce, ciphertext, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func readEntry(filePath string, key []byte) (*Entry, error) {
|
||||||
|
raw, err := os.ReadFile(filePath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var ef EncryptedFile
|
||||||
|
if err := json.Unmarshal(raw, &ef); err != nil {
|
||||||
|
return nil, fmt.Errorf("corrupt file: %w", err)
|
||||||
|
}
|
||||||
|
plain, err := decrypt(&ef, key)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("decryption failed: %w", err)
|
||||||
|
}
|
||||||
|
var entry Entry
|
||||||
|
if err := json.Unmarshal(plain, &entry); err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid entry json: %w", err)
|
||||||
|
}
|
||||||
|
return &entry, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeEntry(filePath string, entry *Entry, key []byte) error {
|
||||||
|
plain, _ := json.Marshal(entry)
|
||||||
|
ef, err := encrypt(plain, key)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
data, _ := json.MarshalIndent(ef, "", " ")
|
||||||
|
return os.WriteFile(filePath, data, 0600)
|
||||||
|
}
|
||||||
|
|
||||||
|
func requirePcguard() {
|
||||||
|
if os.Getenv("AGENT_VERIFY") != expectedAgentVerify {
|
||||||
|
fmt.Fprintln(os.Stderr, "Error: must be invoked via pcexec (AGENT_VERIFY mismatch)")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
if os.Getenv("AGENT_ID") == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, "Error: AGENT_ID not set — must be invoked via pcexec")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
if os.Getenv("AGENT_WORKSPACE") == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, "Error: AGENT_WORKSPACE not set — must be invoked via pcexec")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func generatePassword(length int) (string, error) {
|
||||||
|
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_=+"
|
||||||
|
buf := make([]byte, length)
|
||||||
|
for i := range buf {
|
||||||
|
b := make([]byte, 1)
|
||||||
|
if _, err := rand.Read(b); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
buf[i] = charset[int(b[0])%len(charset)]
|
||||||
|
}
|
||||||
|
return string(buf), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
rootCmd := &cobra.Command{Use: "secret-mgr", Short: "Secret manager for OpenClaw agents"}
|
||||||
|
rootCmd.AddCommand(listCmd(), getSecretCmd(), getUsernameCmd(), getLegacyCmd(), setCmd(), generateCmd(), unsetCmd(), adminCmd())
|
||||||
|
if err := rootCmd.Execute(); err != nil {
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func listKeys(dir string) []string {
|
||||||
|
entries, err := os.ReadDir(dir)
|
||||||
|
if err != nil {
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
out := []string{}
|
||||||
|
for _, e := range entries {
|
||||||
|
name := e.Name()
|
||||||
|
if strings.HasSuffix(name, ".gpg") {
|
||||||
|
out = append(out, strings.TrimSuffix(name, ".gpg"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func listCmd() *cobra.Command {
|
||||||
|
var public bool
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "list",
|
||||||
|
Short: "List keys for current agent",
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
requirePcguard()
|
||||||
|
if public {
|
||||||
|
fmt.Println("----------public------------")
|
||||||
|
for _, k := range listKeys(publicStoreDir()) {
|
||||||
|
fmt.Println(k)
|
||||||
|
}
|
||||||
|
fmt.Println("----------private-----------")
|
||||||
|
for _, k := range listKeys(agentStoreDir(currentAgentID())) {
|
||||||
|
fmt.Println(k)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, k := range listKeys(agentStoreDir(currentAgentID())) {
|
||||||
|
fmt.Println(k)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
cmd.Flags().BoolVar(&public, "public", false, "Include shared public scope")
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func getSecretCmd() *cobra.Command {
|
||||||
|
var keyFlag string
|
||||||
|
var public bool
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "get-secret",
|
||||||
|
Aliases: []string{"get_secret"},
|
||||||
|
Short: "Get secret for a key",
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
requirePcguard()
|
||||||
|
if keyFlag == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, "Error: --key is required")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
key, err := currentKey()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
fp := filepath.Join(resolveStoreDir(public), keyFlag+".gpg")
|
||||||
|
entry, err := readEntry(fp, key)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
fmt.Print(entry.Secret)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
cmd.Flags().StringVar(&keyFlag, "key", "", "Key name")
|
||||||
|
cmd.Flags().BoolVar(&public, "public", false, "Use shared public scope only")
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func getUsernameCmd() *cobra.Command {
|
||||||
|
var keyFlag string
|
||||||
|
var public bool
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "get-username",
|
||||||
|
Aliases: []string{"get_username"},
|
||||||
|
Short: "Get username for a key",
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
requirePcguard()
|
||||||
|
if keyFlag == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, "Error: --key is required")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
key, err := currentKey()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
fp := filepath.Join(resolveStoreDir(public), keyFlag+".gpg")
|
||||||
|
entry, err := readEntry(fp, key)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
fmt.Print(entry.Username)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
cmd.Flags().StringVar(&keyFlag, "key", "", "Key name")
|
||||||
|
cmd.Flags().BoolVar(&public, "public", false, "Use shared public scope only")
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func getLegacyCmd() *cobra.Command {
|
||||||
|
var showUsername bool
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "get [key]",
|
||||||
|
Short: "Get secret (legacy — use get-secret --key instead)",
|
||||||
|
Args: cobra.ExactArgs(1),
|
||||||
|
Hidden: true,
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
requirePcguard()
|
||||||
|
keyName := args[0]
|
||||||
|
key, err := currentKey()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
fp := filepath.Join(agentStoreDir(currentAgentID()), keyName+".gpg")
|
||||||
|
entry, err := readEntry(fp, key)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
if showUsername {
|
||||||
|
fmt.Print(entry.Username)
|
||||||
|
} else {
|
||||||
|
fmt.Print(entry.Secret)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
cmd.Flags().BoolVar(&showUsername, "username", false, "Show username instead of secret")
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func setCmd() *cobra.Command {
|
||||||
|
var keyFlag, username, secret string
|
||||||
|
var public bool
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "set",
|
||||||
|
Short: "Set a key entry",
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
requirePcguard()
|
||||||
|
if keyFlag == "" || secret == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, "Error: --key and --secret are required")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
aesKey, err := currentKey()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
dir := resolveStoreDir(public)
|
||||||
|
if err := os.MkdirAll(dir, 0700); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
if err := ensurePublicStoreDir(); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
entry := &Entry{Username: username, Secret: secret}
|
||||||
|
fp := filepath.Join(dir, keyFlag+".gpg")
|
||||||
|
if err := writeEntry(fp, entry, aesKey); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
cmd.Flags().StringVar(&keyFlag, "key", "", "Key name")
|
||||||
|
cmd.Flags().StringVar(&username, "username", "", "Username")
|
||||||
|
cmd.Flags().StringVar(&secret, "secret", "", "Secret value")
|
||||||
|
cmd.Flags().BoolVar(&public, "public", false, "Use shared public scope only")
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func generateCmd() *cobra.Command {
|
||||||
|
var keyFlag, username string
|
||||||
|
var public bool
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "generate",
|
||||||
|
Short: "Generate a random secret for a key",
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
requirePcguard()
|
||||||
|
if keyFlag == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, "Error: --key is required")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
aesKey, err := currentKey()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
pw, err := generatePassword(32)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
dir := resolveStoreDir(public)
|
||||||
|
if err := os.MkdirAll(dir, 0700); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
if err := ensurePublicStoreDir(); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
entry := &Entry{Username: username, Secret: pw}
|
||||||
|
fp := filepath.Join(dir, keyFlag+".gpg")
|
||||||
|
if err := writeEntry(fp, entry, aesKey); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
fmt.Print(pw)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
cmd.Flags().StringVar(&keyFlag, "key", "", "Key name")
|
||||||
|
cmd.Flags().StringVar(&username, "username", "", "Username")
|
||||||
|
cmd.Flags().BoolVar(&public, "public", false, "Use shared public scope only")
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func unsetCmd() *cobra.Command {
|
||||||
|
var keyFlag string
|
||||||
|
var public bool
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "unset",
|
||||||
|
Short: "Remove a key entry",
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
requirePcguard()
|
||||||
|
if keyFlag == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, "Error: --key is required")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
fp := filepath.Join(resolveStoreDir(public), keyFlag+".gpg")
|
||||||
|
if err := os.Remove(fp); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
cmd.Flags().StringVar(&keyFlag, "key", "", "Key name")
|
||||||
|
cmd.Flags().BoolVar(&public, "public", false, "Use shared public scope only")
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func adminCmd() *cobra.Command {
|
||||||
|
cmd := &cobra.Command{Use: "admin", Short: "Admin commands (human only)"}
|
||||||
|
cmd.AddCommand(adminHandoffCmd(), adminInitFromCmd())
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func adminHandoffCmd() *cobra.Command {
|
||||||
|
return &cobra.Command{
|
||||||
|
Use: "handoff [secret_file_path]",
|
||||||
|
Short: "Export build secret to file for migration",
|
||||||
|
Args: cobra.MaximumNArgs(1),
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
rejectIfAgent("admin handoff")
|
||||||
|
if buildSecret == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, "Error: no build secret compiled in")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
outPath := "pc-pass-store.secret"
|
||||||
|
if len(args) > 0 {
|
||||||
|
outPath = args[0]
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(outPath, []byte(buildSecret), 0600); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(os.Stderr, "Build secret written to %s\n", outPath)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func adminInitFromCmd() *cobra.Command {
|
||||||
|
return &cobra.Command{
|
||||||
|
Use: "init-from [secret_file_path]",
|
||||||
|
Aliases: []string{"init_from"},
|
||||||
|
Short: "Re-encrypt all data from old build secret to current",
|
||||||
|
Args: cobra.MaximumNArgs(1),
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
rejectIfAgent("admin init-from")
|
||||||
|
|
||||||
|
inPath := "pc-pass-store.secret"
|
||||||
|
if len(args) > 0 {
|
||||||
|
inPath = args[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
oldSecretBytes, err := os.ReadFile(inPath)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error reading secret file: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
oldSecret := strings.TrimSpace(string(oldSecretBytes))
|
||||||
|
oldKey := deriveKey(oldSecret)
|
||||||
|
|
||||||
|
newKey, err := currentKey()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = ensurePublicStoreDir()
|
||||||
|
base := passStoreBase()
|
||||||
|
dirs, err := os.ReadDir(base)
|
||||||
|
if err != nil {
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
fmt.Fprintln(os.Stderr, "No pass store found — nothing to migrate")
|
||||||
|
os.Exit(0)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
count := 0
|
||||||
|
for _, d := range dirs {
|
||||||
|
if !d.IsDir() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
scopeDir := filepath.Join(base, d.Name())
|
||||||
|
files, err := os.ReadDir(scopeDir)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, f := range files {
|
||||||
|
if !strings.HasSuffix(f.Name(), ".gpg") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
fp := filepath.Join(scopeDir, f.Name())
|
||||||
|
entry, err := readEntry(fp, oldKey)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Warning: failed to decrypt %s: %v\n", fp, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := writeEntry(fp, entry, newKey); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Warning: failed to re-encrypt %s: %v\n", fp, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := os.Remove(inPath); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Warning: could not remove secret file: %v\n", err)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(os.Stderr, "Re-encrypted %d entries. Secret file removed.\n", count)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
105
skills/ego-mgr/SKILL.md
Normal file
105
skills/ego-mgr/SKILL.md
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
---
|
||||||
|
name: ego-mgr
|
||||||
|
description: Manage agent personal information (name, email, timezone, etc.). Use when storing, retrieving, listing, or managing agent profile fields. Trigger on requests about agent identity, personal info, profile settings, or ego-mgr usage. MUST call ego-mgr via the pcexec tool.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Ego Manager
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
Use ego-mgr to manage agent personal information fields. Supports per-agent fields (Agent Scope) and shared fields (Public Scope).
|
||||||
|
|
||||||
|
## Mandatory safety rule
|
||||||
|
Always invoke ego-mgr through the `pcexec` tool. Do NOT run ego-mgr directly.
|
||||||
|
|
||||||
|
## Concepts
|
||||||
|
|
||||||
|
- **Agent Scope columns**: Each agent stores its own value independently
|
||||||
|
- **Public Scope columns**: All agents share the same value
|
||||||
|
- Column names are globally unique — a name cannot be both agent-scope and public-scope
|
||||||
|
|
||||||
|
## Workflow
|
||||||
|
|
||||||
|
1. First, create a column: `ego-mgr add column <name>` or `ego-mgr add public-column <name>`
|
||||||
|
2. Then, set its value: `ego-mgr set <name> <value>`
|
||||||
|
3. Read it: `ego-mgr get <name>` or `ego-mgr show`
|
||||||
|
|
||||||
|
## Commands (run via pcexec)
|
||||||
|
|
||||||
|
### Add columns
|
||||||
|
```bash
|
||||||
|
# Agent-scope column (per-agent values)
|
||||||
|
ego-mgr add column <column-name> [--default <default-value>]
|
||||||
|
|
||||||
|
# Public-scope column (shared by all agents)
|
||||||
|
ego-mgr add public-column <column-name> [--default <default-value>]
|
||||||
|
```
|
||||||
|
|
||||||
|
### Delete a column
|
||||||
|
```bash
|
||||||
|
ego-mgr delete <column-name>
|
||||||
|
```
|
||||||
|
Removes the column and all its values across all scopes.
|
||||||
|
|
||||||
|
### Set a value
|
||||||
|
```bash
|
||||||
|
ego-mgr set <column-name> <value>
|
||||||
|
```
|
||||||
|
Automatically writes to the correct scope (agent or public) based on column type.
|
||||||
|
|
||||||
|
### Get a value
|
||||||
|
```bash
|
||||||
|
ego-mgr get <column-name>
|
||||||
|
```
|
||||||
|
Outputs just the value (no label).
|
||||||
|
|
||||||
|
### Show all fields
|
||||||
|
```bash
|
||||||
|
ego-mgr show
|
||||||
|
```
|
||||||
|
Lists all fields with values (public first, then agent-scope).
|
||||||
|
|
||||||
|
### List column names
|
||||||
|
```bash
|
||||||
|
ego-mgr list columns
|
||||||
|
```
|
||||||
|
Lists all column names (public first, then agent-scope).
|
||||||
|
|
||||||
|
## Error exit codes
|
||||||
|
|
||||||
|
| Code | Meaning |
|
||||||
|
|------|---------|
|
||||||
|
| 0 | Success |
|
||||||
|
| 1 | Usage error |
|
||||||
|
| 2 | Column not found |
|
||||||
|
| 3 | Column already exists |
|
||||||
|
| 4 | Permission error (not via pcexec) |
|
||||||
|
| 5 | File lock failed |
|
||||||
|
| 6 | JSON read/write error |
|
||||||
|
|
||||||
|
## Common use cases
|
||||||
|
|
||||||
|
### Set up agent identity
|
||||||
|
```bash
|
||||||
|
ego-mgr add column name
|
||||||
|
ego-mgr set name "小智"
|
||||||
|
ego-mgr add column email
|
||||||
|
ego-mgr set email "zhi@example.com"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Set shared config
|
||||||
|
```bash
|
||||||
|
ego-mgr add public-column timezone --default UTC
|
||||||
|
ego-mgr add public-column language --default zh-CN
|
||||||
|
```
|
||||||
|
|
||||||
|
### Check current profile
|
||||||
|
```bash
|
||||||
|
ego-mgr show
|
||||||
|
```
|
||||||
|
|
||||||
|
## Usage notes
|
||||||
|
|
||||||
|
- Always create columns before setting values
|
||||||
|
- Column names are case-sensitive
|
||||||
|
- Public scope values are readable and writable by all agents
|
||||||
|
- Agent scope values are isolated per-agent
|
||||||
68
skills/secret-mgr/SKILL.md
Normal file
68
skills/secret-mgr/SKILL.md
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
---
|
||||||
|
name: secret-mgr
|
||||||
|
description: Manage OpenClaw agent credentials (usernames/secrets). Use when storing, retrieving, listing, generating, or removing credentials for an agent. Trigger on requests about saving or fetching usernames, passwords, tokens, API keys, or other secrets. MUST call secret-mgr via the pcexec tool.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Secret Manager
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
Use secret-mgr to store and retrieve agent-scoped credentials (username/secret pairs) and generate secrets.
|
||||||
|
|
||||||
|
## Mandatory safety rule
|
||||||
|
Always invoke secret-mgr through the `pcexec` tool. Do NOT run secret-mgr directly.
|
||||||
|
|
||||||
|
## Commands (run via pcexec)
|
||||||
|
|
||||||
|
- List keys for current agent
|
||||||
|
- `secret-mgr list`
|
||||||
|
- Include shared scope: `secret-mgr list --public`
|
||||||
|
|
||||||
|
- Get username for a key
|
||||||
|
- `secret-mgr get-username --key <key>`
|
||||||
|
- Shared scope: `secret-mgr get-username --public --key <key>`
|
||||||
|
|
||||||
|
- Get secret for a key
|
||||||
|
- `secret-mgr get-secret --key <key>`
|
||||||
|
- Shared scope: `secret-mgr get-secret --public --key <key>`
|
||||||
|
|
||||||
|
- Set a key entry (username optional)
|
||||||
|
- `secret-mgr set --key <key> --secret <secret> [--username <username>]`
|
||||||
|
- Shared scope: `secret-mgr set --public --key <key> --secret <secret> [--username <username>]`
|
||||||
|
|
||||||
|
- Remove a key entry
|
||||||
|
- `secret-mgr unset --key <key>`
|
||||||
|
- Shared scope: `secret-mgr unset --public --key <key>`
|
||||||
|
|
||||||
|
- Generate a random secret for a key (prints secret)
|
||||||
|
- `secret-mgr generate --key <key> [--username <username>]`
|
||||||
|
- Shared scope: `secret-mgr generate --public --key <key> [--username <username>]`
|
||||||
|
|
||||||
|
- Legacy (hidden) getter
|
||||||
|
- `secret-mgr get <key>`
|
||||||
|
|
||||||
|
## Usage notes
|
||||||
|
|
||||||
|
- Treat all outputs as sensitive. Never echo secrets.
|
||||||
|
- When the agent needs credentials to access a resource, first try `list` to see if a matching key already exists before asking the user.
|
||||||
|
- Prefer `generate` when the user wants a new secret or password.
|
||||||
|
- Use `set` to store both username and secret in one step.
|
||||||
|
- Use `get-username` and `get-secret` for retrieval.
|
||||||
|
- Storing can be explicit (user asks) or proactive after the agent successfully registers/creates an account.
|
||||||
|
- Secrets should be fetched and used immediately in a command, not displayed (e.g., `xxx_cli login --user $(secret-mgr get-username --key some_key) --pass $(secret-mgr get-secret --key some_key)`).
|
||||||
|
|
||||||
|
## Examples (pcexec)
|
||||||
|
|
||||||
|
- Store credentials
|
||||||
|
- pcexec: `secret-mgr set --key github --username alice --secret <secret>`
|
||||||
|
|
||||||
|
- Retrieve username
|
||||||
|
- pcexec: `secret-mgr get-username --key github`
|
||||||
|
|
||||||
|
- Retrieve secret
|
||||||
|
- pcexec: `secret-mgr get-secret --key github`
|
||||||
|
|
||||||
|
- Generate secret
|
||||||
|
- pcexec: `secret-mgr generate --key github`
|
||||||
|
|
||||||
|
- Delete entry
|
||||||
|
- pcexec: `secret-mgr unset --key github`
|
||||||
Reference in New Issue
Block a user