Compare commits
28 Commits
61cffae9ca
...
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 |
83
README.md
83
README.md
@@ -6,7 +6,7 @@
|
||||
|
||||
# PaddedCell
|
||||
|
||||
OpenClaw plugin for secure password management, safe command execution, and coordinated agent restart.
|
||||
OpenClaw plugin for secure secret management, agent identity management, safe command execution, and coordinated agent restart.
|
||||
|
||||
## ⚠️ Security Model
|
||||
|
||||
@@ -16,7 +16,7 @@ OpenClaw plugin for secure password management, safe command execution, and coor
|
||||
|
||||
## Features
|
||||
|
||||
### 1. pass\_mgr — Password Manager (Go)
|
||||
### 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`.
|
||||
@@ -24,23 +24,41 @@ Secrets are stored per-agent under `pc-pass-store/<agent-id>/<key>.gpg`.
|
||||
**Agent commands** (require pcguard — must run through pcexec):
|
||||
|
||||
```bash
|
||||
pass_mgr list # List keys for current agent
|
||||
pass_mgr get-secret --key <key> # Output secret
|
||||
pass_mgr get-username --key <key> # Output username
|
||||
pass_mgr set --key <key> --secret <s> [--username <u>] # Set entry
|
||||
pass_mgr generate --key <key> [--username <u>] # Generate random secret
|
||||
pass_mgr unset --key <key> # Delete entry
|
||||
pass_mgr get <key> # Legacy (maps to get-secret)
|
||||
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
|
||||
pass_mgr admin handoff [file] # Export build secret to file (default: pc-pass-store.secret)
|
||||
pass_mgr admin init-from [file] # Re-encrypt all data from old build secret to current
|
||||
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. pcguard — Exec Guard (Go)
|
||||
### 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.
|
||||
|
||||
@@ -50,15 +68,15 @@ pcguard || exit 1
|
||||
# ... rest of script
|
||||
```
|
||||
|
||||
### 3. pcexec — Safe Execution Tool (TypeScript)
|
||||
### 4. pcexec — Safe Execution Tool (TypeScript)
|
||||
|
||||
Drop-in replacement for `exec` that:
|
||||
- Resolves `$(pass_mgr get-secret --key <key>)` and legacy `$(pass_mgr get <key>)` inline
|
||||
- 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` and `pass_mgr` available)
|
||||
- Appends `$(openclaw path)/bin` to `PATH` (making `pcguard`, `secret-mgr`, and `ego-mgr` available)
|
||||
|
||||
### 4. safe-restart — Coordinated Restart (TypeScript)
|
||||
### 5. safe-restart — Coordinated Restart (TypeScript)
|
||||
|
||||
Agent state management and coordinated gateway restart.
|
||||
|
||||
@@ -75,10 +93,15 @@ PaddedCell/
|
||||
│ ├── openclaw.plugin.json
|
||||
│ ├── package.json
|
||||
│ └── tsconfig.json
|
||||
├── pass_mgr/ # Go password manager binary
|
||||
├── 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
|
||||
@@ -100,7 +123,7 @@ node install.mjs --build-only
|
||||
node install.mjs --uninstall
|
||||
```
|
||||
|
||||
The installer automatically generates a random 32-byte build secret (stored in `.build-secret`, gitignored) and injects it into `pass_mgr` at compile time. Subsequent builds reuse the same secret.
|
||||
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
|
||||
|
||||
@@ -114,14 +137,14 @@ When you rebuild PaddedCell (which generates a new build secret), existing encry
|
||||
|
||||
```bash
|
||||
# 1. Before updating — export current build secret
|
||||
~/.openclaw/bin/pass_mgr admin handoff
|
||||
~/.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/pass_mgr admin init-from
|
||||
~/.openclaw/bin/secret-mgr admin init-from
|
||||
|
||||
# 4. Restart gateway
|
||||
openclaw gateway restart
|
||||
@@ -131,17 +154,23 @@ openclaw gateway restart
|
||||
|
||||
```bash
|
||||
# Agent sets and gets private passwords (via pcexec)
|
||||
pass_mgr set --key myservice --secret s3cret --username admin
|
||||
pass_mgr get-secret --key myservice
|
||||
pass_mgr get-username --key myservice
|
||||
secret-mgr set --key myservice --secret s3cret --username admin
|
||||
secret-mgr get-secret --key myservice
|
||||
secret-mgr get-username --key myservice
|
||||
|
||||
# Shared scope (.public)
|
||||
pass_mgr set --public --key shared-api --secret s3cret
|
||||
pass_mgr list --public
|
||||
pass_mgr get-secret --public --key shared-api
|
||||
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 "$(pass_mgr get-username --key myservice):$(pass_mgr get-secret --key myservice)" https://api.example.com
|
||||
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
|
||||
|
||||
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 能独立使用
|
||||
@@ -1,4 +1,4 @@
|
||||
module pass_mgr
|
||||
module ego-mgr
|
||||
|
||||
go 1.24.0
|
||||
|
||||
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
|
||||
}
|
||||
82
install.mjs
82
install.mjs
@@ -131,13 +131,20 @@ async function build() {
|
||||
|
||||
rmSync(SRC_DIST_DIR, { recursive: true, force: true });
|
||||
|
||||
log(' Building pass_mgr...', 'blue');
|
||||
const pmDir = join(__dirname, 'pass_mgr');
|
||||
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/pass_mgr src/main.go`, { cwd: pmDir, silent: !options.verbose });
|
||||
chmodSync(join(pmDir, 'dist', 'pass_mgr'), 0o755);
|
||||
logOk('pass_mgr');
|
||||
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');
|
||||
@@ -146,6 +153,13 @@ async function build() {
|
||||
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 });
|
||||
@@ -161,7 +175,11 @@ async function build() {
|
||||
}
|
||||
|
||||
function handoffSecretIfPossible(openclawPath) {
|
||||
const passMgrPath = join(openclawPath, 'bin', 'pass_mgr');
|
||||
// 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');
|
||||
@@ -181,7 +199,7 @@ function handoffSecretIfPossible(openclawPath) {
|
||||
|
||||
function clearInstallTargets(openclawPath) {
|
||||
const binDir = join(openclawPath, 'bin');
|
||||
for (const name of ['pass_mgr', 'pcguard']) {
|
||||
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}`); }
|
||||
}
|
||||
@@ -213,7 +231,7 @@ function cleanupConfig(openclawPath) {
|
||||
logOk('Removed from load paths');
|
||||
}
|
||||
|
||||
const skillEntries = ['pcexec', 'safe-restart', 'safe_restart', 'pass-mgr'];
|
||||
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)) {
|
||||
@@ -240,7 +258,7 @@ async function install() {
|
||||
log(` OpenClaw path: ${openclawPath}`, 'blue');
|
||||
|
||||
// update/reinstall path: remove old install first
|
||||
if (existsSync(destDir) || existsSync(join(binDir, 'pass_mgr')) || existsSync(join(binDir, 'pcguard'))) {
|
||||
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);
|
||||
@@ -259,8 +277,10 @@ async function install() {
|
||||
|
||||
mkdirSync(binDir, { recursive: true });
|
||||
const bins = [
|
||||
{ name: 'pass_mgr', src: join(__dirname, 'pass_mgr', 'dist', 'pass_mgr') },
|
||||
{ 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);
|
||||
@@ -281,11 +301,26 @@ async function install() {
|
||||
}
|
||||
}
|
||||
|
||||
// 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, 'pass_mgr');
|
||||
const passMgrPath = join(binDir, 'secret-mgr');
|
||||
try {
|
||||
exec(`${passMgrPath} admin init-from ${secretFile}`, { silent: !options.verbose });
|
||||
logOk('init-from completed from handoff secret');
|
||||
@@ -303,7 +338,7 @@ async function configure() {
|
||||
|
||||
const openclawPath = resolveOpenclawPath();
|
||||
const destDir = join(openclawPath, 'plugins', PLUGIN_NAME);
|
||||
const passMgrPath = join(openclawPath, 'bin', 'pass_mgr');
|
||||
const secretMgrPath = join(openclawPath, 'bin', 'secret-mgr');
|
||||
|
||||
try {
|
||||
const paths = getOpenclawConfig('plugins.load.paths', []);
|
||||
@@ -314,14 +349,21 @@ async function configure() {
|
||||
if (!allow.includes(PLUGIN_NAME)) { allow.push(PLUGIN_NAME); setOpenclawConfig('plugins.allow', allow); }
|
||||
logOk(`plugins.allow includes ${PLUGIN_NAME}`);
|
||||
|
||||
const plugins = getOpenclawConfig('plugins', {});
|
||||
plugins.entries = plugins.entries || {};
|
||||
plugins.entries[PLUGIN_NAME] = {
|
||||
enabled: true,
|
||||
config: { enabled: true, passMgrPath, openclawProfilePath: openclawPath },
|
||||
};
|
||||
setOpenclawConfig('plugins', plugins);
|
||||
logOk('Plugin entry configured');
|
||||
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}`);
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
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, "'\"'\"'")}'`;
|
||||
}
|
||||
}
|
||||
@@ -48,7 +48,7 @@ export class SlashCommandHandler {
|
||||
async handle(command: string, userId: string): Promise<void> {
|
||||
// Check authorization
|
||||
if (!this.authorizedUsers.includes(userId)) {
|
||||
await this.onReply('❌ 无权执行此命令');
|
||||
await this.onReply('Unauthorized');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -68,10 +68,10 @@ export class SlashCommandHandler {
|
||||
break;
|
||||
default:
|
||||
await this.onReply(
|
||||
'用法:\n' +
|
||||
'`/padded-cell-ctrl status` - 查看状态\n' +
|
||||
'`/padded-cell-ctrl enable pass-mgr|safe-restart` - 启用功能\n' +
|
||||
'`/padded-cell-ctrl disable pass-mgr|safe-restart` - 禁用功能'
|
||||
'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'
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -81,12 +81,12 @@ export class SlashCommandHandler {
|
||||
const agents = this.statusManager.getAllAgents();
|
||||
|
||||
const lines = [
|
||||
'**PaddedCell 状态**',
|
||||
'**PaddedCell Status**',
|
||||
'',
|
||||
`🔐 密码管理: ${this.state.passMgrEnabled ? '✅ 启用' : '❌ 禁用'}`,
|
||||
`🔄 安全重启: ${this.state.safeRestartEnabled ? '✅ 启用' : '❌ 禁用'}`,
|
||||
`Secret Manager: ${this.state.passMgrEnabled ? 'Enabled' : 'Disabled'}`,
|
||||
`Safe Restart: ${this.state.safeRestartEnabled ? 'Enabled' : 'Disabled'}`,
|
||||
'',
|
||||
'**Agent 状态:**',
|
||||
'**Agent Status:**',
|
||||
];
|
||||
|
||||
for (const agent of agents) {
|
||||
@@ -95,14 +95,14 @@ export class SlashCommandHandler {
|
||||
}
|
||||
|
||||
if (agents.length === 0) {
|
||||
lines.push('(暂无 agent 注册)');
|
||||
lines.push('(No agents registered)');
|
||||
}
|
||||
|
||||
if (global.restartStatus !== 'idle') {
|
||||
lines.push('');
|
||||
lines.push(`⚠️ 重启状态: ${global.restartStatus}`);
|
||||
lines.push(`Restart Status: ${global.restartStatus}`);
|
||||
if (global.restartScheduledBy) {
|
||||
lines.push(` 由 ${global.restartScheduledBy} 发起`);
|
||||
lines.push(` Initiated by ${global.restartScheduledBy}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,12 +111,12 @@ export class SlashCommandHandler {
|
||||
|
||||
private async handleEnable(feature: 'pass-mgr' | 'safe-restart'): Promise<void> {
|
||||
if (!this.isValidFeature(feature)) {
|
||||
await this.onReply('❌ 未知功能。可用选项: pass-mgr, safe-restart');
|
||||
await this.onReply('Unknown feature. Available: pass-mgr, safe-restart');
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.isOnCooldown(feature)) {
|
||||
await this.onReply('⏳ 该功能最近刚被修改过,请稍后再试');
|
||||
await this.onReply('This feature was recently modified. Please try again later.');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -127,17 +127,17 @@ export class SlashCommandHandler {
|
||||
}
|
||||
|
||||
this.state.lastToggle[feature] = Date.now();
|
||||
await this.onReply(`✅ 已启用 ${feature}`);
|
||||
await this.onReply(`Enabled ${feature}`);
|
||||
}
|
||||
|
||||
private async handleDisable(feature: 'pass-mgr' | 'safe-restart'): Promise<void> {
|
||||
if (!this.isValidFeature(feature)) {
|
||||
await this.onReply('❌ 未知功能。可用选项: pass-mgr, safe-restart');
|
||||
await this.onReply('Unknown feature. Available: pass-mgr, safe-restart');
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.isOnCooldown(feature)) {
|
||||
await this.onReply('⏳ 该功能最近刚被修改过,请稍后再试');
|
||||
await this.onReply('This feature was recently modified. Please try again later.');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -148,7 +148,7 @@ export class SlashCommandHandler {
|
||||
}
|
||||
|
||||
this.state.lastToggle[feature] = Date.now();
|
||||
await this.onReply(`✅ 已禁用 ${feature}`);
|
||||
await this.onReply(`Disabled ${feature}`);
|
||||
}
|
||||
|
||||
private isValidFeature(feature: string): feature is 'pass-mgr' | 'safe-restart' {
|
||||
|
||||
103
plugin/index.ts
103
plugin/index.ts
@@ -10,6 +10,7 @@ import {
|
||||
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';
|
||||
@@ -25,13 +26,25 @@ function resolveOpenclawPath(config?: { openclawProfilePath?: string }): string
|
||||
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, config?: any) {
|
||||
function register(api: any) {
|
||||
const logger = api.logger || { info: console.log, error: console.error };
|
||||
|
||||
logger.info('PaddedCell plugin initializing...');
|
||||
|
||||
const openclawPath = resolveOpenclawPath(config);
|
||||
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
|
||||
@@ -84,6 +97,69 @@ function register(api: any, config?: any) {
|
||||
};
|
||||
});
|
||||
|
||||
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;
|
||||
@@ -110,6 +186,28 @@ function register(api: any, config?: any) {
|
||||
};
|
||||
});
|
||||
|
||||
// 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');
|
||||
}
|
||||
|
||||
@@ -125,4 +223,5 @@ 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;
|
||||
|
||||
@@ -2,14 +2,19 @@
|
||||
"id": "padded-cell",
|
||||
"name": "PaddedCell",
|
||||
"version": "0.2.0",
|
||||
"description": "Secure password management, safe execution, and coordinated agent restart",
|
||||
"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 },
|
||||
"passMgrPath": { "type": "string", "default": "" },
|
||||
"openclawProfilePath": { "type": "string", "default": "" }
|
||||
"secretMgrPath": { "type": "string", "default": "" },
|
||||
"openclawProfilePath": { "type": "string", "default": "" },
|
||||
"proxyAllowlist": {
|
||||
"type": "array",
|
||||
"items": { "type": "string" },
|
||||
"default": []
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,33 +46,55 @@ export interface PcExecError extends Error {
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract pass_mgr invocations from a command string.
|
||||
* Extract secret-mgr (and legacy pass_mgr) invocations from a command string.
|
||||
*
|
||||
* Supports both legacy and new formats:
|
||||
* Legacy: $(pass_mgr get <key>) / `pass_mgr get <key>`
|
||||
* New: $(pass_mgr get-secret --key <key>) / `pass_mgr get-secret --key <key>`
|
||||
* 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 } where subcommand is
|
||||
* Returns array of { fullMatch, subcommand, key, binary } where subcommand is
|
||||
* "get" | "get-secret".
|
||||
*/
|
||||
function extractPassMgrGets(
|
||||
function extractSecretMgrGets(
|
||||
command: string,
|
||||
): Array<{ key: string; fullMatch: string; subcommand: string }> {
|
||||
const results: Array<{ key: string; fullMatch: string; subcommand: 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>();
|
||||
|
||||
// New format: pass_mgr get-secret --key <key>
|
||||
// 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 format: pass_mgr get <key>
|
||||
// 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) {
|
||||
@@ -82,6 +104,7 @@ function extractPassMgrGets(
|
||||
key: match[1],
|
||||
fullMatch: match[0],
|
||||
subcommand: 'get-secret',
|
||||
binary: 'pass_mgr',
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -96,6 +119,7 @@ function extractPassMgrGets(
|
||||
key: match[1],
|
||||
fullMatch: match[0],
|
||||
subcommand: 'get',
|
||||
binary: 'pass_mgr',
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -105,22 +129,24 @@ function extractPassMgrGets(
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute pass_mgr to retrieve a secret.
|
||||
* 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) => {
|
||||
const passMgrPath = env.PASS_MGR_PATH || process.env.PASS_MGR_PATH || 'pass_mgr';
|
||||
// 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(passMgrPath, args, {
|
||||
const child = spawn(binaryPath, args, {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
env: { ...process.env, ...env },
|
||||
});
|
||||
@@ -131,7 +157,7 @@ async function fetchPassword(
|
||||
child.stderr.on('data', (d) => (stderr += d.toString()));
|
||||
child.on('close', (code) => {
|
||||
if (code !== 0) {
|
||||
reject(new Error(`pass_mgr ${subcommand} failed: ${stderr || stdout}`));
|
||||
reject(new Error(`secret-mgr ${subcommand} failed: ${stderr || stdout}`));
|
||||
} else {
|
||||
resolve(stdout.trim());
|
||||
}
|
||||
@@ -155,18 +181,18 @@ function sanitizeOutput(output: string, passwords: string[]): string {
|
||||
}
|
||||
|
||||
/**
|
||||
* Pre-resolve pass_mgr invocations, replace them inline, and collect passwords.
|
||||
* Pre-resolve secret-mgr (and legacy pass_mgr) invocations, replace them inline, and collect passwords.
|
||||
*/
|
||||
async function replacePassMgrGets(
|
||||
async function replaceSecretMgrGets(
|
||||
command: string,
|
||||
env: Record<string, string>,
|
||||
): Promise<{ command: string; passwords: string[] }> {
|
||||
const matches = extractPassMgrGets(command);
|
||||
const matches = extractSecretMgrGets(command);
|
||||
const passwords: string[] = [];
|
||||
let replaced = command;
|
||||
|
||||
for (const { key, fullMatch, subcommand } of matches) {
|
||||
const pw = await fetchPassword(subcommand, key, env);
|
||||
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);
|
||||
}
|
||||
@@ -175,7 +201,7 @@ async function replacePassMgrGets(
|
||||
}
|
||||
|
||||
/**
|
||||
* Safe exec wrapper that handles pass_mgr get commands and sanitizes output.
|
||||
* Safe exec wrapper that handles secret-mgr get commands and sanitizes output.
|
||||
*/
|
||||
export async function pcexec(
|
||||
command: string,
|
||||
@@ -193,7 +219,7 @@ export async function pcexec(
|
||||
let finalCommand = command;
|
||||
let passwords: string[] = [];
|
||||
|
||||
const resolved = await replacePassMgrGets(command, env);
|
||||
const resolved = await replaceSecretMgrGets(command, env);
|
||||
finalCommand = resolved.command;
|
||||
passwords = resolved.passwords;
|
||||
|
||||
@@ -249,7 +275,7 @@ export async function pcexec(
|
||||
command: finalCommand,
|
||||
});
|
||||
} else {
|
||||
const error = new Error(`Command failed: ${command}`) as PcExecError;
|
||||
const error = new Error(`Command failed: ${command}\n${stderr}`) as PcExecError;
|
||||
error.code = code ?? undefined;
|
||||
error.signal = signal ?? undefined;
|
||||
error.stdout = sanitizedStdout;
|
||||
@@ -271,7 +297,7 @@ export async function pcexec(
|
||||
|
||||
/**
|
||||
* Synchronous version — password substitution is NOT supported here
|
||||
* (use async pcexec for pass_mgr integration).
|
||||
* (use async pcexec for secret-mgr integration).
|
||||
*/
|
||||
export function pcexecSync(
|
||||
command: string,
|
||||
|
||||
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=
|
||||
@@ -72,7 +72,7 @@ func rejectIfAgent(cmdName string) {
|
||||
|
||||
func currentKey() ([]byte, error) {
|
||||
if buildSecret == "" {
|
||||
return nil, fmt.Errorf("pass_mgr was built without a build secret; re-run install.mjs")
|
||||
return nil, fmt.Errorf("secret-mgr was built without a build secret; re-run install.mjs")
|
||||
}
|
||||
return deriveKey(buildSecret), nil
|
||||
}
|
||||
@@ -173,7 +173,7 @@ func generatePassword(length int) (string, error) {
|
||||
}
|
||||
|
||||
func main() {
|
||||
rootCmd := &cobra.Command{Use: "pass_mgr", Short: "Password manager for OpenClaw agents"}
|
||||
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)
|
||||
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
|
||||
@@ -1,59 +0,0 @@
|
||||
---
|
||||
name: pass-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 pass_mgr via the pcexec tool.
|
||||
---
|
||||
|
||||
# Pass Manager
|
||||
|
||||
## Purpose
|
||||
Use pass_mgr to store and retrieve agent-scoped credentials (username/secret pairs) and generate secrets.
|
||||
|
||||
## Mandatory safety rule
|
||||
Always invoke pass_mgr through the `pcexec` tool. Do NOT run pass_mgr directly.
|
||||
|
||||
## Commands (run via pcexec)
|
||||
|
||||
- List keys for current agent
|
||||
- `pass_mgr list`
|
||||
|
||||
- Get username for a key
|
||||
- `pass_mgr get-username <key>`
|
||||
|
||||
- Get secret for a key
|
||||
- `pass_mgr get-secret <key>`
|
||||
|
||||
- Set a key entry (username optional)
|
||||
- `pass_mgr set <key> --secret <secret> [--username <username>]`
|
||||
|
||||
- Remove a key entry
|
||||
- `pass_mgr unset <key>`
|
||||
|
||||
- Generate a random secret for a key (prints secret)
|
||||
- `pass_mgr generate <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 $(pass_mgr get-username some_key) --pass $(pass_mgr get-secret some_key)`).
|
||||
|
||||
## Examples (pcexec)
|
||||
|
||||
- Store credentials
|
||||
- pcexec: `pass_mgr set github --username alice --secret <secret>`
|
||||
|
||||
- Retrieve username
|
||||
- pcexec: `pass_mgr get-username github`
|
||||
|
||||
- Retrieve secret
|
||||
- pcexec: `pass_mgr get-secret github`
|
||||
|
||||
- Generate secret
|
||||
- pcexec: `pass_mgr generate github`
|
||||
|
||||
- Delete entry
|
||||
- pcexec: `pass_mgr unset github`
|
||||
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