Compare commits

...

34 Commits

Author SHA1 Message Date
cb683c43bb fix: avoid clobbering sensitive config fields during configure
Reading the entire plugins tree via openclaw config get returns redacted
values for sensitive fields. Writing it back overwrites real secrets with
the __OPENCLAW_REDACTED__ sentinel. Changed to set individual leaf paths
only when missing.
2026-04-16 14:34:07 +00:00
h z
392eafccf2 Merge pull request 'feat(ego-mgr): add lookup subcommand' (#15) from feat/ego-mgr-lookup into main
Reviewed-on: #15
2026-04-14 21:35:37 +00:00
39856a3060 feat(ego-mgr): add lookup subcommand
ego-mgr lookup <username>
  - Finds agent whose default-username == username
  - Echoes the agent-id (map key in agent-scope)
  - Exits 7 if not found or column missing
2026-04-14 21:33:09 +00:00
c6f0393c65 fix: lock-mgr lock identifier if file does not exist 2026-04-13 16:00:40 +01:00
1a202986e8 fix: lock-mgr release meta-lock before exiting 2026-04-13 15:46:49 +01:00
dcc91ead9b fix: lock-mgr get key from arg instead of env 2026-04-13 15:37:13 +01:00
311d9f4d9f feat: add lock-mgr CLI tool and wire into install script
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-12 21:41:51 +01:00
h z
525436d64b Merge pull request 'feat/proxy-pcexec' (#14) from feat/proxy-pcexec into main
Reviewed-on: #14
2026-03-30 11:57:56 +00:00
nav
36f3c93484 fix: preserve existing plugin config on install 2026-03-30 11:56:52 +00:00
nav
1ac75f429c fix: load plugin config from api.pluginConfig 2026-03-30 11:47:42 +00:00
nav
a2b965094d chore: log proxy pcexec auth context 2026-03-30 11:38:05 +00:00
nav
98a75a50d3 feat: add proxy pcexec tool 2026-03-30 11:22:26 +00:00
nav
4a8a4b01cb docs: clarify proxy pcexec rules 2026-03-30 09:22:25 +00:00
nav
95fb9ba820 docs: update proxy pcexec env vars 2026-03-30 09:12:56 +00:00
nav
764ada7c60 chore: organize planning docs 2026-03-30 09:07:00 +00:00
81c0a4c289 Merge pull request 'feat: add default columns to ego.json' (#13) from feat/default-ego-columns into main
Reviewed-on: #13
2026-03-24 19:10:56 +00:00
zhi
4e8e264390 feat: add default columns to ego.json
Initialize ego.json with default columns on first install:
- columns (Agent Scope): default-username, name, discord-id, email, role,
  position, date-of-birth, agent-id, gender
- public-columns (Public Scope): git-host, keycloak-host
2026-03-24 19:10:23 +00:00
21d7a85ba1 Merge pull request 'feat: add /ego-mgr slash command' (#12) from feat/ego-mgr-slash-command into main
Reviewed-on: #12
2026-03-24 19:01:28 +00:00
zhi
7346c80c88 feat: add /ego-mgr slash command
Add /ego-mgr slash command with subcommands:
- get, set, list, delete, add-column, add-public-column, show
- Uses pcexec to call ego-mgr binary with proper env vars

Translate all Chinese text to English in responses.

Note: pcexec tool name and function names remain unchanged.
2026-03-24 10:59:05 +00:00
7fd2819a04 Merge pull request 'feat: rename pass_mgr → secret-mgr, add ego-mgr binary and skill' (#11) from feat/ego-mgr-and-rename into main
Reviewed-on: #11
2026-03-24 09:50:40 +00:00
zhi
98fc3da39c feat: rename pass_mgr → secret-mgr, add ego-mgr binary and skill
M1: Rename pass_mgr to secret-mgr
- Rename directory, binary, and Go module
- Update install.mjs to build/install secret-mgr
- Update pcexec.ts to support secret-mgr patterns (with legacy pass_mgr compat)
- Update plugin config schema (passMgrPath → secretMgrPath)
- Create new skills/secret-mgr/SKILL.md
- install.mjs now initializes ego.json on install

M2: Implement ego-mgr binary (Go)
- Agent Scope and Public Scope column management
- Commands: add column/public-column, delete, set, get, show, list columns
- pcexec environment validation (AGENT_VERIFY, AGENT_ID, AGENT_WORKSPACE)
- File locking for concurrent write safety
- Proper exit codes per spec (0-6)
- Agent auto-registration on read/write
- Global column name uniqueness enforcement

M3: ego-mgr Skill
- Create skills/ego-mgr/SKILL.md with usage guide and examples

Ref: REQUIREMENTS_EGO_MGR.md
2026-03-24 09:36:03 +00:00
nav
be0f194f47 docs: add pass_mgr to secret-mgr migration steps 2026-03-24 00:52:05 +00:00
nav
2816f3a862 docs: remove env var rename note 2026-03-24 00:45:11 +00:00
nav
ce79a782b9 docs: add agent auto-register & column validation rules 2026-03-24 00:43:22 +00:00
nav
63d7fb569e feat: add ego-mgr requirements & secret-mgr rename spec 2026-03-24 00:40:05 +00:00
nav
2f149ed1b4 Fix pass-mgr skill command syntax 2026-03-15 03:49:45 +00:00
123c73cfc6 Merge pull request 'fix(pcexec): include stderr in error message for better debugging' (#10) from fix/pcexec-error-message into main
Reviewed-on: #10
2026-03-15 03:43:58 +00:00
79c5f4cd27 fix(pcexec): include stderr in error message for better debugging 2026-03-09 08:53:04 +00:00
61cffae9ca Merge pull request 'fix: resolve issues #4 #6 #7 #8 for install and pass_mgr' (#9) from fix/issues-4-6-7-8 into main
Reviewed-on: #9
2026-03-09 07:44:39 +00:00
99787e6ded fix: resolve issues #4 #6 #7 #8 for install and pass_mgr 2026-03-08 23:09:16 +00:00
nav
2e38cb8fe2 tighten secret handling guidance 2026-03-08 21:50:44 +00:00
nav
c16149db9d note username optional for pass_mgr set 2026-03-08 21:47:20 +00:00
nav
b00086816c refine pass-mgr usage guidance 2026-03-08 21:44:47 +00:00
nav
a347908d9f add pass-mgr skill 2026-03-08 21:39:29 +00:00
22 changed files with 2204 additions and 426 deletions

View File

@@ -6,7 +6,7 @@
# PaddedCell # 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 ## ⚠️ Security Model
@@ -16,7 +16,7 @@ OpenClaw plugin for secure password management, safe command execution, and coor
## Features ## 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. 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`. Secrets are stored per-agent under `pc-pass-store/<agent-id>/<key>.gpg`.
@@ -24,24 +24,41 @@ Secrets are stored per-agent under `pc-pass-store/<agent-id>/<key>.gpg`.
**Agent commands** (require pcguard — must run through pcexec): **Agent commands** (require pcguard — must run through pcexec):
```bash ```bash
pass_mgr list # List keys for current agent secret-mgr list # List keys for current agent
pass_mgr get-secret --key <key> # Output secret secret-mgr get-secret --key <key> # Output secret
pass_mgr get-username --key <key> # Output username secret-mgr get-username --key <key> # Output username
pass_mgr set --key <key> --secret <s> [--username <u>] # Set entry secret-mgr set --key <key> --secret <s> [--username <u>] # Set entry
pass_mgr generate --key <key> [--username <u>] # Generate random secret secret-mgr generate --key <key> [--username <u>] # Generate random secret
pass_mgr unset --key <key> # Delete entry secret-mgr unset --key <key> # Delete entry
pass_mgr get <key> # Legacy (maps to get-secret) secret-mgr get <key> # Legacy (maps to get-secret)
``` ```
**Admin commands** (human-only — rejected if any `AGENT_*` env var is set): **Admin commands** (human-only — rejected if any `AGENT_*` env var is set):
```bash ```bash
pass_mgr admin init # Set admin password (interactive or PC_ADMIN_PASS) secret-mgr admin handoff [file] # Export build secret to file (default: pc-pass-store.secret)
pass_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
pass_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. 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.
@@ -51,15 +68,15 @@ pcguard || exit 1
# ... rest of script # ... rest of script
``` ```
### 3. pcexec — Safe Execution Tool (TypeScript) ### 4. pcexec — Safe Execution Tool (TypeScript)
Drop-in replacement for `exec` that: 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 - Sanitizes all resolved passwords from stdout/stderr
- Injects `AGENT_VERIFY`, `AGENT_ID`, `AGENT_WORKSPACE` environment variables - 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. Agent state management and coordinated gateway restart.
@@ -76,10 +93,15 @@ PaddedCell/
│ ├── openclaw.plugin.json │ ├── openclaw.plugin.json
│ ├── package.json │ ├── package.json
│ └── tsconfig.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 │ └── src/main.go
├── pcguard/ # Go exec guard binary ├── pcguard/ # Go exec guard binary
│ └── src/main.go │ └── src/main.go
├── skills/ # Agent skills
│ ├── secret-mgr/SKILL.md
│ └── ego-mgr/SKILL.md
├── dist/padded-cell/ # Build output ├── dist/padded-cell/ # Build output
├── install.mjs # Installer ├── install.mjs # Installer
└── README.md └── README.md
@@ -101,7 +123,7 @@ node install.mjs --build-only
node install.mjs --uninstall 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 ### Install paths
@@ -115,14 +137,14 @@ When you rebuild PaddedCell (which generates a new build secret), existing encry
```bash ```bash
# 1. Before updating — export current build secret # 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) # 2. Rebuild & reinstall (generates new .build-secret)
rm .build-secret rm .build-secret
node install.mjs node install.mjs
# 3. After updating — re-encrypt data with new secret # 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 # 4. Restart gateway
openclaw gateway restart openclaw gateway restart
@@ -131,16 +153,24 @@ openclaw gateway restart
## Usage ## Usage
```bash ```bash
# Initialize admin password # Agent sets and gets private passwords (via pcexec)
~/.openclaw/bin/pass_mgr admin init secret-mgr set --key myservice --secret s3cret --username admin
secret-mgr get-secret --key myservice
secret-mgr get-username --key myservice
# Agent sets and gets passwords (via pcexec) # Shared scope (.public)
pass_mgr set --key myservice --secret s3cret --username admin secret-mgr set --public --key shared-api --secret s3cret
pass_mgr get-secret --key myservice secret-mgr list --public
pass_mgr get-username --key myservice secret-mgr get-secret --public --key shared-api
# Use in shell commands (pcexec resolves and sanitizes) # 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 ## License

View 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.5pass_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 能独立使用

View File

@@ -1,14 +1,10 @@
module pass_mgr module ego-mgr
go 1.24.0 go 1.24.0
require ( require github.com/spf13/cobra v1.8.0
github.com/spf13/cobra v1.8.0
golang.org/x/term v0.40.0
)
require ( require (
github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect github.com/spf13/pflag v1.0.5 // indirect
golang.org/x/sys v0.41.0 // indirect
) )

View File

@@ -6,9 +6,5 @@ github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0=
github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho= 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 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.40.0 h1:36e4zGLqU4yhjlmxEaagx2KuYbJq3EwY8K943ZsHcvg=
golang.org/x/term v0.40.0/go.mod h1:w2P8uVp06p2iyKKuvXIm7N/y0UCRt3UfJTfZ7oOpglM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 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= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

517
ego-mgr/src/main.go Normal file
View 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
}

View File

@@ -1,18 +1,20 @@
#!/usr/bin/env node #!/usr/bin/env node
/** /**
* PaddedCell Plugin Installer v0.2.0 * PaddedCell Plugin Installer v0.3.0
*
* Usage:
* node install.mjs
* node install.mjs --openclaw-profile-path /path/to/.openclaw
* node install.mjs --build-only
* node install.mjs --skip-check
* node install.mjs --uninstall
*/ */
import { execSync } from 'child_process'; import { execSync } from 'child_process';
import { existsSync, mkdirSync, copyFileSync, chmodSync, readdirSync, rmSync, readFileSync, writeFileSync } from 'fs'; import {
existsSync,
mkdirSync,
copyFileSync,
chmodSync,
readdirSync,
rmSync,
readFileSync,
writeFileSync,
} from 'fs';
import { randomBytes } from 'crypto'; import { randomBytes } from 'crypto';
import { dirname, join, resolve } from 'path'; import { dirname, join, resolve } from 'path';
import { fileURLToPath } from 'url'; import { fileURLToPath } from 'url';
@@ -24,7 +26,6 @@ const __dirname = resolve(dirname(__filename));
const PLUGIN_NAME = 'padded-cell'; const PLUGIN_NAME = 'padded-cell';
const SRC_DIST_DIR = join(__dirname, 'dist', PLUGIN_NAME); const SRC_DIST_DIR = join(__dirname, 'dist', PLUGIN_NAME);
// Parse arguments
const args = process.argv.slice(2); const args = process.argv.slice(2);
const options = { const options = {
openclawProfilePath: null, openclawProfilePath: null,
@@ -32,22 +33,20 @@ const options = {
skipCheck: args.includes('--skip-check'), skipCheck: args.includes('--skip-check'),
verbose: args.includes('--verbose') || args.includes('-v'), verbose: args.includes('--verbose') || args.includes('-v'),
uninstall: args.includes('--uninstall'), uninstall: args.includes('--uninstall'),
installOnly: args.includes('--install'),
}; };
// Parse --openclaw-profile-path value
const profileIdx = args.indexOf('--openclaw-profile-path'); const profileIdx = args.indexOf('--openclaw-profile-path');
if (profileIdx !== -1 && args[profileIdx + 1]) { if (profileIdx !== -1 && args[profileIdx + 1]) {
options.openclawProfilePath = resolve(args[profileIdx + 1]); options.openclawProfilePath = resolve(args[profileIdx + 1]);
} }
// Resolve openclaw path: --openclaw-profile-path → $OPENCLAW_PATH → ~/.openclaw
function resolveOpenclawPath() { function resolveOpenclawPath() {
if (options.openclawProfilePath) return options.openclawProfilePath; if (options.openclawProfilePath) return options.openclawProfilePath;
if (process.env.OPENCLAW_PATH) return resolve(process.env.OPENCLAW_PATH); if (process.env.OPENCLAW_PATH) return resolve(process.env.OPENCLAW_PATH);
return join(homedir(), '.openclaw'); return join(homedir(), '.openclaw');
} }
// Colors
const c = { const c = {
reset: '\x1b[0m', red: '\x1b[31m', green: '\x1b[32m', reset: '\x1b[0m', red: '\x1b[31m', green: '\x1b[32m',
yellow: '\x1b[33m', blue: '\x1b[34m', cyan: '\x1b[36m', yellow: '\x1b[33m', blue: '\x1b[34m', cyan: '\x1b[36m',
@@ -86,26 +85,20 @@ function copyDir(src, dest) {
for (const entry of readdirSync(src, { withFileTypes: true })) { for (const entry of readdirSync(src, { withFileTypes: true })) {
const s = join(src, entry.name); const s = join(src, entry.name);
const d = join(dest, entry.name); const d = join(dest, entry.name);
if (entry.name === 'node_modules') continue; // skip node_modules if (entry.name === 'node_modules') continue;
entry.isDirectory() ? copyDir(s, d) : copyFileSync(s, d); entry.isDirectory() ? copyDir(s, d) : copyFileSync(s, d);
} }
} }
// ── Step 1: Detect ──────────────────────────────────────────────────────
function detectEnvironment() { function detectEnvironment() {
logStep(1, 6, 'Detecting environment...'); logStep(1, 6, 'Detecting environment...');
const env = { platform: platform(), nodeVersion: null, goVersion: null }; 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.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 { 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'); } try { logOk(`openclaw at ${exec('which openclaw', { silent: true }).trim()}`); } catch { logWarn('openclaw CLI not in PATH'); }
return env; return env;
} }
// ── Step 2: Check deps ──────────────────────────────────────────────────
function checkDeps(env) { function checkDeps(env) {
if (options.skipCheck) { logStep(2, 6, 'Skipping dep checks'); return; } if (options.skipCheck) { logStep(2, 6, 'Skipping dep checks'); return; }
logStep(2, 6, 'Checking dependencies...'); logStep(2, 6, 'Checking dependencies...');
@@ -116,8 +109,6 @@ function checkDeps(env) {
logOk('All deps OK'); logOk('All deps OK');
} }
// ── Step 3: Build ───────────────────────────────────────────────────────
function ensureBuildSecret() { function ensureBuildSecret() {
const secretFile = join(__dirname, '.build-secret'); const secretFile = join(__dirname, '.build-secret');
if (existsSync(secretFile)) { if (existsSync(secretFile)) {
@@ -136,19 +127,25 @@ function ensureBuildSecret() {
async function build() { async function build() {
logStep(3, 6, 'Building components...'); logStep(3, 6, 'Building components...');
// Generate / load build secret for pass_mgr
const buildSecret = ensureBuildSecret(); const buildSecret = ensureBuildSecret();
// pass_mgr (Go) 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 }); exec('go mod tidy', { cwd: pmDir, silent: !options.verbose });
const ldflags = `-X main.buildSecret=${buildSecret}`; const ldflags = `-X main.buildSecret=${buildSecret}`;
exec(`go build -ldflags "${ldflags}" -o dist/pass_mgr src/main.go`, { cwd: pmDir, silent: !options.verbose }); exec(`go build -ldflags "${ldflags}" -o dist/secret-mgr src/main.go`, { cwd: pmDir, silent: !options.verbose });
chmodSync(join(pmDir, 'dist', 'pass_mgr'), 0o755); chmodSync(join(pmDir, 'dist', 'secret-mgr'), 0o755);
logOk('pass_mgr'); 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');
// pcguard (Go)
log(' Building pcguard...', 'blue'); log(' Building pcguard...', 'blue');
const pgDir = join(__dirname, 'pcguard'); const pgDir = join(__dirname, 'pcguard');
exec('go mod tidy', { cwd: pgDir, silent: !options.verbose }); exec('go mod tidy', { cwd: pgDir, silent: !options.verbose });
@@ -156,15 +153,96 @@ async function build() {
chmodSync(join(pgDir, 'dist', 'pcguard'), 0o755); chmodSync(join(pgDir, 'dist', 'pcguard'), 0o755);
logOk('pcguard'); logOk('pcguard');
// Plugin (TypeScript) 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'); log(' Building plugin...', 'blue');
const pluginDir = join(__dirname, 'plugin'); const pluginDir = join(__dirname, 'plugin');
exec('npm install', { cwd: pluginDir, silent: !options.verbose }); exec('npm install', { cwd: pluginDir, silent: !options.verbose });
exec('npx tsc', { cwd: pluginDir, silent: !options.verbose }); exec('npx tsc', { cwd: pluginDir, silent: !options.verbose });
logOk('plugin'); 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');
}
} }
// ── Step 4: Install ───────────────────────────────────────────────────── 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() { async function install() {
if (options.buildOnly) { logStep(4, 6, 'Skipping install (--build-only)'); return null; } if (options.buildOnly) { logStep(4, 6, 'Skipping install (--build-only)'); return null; }
@@ -174,27 +252,35 @@ async function install() {
const binDir = join(openclawPath, 'bin'); const binDir = join(openclawPath, 'bin');
const pluginsDir = join(openclawPath, 'plugins'); const pluginsDir = join(openclawPath, 'plugins');
const destDir = join(pluginsDir, PLUGIN_NAME); const destDir = join(pluginsDir, PLUGIN_NAME);
const skillsDir = join(openclawPath, 'skills');
const distSkillsDir = join(SRC_DIST_DIR, 'skills');
log(` OpenClaw path: ${openclawPath}`, 'blue'); log(` OpenClaw path: ${openclawPath}`, 'blue');
// Copy dist/padded-cell → plugins/padded-cell // 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 }); if (existsSync(destDir)) rmSync(destDir, { recursive: true, force: true });
copyDir(SRC_DIST_DIR, destDir); copyDir(SRC_DIST_DIR, destDir);
// Copy openclaw.plugin.json and package.json
copyFileSync(join(__dirname, 'plugin', 'openclaw.plugin.json'), join(destDir, 'openclaw.plugin.json')); copyFileSync(join(__dirname, 'plugin', 'openclaw.plugin.json'), join(destDir, 'openclaw.plugin.json'));
copyFileSync(join(__dirname, 'plugin', 'package.json'), join(destDir, 'package.json')); copyFileSync(join(__dirname, 'plugin', 'package.json'), join(destDir, 'package.json'));
logOk(`Plugin files → ${destDir}`); logOk(`Plugin files → ${destDir}`);
// Install runtime deps into dest (express, ws)
exec('npm install --omit=dev', { cwd: destDir, silent: !options.verbose }); exec('npm install --omit=dev', { cwd: destDir, silent: !options.verbose });
logOk('Runtime deps installed'); logOk('Runtime deps installed');
// Binaries
mkdirSync(binDir, { recursive: true }); mkdirSync(binDir, { recursive: true });
const bins = [ 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: 'pcguard', src: join(__dirname, 'pcguard', 'dist', 'pcguard') },
{ name: 'lock-mgr', src: join(__dirname, 'lock-mgr', 'dist', 'lock-mgr') },
]; ];
for (const b of bins) { for (const b of bins) {
const dest = join(binDir, b.name); const dest = join(binDir, b.name);
@@ -203,58 +289,91 @@ async function install() {
logOk(`${b.name}${dest}`); 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 }; return { binDir, destDir };
} }
// ── Step 5: Configure ───────────────────────────────────────────────────
async function configure() { async function configure() {
if (options.buildOnly) { logStep(5, 6, 'Skipping config'); return; } if (options.buildOnly) { logStep(5, 6, 'Skipping config'); return; }
logStep(5, 6, 'Configuring OpenClaw...'); logStep(5, 6, 'Configuring OpenClaw...');
const openclawPath = resolveOpenclawPath(); const openclawPath = resolveOpenclawPath();
const destDir = join(openclawPath, 'plugins', PLUGIN_NAME); const destDir = join(openclawPath, 'plugins', PLUGIN_NAME);
const passMgrPath = join(openclawPath, 'bin', 'pass_mgr'); const secretMgrPath = join(openclawPath, 'bin', 'secret-mgr');
try { try {
// plugins.load.paths
const paths = getOpenclawConfig('plugins.load.paths', []); const paths = getOpenclawConfig('plugins.load.paths', []);
if (!paths.includes(destDir)) { paths.push(destDir); setOpenclawConfig('plugins.load.paths', paths); } if (!paths.includes(destDir)) { paths.push(destDir); setOpenclawConfig('plugins.load.paths', paths); }
logOk(`plugins.load.paths includes ${destDir}`); logOk(`plugins.load.paths includes ${destDir}`);
// plugins.allow
const allow = getOpenclawConfig('plugins.allow', []); const allow = getOpenclawConfig('plugins.allow', []);
if (!allow.includes(PLUGIN_NAME)) { allow.push(PLUGIN_NAME); setOpenclawConfig('plugins.allow', allow); } if (!allow.includes(PLUGIN_NAME)) { allow.push(PLUGIN_NAME); setOpenclawConfig('plugins.allow', allow); }
logOk(`plugins.allow includes ${PLUGIN_NAME}`); logOk(`plugins.allow includes ${PLUGIN_NAME}`);
// plugins.entries const entryPath = `plugins.entries.${PLUGIN_NAME}`;
const plugins = getOpenclawConfig('plugins', {}); const existingEnabled = getOpenclawConfig(`${entryPath}.enabled`, undefined);
plugins.entries = plugins.entries || {}; if (existingEnabled === undefined) setOpenclawConfig(`${entryPath}.enabled`, true);
plugins.entries[PLUGIN_NAME] = {
enabled: true, const cfgPath = `${entryPath}.config`;
config: { enabled: true, passMgrPath, openclawProfilePath: openclawPath }, const existingCfgEnabled = getOpenclawConfig(`${cfgPath}.enabled`, undefined);
}; if (existingCfgEnabled === undefined) setOpenclawConfig(`${cfgPath}.enabled`, true);
setOpenclawConfig('plugins', plugins);
logOk('Plugin entry configured'); 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) { } catch (err) {
logWarn(`Config failed: ${err.message}`); logWarn(`Config failed: ${err.message}`);
} }
// Check pass_mgr init
if (existsSync(join(homedir(), '.pass_mgr', 'config.json'))) {
logOk('pass_mgr already initialized');
} else {
logWarn(`pass_mgr not initialized — run: ${passMgrPath} admin init`);
}
} }
// ── Step 6: Summary ───────────────────────────────────────────────────── function summary() {
function summary(result) {
logStep(6, 6, 'Done!'); logStep(6, 6, 'Done!');
console.log(''); console.log('');
log('╔══════════════════════════════════════════════╗', 'cyan'); log('╔══════════════════════════════════════════════╗', 'cyan');
log('║ PaddedCell v0.2.0 Install Complete ║', 'cyan'); log('║ PaddedCell v0.3.0 Install Complete ║', 'cyan');
log('╚══════════════════════════════════════════════╝', 'cyan'); log('╚══════════════════════════════════════════════╝', 'cyan');
if (options.buildOnly) { if (options.buildOnly) {
@@ -265,63 +384,42 @@ function summary(result) {
console.log(''); console.log('');
log('Next steps:', 'blue'); log('Next steps:', 'blue');
log(' 1. openclaw gateway restart', 'cyan'); log(' 1. openclaw gateway restart', 'cyan');
const openclawPath = resolveOpenclawPath();
const pmPath = join(openclawPath, 'bin', 'pass_mgr');
if (!existsSync(join(homedir(), '.pass_mgr', 'config.json'))) {
log(` 2. ${pmPath} admin init`, 'cyan');
}
console.log(''); console.log('');
} }
// ── Uninstall ───────────────────────────────────────────────────────────
async function uninstall() { async function uninstall() {
log('Uninstalling PaddedCell...', 'cyan'); log('Uninstalling PaddedCell...', 'cyan');
const openclawPath = resolveOpenclawPath(); const openclawPath = resolveOpenclawPath();
handoffSecretIfPossible(openclawPath);
// Remove binaries clearInstallTargets(openclawPath);
for (const name of ['pass_mgr', 'pcguard']) { cleanupConfig(openclawPath);
const p = join(openclawPath, 'bin', name);
if (existsSync(p)) { rmSync(p); logOk(`Removed ${p}`); }
}
// Remove plugin dir
const destDir = join(openclawPath, 'plugins', PLUGIN_NAME);
if (existsSync(destDir)) { rmSync(destDir, { recursive: true }); logOk(`Removed ${destDir}`); }
// Remove config
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'); }
} catch (err) { logWarn(`Config cleanup: ${err.message}`); }
log('\nRun: openclaw gateway restart', 'yellow'); log('\nRun: openclaw gateway restart', 'yellow');
} }
// ── Main ────────────────────────────────────────────────────────────────
async function main() { async function main() {
console.log(''); console.log('');
log('╔══════════════════════════════════════════════╗', 'cyan'); log('╔══════════════════════════════════════════════╗', 'cyan');
log('║ PaddedCell Plugin Installer v0.2.0 ║', 'cyan'); log('║ PaddedCell Plugin Installer v0.3.0 ║', 'cyan');
log('╚══════════════════════════════════════════════╝', 'cyan'); log('╚══════════════════════════════════════════════╝', 'cyan');
console.log(''); console.log('');
try { try {
const env = detectEnvironment(); const env = detectEnvironment();
if (options.uninstall) { await uninstall(); process.exit(0); }
if (options.uninstall) {
await uninstall();
process.exit(0);
}
checkDeps(env); checkDeps(env);
await build(); await build();
const result = await install();
if (!options.buildOnly) {
await install();
await configure(); await configure();
summary(result); }
summary();
} catch (err) { } catch (err) {
log(`\nInstallation failed: ${err.message}`, 'red'); log(`\nInstallation failed: ${err.message}`, 'red');
process.exit(1); process.exit(1);

3
lock-mgr/go.mod Normal file
View File

@@ -0,0 +1,3 @@
module lock-mgr
go 1.24.0

380
lock-mgr/main.go Normal file
View 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
View 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` 限制

View 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, "'\"'\"'")}'`;
}
}

View File

@@ -48,7 +48,7 @@ export class SlashCommandHandler {
async handle(command: string, userId: string): Promise<void> { async handle(command: string, userId: string): Promise<void> {
// Check authorization // Check authorization
if (!this.authorizedUsers.includes(userId)) { if (!this.authorizedUsers.includes(userId)) {
await this.onReply('❌ 无权执行此命令'); await this.onReply('Unauthorized');
return; return;
} }
@@ -68,10 +68,10 @@ export class SlashCommandHandler {
break; break;
default: default:
await this.onReply( await this.onReply(
'用法:\n' + 'Usage:\n' +
'`/padded-cell-ctrl status` - 查看状态\n' + '`/padded-cell-ctrl status` - Show status\n' +
'`/padded-cell-ctrl enable pass-mgr|safe-restart` - 启用功能\n' + '`/padded-cell-ctrl enable pass-mgr|safe-restart` - Enable feature\n' +
'`/padded-cell-ctrl disable pass-mgr|safe-restart` - 禁用功能' '`/padded-cell-ctrl disable pass-mgr|safe-restart` - Disable feature'
); );
} }
} }
@@ -81,12 +81,12 @@ export class SlashCommandHandler {
const agents = this.statusManager.getAllAgents(); const agents = this.statusManager.getAllAgents();
const lines = [ const lines = [
'**PaddedCell 状态**', '**PaddedCell Status**',
'', '',
`🔐 密码管理: ${this.state.passMgrEnabled ? '✅ 启用' : '❌ 禁用'}`, `Secret Manager: ${this.state.passMgrEnabled ? 'Enabled' : 'Disabled'}`,
`🔄 安全重启: ${this.state.safeRestartEnabled ? '✅ 启用' : '❌ 禁用'}`, `Safe Restart: ${this.state.safeRestartEnabled ? 'Enabled' : 'Disabled'}`,
'', '',
'**Agent 状态:**', '**Agent Status:**',
]; ];
for (const agent of agents) { for (const agent of agents) {
@@ -95,14 +95,14 @@ export class SlashCommandHandler {
} }
if (agents.length === 0) { if (agents.length === 0) {
lines.push('(暂无 agent 注册)'); lines.push('(No agents registered)');
} }
if (global.restartStatus !== 'idle') { if (global.restartStatus !== 'idle') {
lines.push(''); lines.push('');
lines.push(`⚠️ 重启状态: ${global.restartStatus}`); lines.push(`Restart Status: ${global.restartStatus}`);
if (global.restartScheduledBy) { 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> { private async handleEnable(feature: 'pass-mgr' | 'safe-restart'): Promise<void> {
if (!this.isValidFeature(feature)) { if (!this.isValidFeature(feature)) {
await this.onReply('❌ 未知功能。可用选项: pass-mgr, safe-restart'); await this.onReply('Unknown feature. Available: pass-mgr, safe-restart');
return; return;
} }
if (this.isOnCooldown(feature)) { if (this.isOnCooldown(feature)) {
await this.onReply('⏳ 该功能最近刚被修改过,请稍后再试'); await this.onReply('This feature was recently modified. Please try again later.');
return; return;
} }
@@ -127,17 +127,17 @@ export class SlashCommandHandler {
} }
this.state.lastToggle[feature] = Date.now(); 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> { private async handleDisable(feature: 'pass-mgr' | 'safe-restart'): Promise<void> {
if (!this.isValidFeature(feature)) { if (!this.isValidFeature(feature)) {
await this.onReply('❌ 未知功能。可用选项: pass-mgr, safe-restart'); await this.onReply('Unknown feature. Available: pass-mgr, safe-restart');
return; return;
} }
if (this.isOnCooldown(feature)) { if (this.isOnCooldown(feature)) {
await this.onReply('⏳ 该功能最近刚被修改过,请稍后再试'); await this.onReply('This feature was recently modified. Please try again later.');
return; return;
} }
@@ -148,7 +148,7 @@ export class SlashCommandHandler {
} }
this.state.lastToggle[feature] = Date.now(); 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' { private isValidFeature(feature: string): feature is 'pass-mgr' | 'safe-restart' {

View File

@@ -10,6 +10,7 @@ import {
startApiServer, startApiServer,
} from './core/index'; } from './core/index';
import { SlashCommandHandler } from './commands/slash-commands'; import { SlashCommandHandler } from './commands/slash-commands';
import { EgoMgrSlashCommand } from './commands/ego-mgr-slash';
/** Sentinel value injected into every pcexec subprocess */ /** Sentinel value injected into every pcexec subprocess */
const AGENT_VERIFY = 'IF YOU ARE AN AGENT/MODEL, YOU SHOULD NEVER TOUCH THIS ENV VARIABLE'; 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'); 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 // Plugin registration function
function register(api: any, config?: any) { function register(api: any) {
const logger = api.logger || { info: console.log, error: console.error }; const logger = api.logger || { info: console.log, error: console.error };
logger.info('PaddedCell plugin initializing...'); logger.info('PaddedCell plugin initializing...');
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'); const binDir = require('path').join(openclawPath, 'bin');
// Register pcexec tool — pass a FACTORY function that receives context // 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 // Register safe_restart tool
api.registerTool((ctx: any) => { api.registerTool((ctx: any) => {
const agentId = ctx.agentId; 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'); logger.info('PaddedCell plugin initialized');
} }
@@ -125,4 +223,5 @@ module.exports.StatusManager = StatusManager;
module.exports.createApiServer = createApiServer; module.exports.createApiServer = createApiServer;
module.exports.startApiServer = startApiServer; module.exports.startApiServer = startApiServer;
module.exports.SlashCommandHandler = SlashCommandHandler; module.exports.SlashCommandHandler = SlashCommandHandler;
module.exports.EgoMgrSlashCommand = EgoMgrSlashCommand;
module.exports.AGENT_VERIFY = AGENT_VERIFY; module.exports.AGENT_VERIFY = AGENT_VERIFY;

View File

@@ -2,14 +2,19 @@
"id": "padded-cell", "id": "padded-cell",
"name": "PaddedCell", "name": "PaddedCell",
"version": "0.2.0", "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", "entry": "./index.js",
"configSchema": { "configSchema": {
"type": "object", "type": "object",
"properties": { "properties": {
"enabled": { "type": "boolean", "default": true }, "enabled": { "type": "boolean", "default": true },
"passMgrPath": { "type": "string", "default": "" }, "secretMgrPath": { "type": "string", "default": "" },
"openclawProfilePath": { "type": "string", "default": "" } "openclawProfilePath": { "type": "string", "default": "" },
"proxyAllowlist": {
"type": "array",
"items": { "type": "string" },
"default": []
}
} }
} }
} }

View File

@@ -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: * 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>` * Legacy: $(pass_mgr get <key>) / `pass_mgr get <key>`
* New: $(pass_mgr get-secret --key <key>) / `pass_mgr get-secret --key <key>`
* *
* Returns array of { fullMatch, subcommand, key } where subcommand is * Returns array of { fullMatch, subcommand, key, binary } where subcommand is
* "get" | "get-secret". * "get" | "get-secret".
*/ */
function extractPassMgrGets( function extractSecretMgrGets(
command: string, command: string,
): 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 }> = []; const results: Array<{ key: string; fullMatch: string; subcommand: string; binary: string }> = [];
const seen = new Set<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 = [ 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,
/`\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 = [ const legacyPatterns = [
/\$\(\s*pass_mgr\s+get\s+(\S+)\s*\)/g, /\$\(\s*pass_mgr\s+get\s+(\S+)\s*\)/g,
/`\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) { for (const pattern of newPatterns) {
let match; let match;
while ((match = pattern.exec(command)) !== null) { while ((match = pattern.exec(command)) !== null) {
@@ -82,6 +104,7 @@ function extractPassMgrGets(
key: match[1], key: match[1],
fullMatch: match[0], fullMatch: match[0],
subcommand: 'get-secret', subcommand: 'get-secret',
binary: 'pass_mgr',
}); });
} }
} }
@@ -96,6 +119,7 @@ function extractPassMgrGets(
key: match[1], key: match[1],
fullMatch: match[0], fullMatch: match[0],
subcommand: 'get', 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. * Uses the same env vars that the caller passes so pcguard checks pass.
*/ */
async function fetchPassword( async function fetchPassword(
subcommand: string, subcommand: string,
key: string, key: string,
env: Record<string, string>, env: Record<string, string>,
binary: string = 'secret-mgr',
): Promise<string> { ): Promise<string> {
return new Promise((resolve, reject) => { 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 = const args =
subcommand === 'get-secret' subcommand === 'get-secret'
? ['get-secret', '--key', key] ? ['get-secret', '--key', key]
: ['get', key]; : ['get', key];
const child = spawn(passMgrPath, args, { const child = spawn(binaryPath, args, {
stdio: ['ignore', 'pipe', 'pipe'], stdio: ['ignore', 'pipe', 'pipe'],
env: { ...process.env, ...env }, env: { ...process.env, ...env },
}); });
@@ -131,7 +157,7 @@ async function fetchPassword(
child.stderr.on('data', (d) => (stderr += d.toString())); child.stderr.on('data', (d) => (stderr += d.toString()));
child.on('close', (code) => { child.on('close', (code) => {
if (code !== 0) { if (code !== 0) {
reject(new Error(`pass_mgr ${subcommand} failed: ${stderr || stdout}`)); reject(new Error(`secret-mgr ${subcommand} failed: ${stderr || stdout}`));
} else { } else {
resolve(stdout.trim()); 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, command: string,
env: Record<string, string>, env: Record<string, string>,
): Promise<{ command: string; passwords: string[] }> { ): Promise<{ command: string; passwords: string[] }> {
const matches = extractPassMgrGets(command); const matches = extractSecretMgrGets(command);
const passwords: string[] = []; const passwords: string[] = [];
let replaced = command; let replaced = command;
for (const { key, fullMatch, subcommand } of matches) { for (const { key, fullMatch, subcommand, binary } of matches) {
const pw = await fetchPassword(subcommand, key, env); const pw = await fetchPassword(subcommand, key, env, binary);
passwords.push(pw); passwords.push(pw);
replaced = replaced.split(fullMatch).join(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( export async function pcexec(
command: string, command: string,
@@ -193,7 +219,7 @@ export async function pcexec(
let finalCommand = command; let finalCommand = command;
let passwords: string[] = []; let passwords: string[] = [];
const resolved = await replacePassMgrGets(command, env); const resolved = await replaceSecretMgrGets(command, env);
finalCommand = resolved.command; finalCommand = resolved.command;
passwords = resolved.passwords; passwords = resolved.passwords;
@@ -249,7 +275,7 @@ export async function pcexec(
command: finalCommand, command: finalCommand,
}); });
} else { } 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.code = code ?? undefined;
error.signal = signal ?? undefined; error.signal = signal ?? undefined;
error.stdout = sanitizedStdout; error.stdout = sanitizedStdout;
@@ -271,7 +297,7 @@ export async function pcexec(
/** /**
* Synchronous version — password substitution is NOT supported here * 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( export function pcexecSync(
command: string, command: string,

10
secret-mgr/go.mod Normal file
View 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
View 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=

View File

@@ -12,10 +12,8 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"syscall"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"golang.org/x/term"
) )
// buildSecret is injected at compile time via -ldflags "-X main.buildSecret=<hex>" // buildSecret is injected at compile time via -ldflags "-X main.buildSecret=<hex>"
@@ -23,16 +21,14 @@ var buildSecret string
const ( const (
PassStoreDirName = "pc-pass-store" PassStoreDirName = "pc-pass-store"
AdminDirName = ".pass_mgr" PublicDirName = ".public"
AdminFile = "admin.json"
// Must match pcguard sentinel // Must match pcguard sentinel
expectedAgentVerify = "IF YOU ARE AN AGENT/MODEL, YOU SHOULD NEVER TOUCH THIS ENV VARIABLE" expectedAgentVerify = "IF YOU ARE AN AGENT/MODEL, YOU SHOULD NEVER TOUCH THIS ENV VARIABLE"
) )
// ── Data types ──────────────────────────────────────────────────────────
// EncryptedFile is the on-disk format for .gpg files // EncryptedFile is the on-disk format for .gpg files
// (kept for compatibility with existing files)
type EncryptedFile struct { type EncryptedFile struct {
Nonce string `json:"nonce"` Nonce string `json:"nonce"`
Data string `json:"data"` Data string `json:"data"`
@@ -44,13 +40,6 @@ type Entry struct {
Secret string `json:"secret"` Secret string `json:"secret"`
} }
// AdminConfig stores hashed admin password
type AdminConfig struct {
PasswordHash string `json:"password_hash"`
}
// ── Helpers ─────────────────────────────────────────────────────────────
func resolveOpenclawPath() string { func resolveOpenclawPath() string {
if p := os.Getenv("OPENCLAW_PATH"); p != "" { if p := os.Getenv("OPENCLAW_PATH"); p != "" {
return p return p
@@ -59,38 +48,35 @@ func resolveOpenclawPath() string {
return filepath.Join(home, ".openclaw") return filepath.Join(home, ".openclaw")
} }
func passStoreBase() string { func passStoreBase() string { return filepath.Join(resolveOpenclawPath(), PassStoreDirName) }
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 agentStoreDir(agentID string) string {
return filepath.Join(passStoreBase(), agentID)
}
func adminDir() string {
return filepath.Join(resolveOpenclawPath(), AdminDirName)
}
func adminConfigPath() string {
return filepath.Join(adminDir(), AdminFile)
}
// deriveKey returns AES-256 key from SHA-256 of the given secret string
func deriveKey(secret string) []byte {
h := sha256.Sum256([]byte(secret))
return h[:]
}
// currentKey returns the AES key derived from the compiled-in buildSecret
func currentKey() ([]byte, error) { func currentKey() ([]byte, error) {
if buildSecret == "" { 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 return deriveKey(buildSecret), nil
} }
// ── Encryption ──────────────────────────────────────────────────────────
func encrypt(plaintext, key []byte) (*EncryptedFile, error) { func encrypt(plaintext, key []byte) (*EncryptedFile, error) {
block, err := aes.NewCipher(key) block, err := aes.NewCipher(key)
if err != nil { if err != nil {
@@ -105,10 +91,7 @@ func encrypt(plaintext, key []byte) (*EncryptedFile, error) {
return nil, err return nil, err
} }
ciphertext := gcm.Seal(nil, nonce, plaintext, nil) ciphertext := gcm.Seal(nil, nonce, plaintext, nil)
return &EncryptedFile{ return &EncryptedFile{Nonce: base64.StdEncoding.EncodeToString(nonce), Data: base64.StdEncoding.EncodeToString(ciphertext)}, nil
Nonce: base64.StdEncoding.EncodeToString(nonce),
Data: base64.StdEncoding.EncodeToString(ciphertext),
}, nil
} }
func decrypt(ef *EncryptedFile, key []byte) ([]byte, error) { func decrypt(ef *EncryptedFile, key []byte) ([]byte, error) {
@@ -131,8 +114,6 @@ func decrypt(ef *EncryptedFile, key []byte) ([]byte, error) {
return gcm.Open(nil, nonce, ciphertext, nil) return gcm.Open(nil, nonce, ciphertext, nil)
} }
// ── Entry I/O ───────────────────────────────────────────────────────────
func readEntry(filePath string, key []byte) (*Entry, error) { func readEntry(filePath string, key []byte) (*Entry, error) {
raw, err := os.ReadFile(filePath) raw, err := os.ReadFile(filePath)
if err != nil { if err != nil {
@@ -163,8 +144,6 @@ func writeEntry(filePath string, entry *Entry, key []byte) error {
return os.WriteFile(filePath, data, 0600) return os.WriteFile(filePath, data, 0600)
} }
// ── pcguard inline check ────────────────────────────────────────────────
func requirePcguard() { func requirePcguard() {
if os.Getenv("AGENT_VERIFY") != expectedAgentVerify { if os.Getenv("AGENT_VERIFY") != expectedAgentVerify {
fmt.Fprintln(os.Stderr, "Error: must be invoked via pcexec (AGENT_VERIFY mismatch)") fmt.Fprintln(os.Stderr, "Error: must be invoked via pcexec (AGENT_VERIFY mismatch)")
@@ -180,77 +159,6 @@ func requirePcguard() {
} }
} }
func currentAgentID() string {
return os.Getenv("AGENT_ID")
}
// ── Admin helpers ───────────────────────────────────────────────────────
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 hashPassword(pw string) string {
h := sha256.Sum256([]byte(pw))
return fmt.Sprintf("%x", h)
}
func loadAdminConfig() (*AdminConfig, error) {
raw, err := os.ReadFile(adminConfigPath())
if err != nil {
return nil, err
}
var cfg AdminConfig
if err := json.Unmarshal(raw, &cfg); err != nil {
return nil, err
}
return &cfg, nil
}
func saveAdminConfig(cfg *AdminConfig) error {
if err := os.MkdirAll(adminDir(), 0700); err != nil {
return err
}
data, _ := json.MarshalIndent(cfg, "", " ")
return os.WriteFile(adminConfigPath(), data, 0600)
}
func verifyAdminPassword() error {
cfg, err := loadAdminConfig()
if err != nil {
return fmt.Errorf("admin not initialized — run 'pass_mgr admin init' first")
}
var password string
if envPw := os.Getenv("PC_ADMIN_PASS"); envPw != "" {
password = envPw
} else {
fmt.Fprint(os.Stderr, "Admin password: ")
raw, err := term.ReadPassword(int(syscall.Stdin))
if err != nil {
return fmt.Errorf("failed to read password: %w", err)
}
fmt.Fprintln(os.Stderr)
password = strings.TrimSpace(string(raw))
}
if hashPassword(password) != cfg.PasswordHash {
return fmt.Errorf("invalid admin password")
}
return nil
}
// ── Password generation ─────────────────────────────────────────────────
func generatePassword(length int) (string, error) { func generatePassword(length int) (string, error) {
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_=+" const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_=+"
buf := make([]byte, length) buf := make([]byte, length)
@@ -264,63 +172,66 @@ func generatePassword(length int) (string, error) {
return string(buf), nil return string(buf), nil
} }
// ── Commands ────────────────────────────────────────────────────────────
func main() { func main() {
rootCmd := &cobra.Command{ rootCmd := &cobra.Command{Use: "secret-mgr", Short: "Secret manager for OpenClaw agents"}
Use: "pass_mgr", rootCmd.AddCommand(listCmd(), getSecretCmd(), getUsernameCmd(), getLegacyCmd(), setCmd(), generateCmd(), unsetCmd(), adminCmd())
Short: "Password manager for OpenClaw agents",
}
rootCmd.AddCommand(
listCmd(),
getSecretCmd(),
getUsernameCmd(),
getLegacyCmd(), // backward compat: pass_mgr get <key>
setCmd(),
generateCmd(),
unsetCmd(),
adminCmd(),
)
if err := rootCmd.Execute(); err != nil { if err := rootCmd.Execute(); err != nil {
os.Exit(1) os.Exit(1)
} }
} }
// ── list ───────────────────────────────────────────────────────────────── func listKeys(dir string) []string {
func listCmd() *cobra.Command {
return &cobra.Command{
Use: "list",
Short: "List keys for current agent",
Run: func(cmd *cobra.Command, args []string) {
requirePcguard()
dir := agentStoreDir(currentAgentID())
entries, err := os.ReadDir(dir) entries, err := os.ReadDir(dir)
if err != nil { if err != nil {
if os.IsNotExist(err) { if os.IsNotExist(err) {
return // no keys yet return nil
} }
fmt.Fprintf(os.Stderr, "Error: %v\n", err) fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1) os.Exit(1)
} }
out := []string{}
for _, e := range entries { for _, e := range entries {
name := e.Name() name := e.Name()
if strings.HasSuffix(name, ".gpg") { if strings.HasSuffix(name, ".gpg") {
fmt.Println(strings.TrimSuffix(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
} }
// ── get-secret ──────────────────────────────────────────────────────────
func getSecretCmd() *cobra.Command { func getSecretCmd() *cobra.Command {
var keyFlag string var keyFlag string
var public bool
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "get-secret", Use: "get-secret",
Aliases: []string{"get_secret"},
Short: "Get secret for a key", Short: "Get secret for a key",
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
requirePcguard() requirePcguard()
@@ -333,7 +244,7 @@ func getSecretCmd() *cobra.Command {
fmt.Fprintf(os.Stderr, "Error: %v\n", err) fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1) os.Exit(1)
} }
fp := filepath.Join(agentStoreDir(currentAgentID()), keyFlag+".gpg") fp := filepath.Join(resolveStoreDir(public), keyFlag+".gpg")
entry, err := readEntry(fp, key) entry, err := readEntry(fp, key)
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err) fmt.Fprintf(os.Stderr, "Error: %v\n", err)
@@ -343,15 +254,16 @@ func getSecretCmd() *cobra.Command {
}, },
} }
cmd.Flags().StringVar(&keyFlag, "key", "", "Key name") cmd.Flags().StringVar(&keyFlag, "key", "", "Key name")
cmd.Flags().BoolVar(&public, "public", false, "Use shared public scope only")
return cmd return cmd
} }
// ── get-username ────────────────────────────────────────────────────────
func getUsernameCmd() *cobra.Command { func getUsernameCmd() *cobra.Command {
var keyFlag string var keyFlag string
var public bool
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "get-username", Use: "get-username",
Aliases: []string{"get_username"},
Short: "Get username for a key", Short: "Get username for a key",
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
requirePcguard() requirePcguard()
@@ -364,7 +276,7 @@ func getUsernameCmd() *cobra.Command {
fmt.Fprintf(os.Stderr, "Error: %v\n", err) fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1) os.Exit(1)
} }
fp := filepath.Join(agentStoreDir(currentAgentID()), keyFlag+".gpg") fp := filepath.Join(resolveStoreDir(public), keyFlag+".gpg")
entry, err := readEntry(fp, key) entry, err := readEntry(fp, key)
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err) fmt.Fprintf(os.Stderr, "Error: %v\n", err)
@@ -374,11 +286,10 @@ func getUsernameCmd() *cobra.Command {
}, },
} }
cmd.Flags().StringVar(&keyFlag, "key", "", "Key name") cmd.Flags().StringVar(&keyFlag, "key", "", "Key name")
cmd.Flags().BoolVar(&public, "public", false, "Use shared public scope only")
return cmd return cmd
} }
// ── get (legacy) ────────────────────────────────────────────────────────
func getLegacyCmd() *cobra.Command { func getLegacyCmd() *cobra.Command {
var showUsername bool var showUsername bool
cmd := &cobra.Command{ cmd := &cobra.Command{
@@ -411,10 +322,9 @@ func getLegacyCmd() *cobra.Command {
return cmd return cmd
} }
// ── set ─────────────────────────────────────────────────────────────────
func setCmd() *cobra.Command { func setCmd() *cobra.Command {
var keyFlag, username, secret string var keyFlag, username, secret string
var public bool
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "set", Use: "set",
Short: "Set a key entry", Short: "Set a key entry",
@@ -429,11 +339,15 @@ func setCmd() *cobra.Command {
fmt.Fprintf(os.Stderr, "Error: %v\n", err) fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1) os.Exit(1)
} }
dir := agentStoreDir(currentAgentID()) dir := resolveStoreDir(public)
if err := os.MkdirAll(dir, 0700); err != nil { if err := os.MkdirAll(dir, 0700); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err) fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1) 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} entry := &Entry{Username: username, Secret: secret}
fp := filepath.Join(dir, keyFlag+".gpg") fp := filepath.Join(dir, keyFlag+".gpg")
if err := writeEntry(fp, entry, aesKey); err != nil { if err := writeEntry(fp, entry, aesKey); err != nil {
@@ -445,13 +359,13 @@ func setCmd() *cobra.Command {
cmd.Flags().StringVar(&keyFlag, "key", "", "Key name") cmd.Flags().StringVar(&keyFlag, "key", "", "Key name")
cmd.Flags().StringVar(&username, "username", "", "Username") cmd.Flags().StringVar(&username, "username", "", "Username")
cmd.Flags().StringVar(&secret, "secret", "", "Secret value") cmd.Flags().StringVar(&secret, "secret", "", "Secret value")
cmd.Flags().BoolVar(&public, "public", false, "Use shared public scope only")
return cmd return cmd
} }
// ── generate ────────────────────────────────────────────────────────────
func generateCmd() *cobra.Command { func generateCmd() *cobra.Command {
var keyFlag, username string var keyFlag, username string
var public bool
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "generate", Use: "generate",
Short: "Generate a random secret for a key", Short: "Generate a random secret for a key",
@@ -471,11 +385,15 @@ func generateCmd() *cobra.Command {
fmt.Fprintf(os.Stderr, "Error: %v\n", err) fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1) os.Exit(1)
} }
dir := agentStoreDir(currentAgentID()) dir := resolveStoreDir(public)
if err := os.MkdirAll(dir, 0700); err != nil { if err := os.MkdirAll(dir, 0700); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err) fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1) 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} entry := &Entry{Username: username, Secret: pw}
fp := filepath.Join(dir, keyFlag+".gpg") fp := filepath.Join(dir, keyFlag+".gpg")
if err := writeEntry(fp, entry, aesKey); err != nil { if err := writeEntry(fp, entry, aesKey); err != nil {
@@ -487,13 +405,13 @@ func generateCmd() *cobra.Command {
} }
cmd.Flags().StringVar(&keyFlag, "key", "", "Key name") cmd.Flags().StringVar(&keyFlag, "key", "", "Key name")
cmd.Flags().StringVar(&username, "username", "", "Username") cmd.Flags().StringVar(&username, "username", "", "Username")
cmd.Flags().BoolVar(&public, "public", false, "Use shared public scope only")
return cmd return cmd
} }
// ── unset ───────────────────────────────────────────────────────────────
func unsetCmd() *cobra.Command { func unsetCmd() *cobra.Command {
var keyFlag string var keyFlag string
var public bool
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "unset", Use: "unset",
Short: "Remove a key entry", Short: "Remove a key entry",
@@ -503,7 +421,7 @@ func unsetCmd() *cobra.Command {
fmt.Fprintln(os.Stderr, "Error: --key is required") fmt.Fprintln(os.Stderr, "Error: --key is required")
os.Exit(1) os.Exit(1)
} }
fp := filepath.Join(agentStoreDir(currentAgentID()), keyFlag+".gpg") fp := filepath.Join(resolveStoreDir(public), keyFlag+".gpg")
if err := os.Remove(fp); err != nil { if err := os.Remove(fp); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err) fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1) os.Exit(1)
@@ -511,67 +429,16 @@ func unsetCmd() *cobra.Command {
}, },
} }
cmd.Flags().StringVar(&keyFlag, "key", "", "Key name") cmd.Flags().StringVar(&keyFlag, "key", "", "Key name")
cmd.Flags().BoolVar(&public, "public", false, "Use shared public scope only")
return cmd return cmd
} }
// ── admin ───────────────────────────────────────────────────────────────
func adminCmd() *cobra.Command { func adminCmd() *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{Use: "admin", Short: "Admin commands (human only)"}
Use: "admin", cmd.AddCommand(adminHandoffCmd(), adminInitFromCmd())
Short: "Admin commands (human only)",
}
cmd.AddCommand(adminInitCmd(), adminHandoffCmd(), adminInitFromCmd())
return cmd return cmd
} }
func adminInitCmd() *cobra.Command {
return &cobra.Command{
Use: "init",
Short: "Set admin password",
Run: func(cmd *cobra.Command, args []string) {
rejectIfAgent("admin init")
var password string
if envPw := os.Getenv("PC_ADMIN_PASS"); envPw != "" {
password = envPw
} else {
fmt.Fprint(os.Stderr, "Enter admin password: ")
pw1, err := term.ReadPassword(int(syscall.Stdin))
if err != nil {
fmt.Fprintf(os.Stderr, "\nError: %v\n", err)
os.Exit(1)
}
fmt.Fprintln(os.Stderr)
p1 := strings.TrimSpace(string(pw1))
if len(p1) < 6 {
fmt.Fprintln(os.Stderr, "Error: password must be at least 6 characters")
os.Exit(1)
}
fmt.Fprint(os.Stderr, "Confirm admin password: ")
pw2, err := term.ReadPassword(int(syscall.Stdin))
if err != nil {
fmt.Fprintf(os.Stderr, "\nError: %v\n", err)
os.Exit(1)
}
fmt.Fprintln(os.Stderr)
if p1 != strings.TrimSpace(string(pw2)) {
fmt.Fprintln(os.Stderr, "Error: passwords do not match")
os.Exit(1)
}
password = p1
}
cfg := &AdminConfig{PasswordHash: hashPassword(password)}
if err := saveAdminConfig(cfg); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
fmt.Println("Admin password set successfully")
},
}
}
func adminHandoffCmd() *cobra.Command { func adminHandoffCmd() *cobra.Command {
return &cobra.Command{ return &cobra.Command{
Use: "handoff [secret_file_path]", Use: "handoff [secret_file_path]",
@@ -579,10 +446,6 @@ func adminHandoffCmd() *cobra.Command {
Args: cobra.MaximumNArgs(1), Args: cobra.MaximumNArgs(1),
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
rejectIfAgent("admin handoff") rejectIfAgent("admin handoff")
if err := verifyAdminPassword(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
if buildSecret == "" { if buildSecret == "" {
fmt.Fprintln(os.Stderr, "Error: no build secret compiled in") fmt.Fprintln(os.Stderr, "Error: no build secret compiled in")
os.Exit(1) os.Exit(1)
@@ -604,14 +467,11 @@ func adminHandoffCmd() *cobra.Command {
func adminInitFromCmd() *cobra.Command { func adminInitFromCmd() *cobra.Command {
return &cobra.Command{ return &cobra.Command{
Use: "init-from [secret_file_path]", Use: "init-from [secret_file_path]",
Aliases: []string{"init_from"},
Short: "Re-encrypt all data from old build secret to current", Short: "Re-encrypt all data from old build secret to current",
Args: cobra.MaximumNArgs(1), Args: cobra.MaximumNArgs(1),
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
rejectIfAgent("admin init-from") rejectIfAgent("admin init-from")
if err := verifyAdminPassword(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
inPath := "pc-pass-store.secret" inPath := "pc-pass-store.secret"
if len(args) > 0 { if len(args) > 0 {
@@ -632,8 +492,9 @@ func adminInitFromCmd() *cobra.Command {
os.Exit(1) os.Exit(1)
} }
_ = ensurePublicStoreDir()
base := passStoreBase() base := passStoreBase()
agentDirs, err := os.ReadDir(base) dirs, err := os.ReadDir(base)
if err != nil { if err != nil {
if os.IsNotExist(err) { if os.IsNotExist(err) {
fmt.Fprintln(os.Stderr, "No pass store found — nothing to migrate") fmt.Fprintln(os.Stderr, "No pass store found — nothing to migrate")
@@ -644,12 +505,12 @@ func adminInitFromCmd() *cobra.Command {
} }
count := 0 count := 0
for _, ad := range agentDirs { for _, d := range dirs {
if !ad.IsDir() { if !d.IsDir() {
continue continue
} }
agentDir := filepath.Join(base, ad.Name()) scopeDir := filepath.Join(base, d.Name())
files, err := os.ReadDir(agentDir) files, err := os.ReadDir(scopeDir)
if err != nil { if err != nil {
continue continue
} }
@@ -657,7 +518,7 @@ func adminInitFromCmd() *cobra.Command {
if !strings.HasSuffix(f.Name(), ".gpg") { if !strings.HasSuffix(f.Name(), ".gpg") {
continue continue
} }
fp := filepath.Join(agentDir, f.Name()) fp := filepath.Join(scopeDir, f.Name())
entry, err := readEntry(fp, oldKey) entry, err := readEntry(fp, oldKey)
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to decrypt %s: %v\n", fp, err) fmt.Fprintf(os.Stderr, "Warning: failed to decrypt %s: %v\n", fp, err)
@@ -671,11 +532,9 @@ func adminInitFromCmd() *cobra.Command {
} }
} }
// Delete the old secret file
if err := os.Remove(inPath); err != nil { if err := os.Remove(inPath); err != nil {
fmt.Fprintf(os.Stderr, "Warning: could not remove secret file: %v\n", err) 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) fmt.Fprintf(os.Stderr, "Re-encrypted %d entries. Secret file removed.\n", count)
}, },
} }

105
skills/ego-mgr/SKILL.md Normal file
View 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

View 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`