Secure key management for AI agents. An agent skill from LeoYeAI/openclaw-master-skills.

MITAuto-check: notesSecurity

Install Bagman

skills CLI
$ npx skills add LeoYeAI/openclaw-master-skills --skill bagman -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install LeoYeAI/openclaw-master-skills bagman --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/LeoYeAI/openclaw-master-skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/master-skills .claude/skills/bagman && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
bagman
GitHub stars
2.2k
Token cost
~2.9k tokens
SKILL.md length
502 words
Files
3
Skills in repo
1,235
Repo updated
First seen
Licence
MIT

At a glance

Secure key management for AI agents. An agent skill from LeoYeAI/openclaw-master-skills.

  • Works in 7 steps: Create 1Password Vault for Agent Secrets → Agent Retrieves Credentials at Runtime → Never Log or Store the Key → …
  • Handling private keys
  • SKILL.md covers Core Principles, References, Quick Reference and Architecture: Agent Wallet Stack, plus 8 more sections
  • Needs PRIVATE_KEY

What it does

Bagman is an agent skill from LeoYeAI/openclaw-master-skills. Secure key management for AI agents. Use when handling private keys, API secrets, wallet credentials, or when building systems that need agent-controlled funds. Covers secure storage, session keys, leak prevention, and prompt injection defense.

Its SKILL.md is about 2.9k tokens, which your agent loads only when the skill is triggered. The skill folder holds 3 other files (for example `.clawhub/origin.json` and `_meta.json`).

It sits in Security, covering Prompt injection and agent security and Cryptography. The repository describes itself as: 🧠 Curated collection of 1209+ best OpenClaw skills — weekly updated by MyClaw.ai. The licence is MIT.

When your agent uses it

  • Handling private keys
  • Wallet credentials
  • Building systems that need agent-controlled funds

Example prompts

  • “/bagman”

Requirements

  • Python 3
  • A credential in PRIVATE_KEY

Workflow steps

7 steps, taken from the step headings in SKILL.md.

  1. Create 1Password Vault for Agent Secrets
  2. Agent Retrieves Credentials at Runtime
  3. Never Log or Store the Key
  4. Keys in Memory Files
  5. Keys in Environment Templates
  6. Keys in Error Messages
  7. Test Keys in Production Code

What it can do on your machine

Read from SKILL.md and the folder at commit e5199b5. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are python, bash, markdown and gitignore).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names these keys or tokens, usually read from environment variables:

    • PRIVATE_KEY

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Bagman loads about 2.9k tokens when it runs. Until then it costs about 63 tokens; SKILL.md has 502 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~63
When it runs · the whole SKILL.md, loaded when a task matches
~2.9k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check: notes

The automated check noted patterns worth knowing about, such as sudo or a known installer.

  • NoteMentions a .env fileSKILL.md:48
    op run --env-file=.env.tpl -- node agent.js
  • NoteMentions a .env fileSKILL.md:58
    echo "PRIVATE_KEY=0x123..." > .env
  • NoteMentions a .env fileSKILL.md:229
    .env
  • NoteMentions a .env fileSKILL.md:230
    .env.*

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from LeoYeAI/openclaw-master-skills at commit e5199b5, republished under its MIT licence (© LeoYeAI). 502 words, ~2,945 tokens.

Download SKILL.mdSave it as .claude/skills/bagman/SKILL.md (or your agent's skills folder). This skill also uses 2 other files; get the full folder from GitHub.
name
bagman
description
Secure key management for AI agents. Use when handling private keys, API secrets, wallet credentials, or when building systems that need agent-controlled funds. Covers secure storage, session keys, leak prevention, and prompt injection defense.
version
1.0.0
homepage
https://numbergroup.xyz

Bagman

Secure key management patterns for AI agents handling private keys and secrets. Designed to prevent:

  • Key loss: Agents forgetting keys between sessions
  • Accidental exposure: Keys leaked to GitHub, logs, or outputs
  • Prompt injection: Malicious prompts extracting secrets

Core Principles

  1. Never store raw private keys in config, env vars, or memory files
  2. Use session keys / delegated access instead of full control
  3. All secret access goes through 1Password CLI (op)
  4. Validate all outputs before sending to prevent key leakage

References

  • references/secure-storage.md - 1Password patterns for agent secrets
  • references/session-keys.md - ERC-4337 delegated access patterns
  • references/leak-prevention.md - Pre-commit hooks and output sanitization
  • references/prompt-injection-defense.md - Input validation and output filtering

Quick Reference

DO ✅
bash
# Retrieve key at runtime via 1Password
PRIVATE_KEY=$(op read "op://Agents/my-agent-wallet/private-key")

# Use environment injection (key never touches disk)
op run --env-file=.env.tpl -- node agent.js

# Use session keys with bounded permissions
# (delegate specific capabilities, not full wallet access)
DON'T ❌
bash
# NEVER store keys in files
echo "PRIVATE_KEY=0x123..." > .env

# NEVER log or print keys
console.log("Key:", privateKey)

# NEVER store keys in memory/journal files
# Even in "private" agent memory - these can be exfiltrated

# NEVER trust unvalidated input near key operations

Architecture: Agent Wallet Stack

┌─────────────────────────────────────────────────────┐
│                   AI Agent                          │
├─────────────────────────────────────────────────────┤
│  Session Key (time/value bounded)                   │
│  - Expires after N hours                            │
│  - Spending cap per operation                       │
│  - Whitelist of allowed contracts                   │
├─────────────────────────────────────────────────────┤
│  1Password / Secret Manager                         │
│  - Agent retrieves session key at runtime           │
│  - Never stores full private key                    │
│  - Audit log of all accesses                        │
├─────────────────────────────────────────────────────┤
│  ERC-4337 Smart Account                             │
│  - Programmable permissions                         │
│  - Recovery without private key exposure            │
│  - Multi-sig for high-value operations              │
├─────────────────────────────────────────────────────┤
│  Operator (Human)                                   │
│  - Holds master key in hardware wallet              │
│  - Issues/revokes session keys                      │
│  - Monitors agent activity                          │
└─────────────────────────────────────────────────────┘

Workflow: Setting Up Agent Wallet Access

1. Create 1Password Vault for Agent Secrets
bash
# Create dedicated vault (via 1Password app or CLI)
op vault create "Agent-Wallets" --description "AI agent wallet credentials"

# Store agent session key (not master key!)
op item create \
  --vault "Agent-Wallets" \
  --category "API Credential" \
  --title "trading-bot-session" \
  --field "session-key[password]=0xsession..." \
  --field "expires=2026-02-15T00:00:00Z" \
  --field "spending-cap=1000 USDC" \
  --field "allowed-contracts=0xDEX1,0xDEX2"
2. Agent Retrieves Credentials at Runtime
python
import subprocess
import json

def get_session_key(item_name: str) -> dict:
    """Retrieve session key from 1Password at runtime."""
    result = subprocess.run(
        ["op", "item", "get", item_name, "--vault", "Agent-Wallets", "--format", "json"],
        capture_output=True, text=True, check=True
    )
    item = json.loads(result.stdout)
    
    # Extract fields
    fields = {f["label"]: f.get("value") for f in item.get("fields", [])}
    
    # Validate session hasn't expired
    from datetime import datetime
    expires = datetime.fromisoformat(fields.get("expires", "2000-01-01"))
    if datetime.now() > expires:
        raise ValueError("Session key expired - request new key from operator")
    
    return {
        "session_key": fields.get("session-key"),
        "expires": fields.get("expires"),
        "spending_cap": fields.get("spending-cap"),
        "allowed_contracts": fields.get("allowed-contracts", "").split(",")
    }
3. Never Log or Store the Key
python
# ❌ BAD - Key in logs
logger.info(f"Using key: {session_key}")

# ✅ GOOD - Redacted identifier
logger.info(f"Using session key: {session_key[:8]}...{session_key[-4:]}")

# ❌ BAD - Key in memory file
with open("memory/today.md", "a") as f:
    f.write(f"Session key: {session_key}")

# ✅ GOOD - Reference only
with open("memory/today.md", "a") as f:
    f.write(f"Session key: [stored in 1Password: trading-bot-session]")

Leak Prevention

Output Sanitization

Before any agent output (chat, logs, file writes), scan for key patterns:

python
import re

KEY_PATTERNS = [
    r'0x[a-fA-F0-9]{64}',                    # ETH private keys
    r'sk-[a-zA-Z0-9]{48,}',                  # OpenAI keys
    r'sk-ant-[a-zA-Z0-9\-_]{80,}',           # Anthropic keys
    r'gsk_[a-zA-Z0-9]{48,}',                 # Groq keys
    r'[A-Za-z0-9+/]{40,}={0,2}',             # Base64 encoded (suspiciously long)
]

def sanitize_output(text: str) -> str:
    """Remove potential secrets from output."""
    for pattern in KEY_PATTERNS:
        text = re.sub(pattern, '[REDACTED]', text)
    return text

# Apply to ALL agent outputs
def send_message(content: str):
    content = sanitize_output(content)
    # ... send to chat/log/file
Pre-commit Hook

Install this hook to prevent accidental commits of secrets:

bash
#!/bin/bash
# .git/hooks/pre-commit

PATTERNS=(
    '0x[a-fA-F0-9]{64}'
    'sk-[a-zA-Z0-9]{48,}'
    'sk-ant-api'
    'PRIVATE_KEY='
    'gsk_[a-zA-Z0-9]{48,}'
)

for pattern in "${PATTERNS[@]}"; do
    if git diff --cached | grep -qE "$pattern"; then
        echo "❌ Potential secret detected matching: $pattern"
        echo "   Remove secrets before committing!"
        exit 1
    fi
done
.gitignore Essentials
gitignore
# Secrets
.env
.env.*
*.pem
*.key
secrets/
credentials/

# Agent state that might contain secrets
memory/*.json
wallet-state.json
session-keys/

Prompt Injection Defense

Input Validation

Before processing any user input that touches wallet operations:

python
DANGEROUS_PATTERNS = [
    r'ignore.*(previous|above|prior).*instructions',
    r'reveal.*(key|secret|password|credential)',
    r'output.*(key|secret|private)',
    r'print.*(key|secret|wallet)',
    r'show.*(key|secret|password)',
    r'what.*(key|secret|password)',
    r'tell.*me.*(key|secret)',
    r'disregard.*rules',
    r'system.*prompt',
    r'jailbreak',
    r'dan.*mode',
]

def validate_input(text: str) -> bool:
    """Check for prompt injection attempts."""
    text_lower = text.lower()
    for pattern in DANGEROUS_PATTERNS:
        if re.search(pattern, text_lower):
            return False
    return True

def process_wallet_request(user_input: str):
    if not validate_input(user_input):
        return "I can't help with that request."
    # ... proceed with wallet operation
Separation of Concerns
  • Wallet operations should be in isolated functions with no access to conversation context
  • Never pass full conversation history to wallet-sensitive code
  • Use allowlists for operations, not blocklists
python
ALLOWED_WALLET_OPERATIONS = {
    "check_balance": lambda: get_balance(),
    "send_usdc": lambda to, amount: send_usdc(to, amount) if amount < DAILY_LIMIT else deny(),
    "swap": lambda: swap_tokens() if within_limits() else deny(),
}

def execute_wallet_operation(operation: str, **kwargs):
    """Execute only explicitly allowed operations."""
    if operation not in ALLOWED_WALLET_OPERATIONS:
        raise ValueError(f"Operation '{operation}' not allowed")
    return ALLOWED_WALLET_OPERATIONS[operation](**kwargs)

Session Key Implementation (ERC-4337)

For agents needing on-chain access, use session keys instead of raw private keys.

See references/session-keys.md for full implementation details including:

  • ZeroDev/Biconomy SDK examples
  • Permission patterns for trading/DeFi/payment agents
  • Session key lifecycle management
  • Revocation procedures

Incident Response

If a Key is Leaked
  1. Immediate: Revoke the session key / rotate credentials
  2. Assess: Check transaction history for unauthorized activity
  3. Notify: Alert operator via secure channel
  4. Rotate: Issue new session key with tighter permissions
  5. Audit: Review how leak occurred, update defenses
bash
# Emergency: Revoke 1Password item
op item delete "compromised-session-key" --vault "Agent-Wallets"

# Rotate to new session key
op item create --vault "Agent-Wallets" --category "API Credential" \
  --title "trading-bot-session-v2" ...

Show full SKILL.md (204 more words)Show less

Checklist: Agent Wallet Setup

  • Create dedicated 1Password vault for agent credentials
  • Store session keys (NOT master keys) in vault
  • Set appropriate expiry and spending limits
  • Install pre-commit hook for secret detection
  • Add output sanitization to all agent responses
  • Implement input validation for prompt injection
  • Configure monitoring and alerts
  • Document incident response procedure
  • Test key rotation procedure

Common Mistakes Found in Production

1. Keys in Memory Files

Problem: Agents store keys in memory/*.md for "persistence"

markdown
# memory/2026-02-07.md
## Test Wallet
- Private key: 0x9f01dad551039daad3a8c4e43a32035bdd4da54e7b4292268be16e913b0b3e56

Fix: Store reference only: Private key: [1Password: test-wallet-session]

2. Keys in Environment Templates

Problem: .env.example contains real keys

# .env.example
PRIVATE_KEY=sk-ant-api03-real-key-here...  # "for testing"

Fix: Use obviously fake placeholders: PRIVATE_KEY=your-key-here

3. Keys in Error Messages

Problem: Error handling exposes keys

python
try:
    sign_transaction(private_key, tx)
except Exception as e:
    logger.error(f"Failed with key {private_key}: {e}")  # ❌

Fix: Never include credentials in error context

4. Test Keys in Production Code

Problem: Hardcoded test keys make it to main branch

Fix: Use separate test vault, CI checks for key patterns


Integration with OpenClaw

When running as an OpenClaw agent:

  1. Use 1Password skill for all secret retrieval
  2. Never write keys to workspace files - they persist across sessions
  3. Sanitize outputs before sending to any channel (Telegram, Discord, etc.)
  4. Session key approach for wallet operations - request bounded access from operator
  5. Document key references in TOOLS.md, not the actual keys

Example TOOLS.md entry:

markdown
### Agent Wallet
- Address: 0xABC123...
- Session key: [1Password: my-agent-session]
- Permissions: USDC transfers < 100, approved DEX only
- Expires: 2026-02-15
- To rotate: Ask operator via Telegram

© LeoYeAI, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 2 other files in skills/master-skills of LeoYeAI/openclaw-master-skills.

  • SKILL.md
  • .clawhub/origin.json
  • _meta.json

Open the folder on GitHubat commit e5199b5

Compare with similar skills

Bagman next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Bagman compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Bagman this skillLeoYeAI/openclaw-master-skills2.2k—~2.9kAutomated safety check: NotesMIT
Bagmanprofbernardoj/everclaw-community-branches112—~4.4kAutomated safety check: WarnMIT
Agent Security Managerruvnet/ruflo74k2 repos~4.9kAutomated safety check: PassMIT
Clade Security Basicsjeremylongshore/tons-of-skills-marketplace2.8k—~1.1kAutomated safety check: NotesMIT
Anth Security Basicsjeremylongshore/tons-of-skills-marketplace2.8k—~1.9kAutomated safety check: NotesMIT
Skill Scannergetsentry/skills1k4 repos~2.5kAutomated safety check: WarnApache-2.0

Similar skills

  • Bagman

    profbernardoj/everclaw-community-branches

    Secure key management for AI agents. An agent skill from profbernardoj/everclaw-community-branches.

    112 GitHub stars~4.4k tokensUpdated 1 mo ago
    SecurityAuto-check: warnings
  • Agent skill for security-manager - invoke with $agent-security-manager

    74k GitHub starsUsed in 2 repos~4.9k tokens
    SecurityAuto-check passed
  • Clade Security Basics

    jeremylongshore/tons-of-skills-marketplace

    Secure your Anthropic integration — API key management, input validation, Use when working with security-basics patterns.

    2.8k GitHub stars~1.1k tokensUpdated today
    SecurityAuto-check: notes
  • Anth Security Basics

    jeremylongshore/tons-of-skills-marketplace

    Apply Anthropic Claude API security best practices for key management, input validation, and prompt injection defense.

    2.8k GitHub stars~1.9k tokensUpdated today
    AI & LLM EngineeringAuto-check: notes
  • Skill Scanner

    getsentry/skills

    Official

    Scan agent skills for security issues. An agent skill from getsentry/skills.

    1k GitHub starsUsed in 4 repos~2.5k tokens
    SecurityAuto-check: warnings
  • Forensify

    alexgreensh/repo-forensics

    Cross-agent self-inspection of your AI-agent stack. An agent skill from alexgreensh/repo-forensics.

    188 GitHub stars~2.5k tokensUpdated 12 days ago
    SecurityAuto-check: notes

More from LeoYeAI/openclaw-master-skills

All 1,235 skills in this repo
  • DevOps Pipeline Management

    LeoYeAI/openclaw-master-skills

    Manages pipelines on a DevOps quality and efficiency platform through its OpenAPI: list workspaces and templates, create, update, run and cancel pipelines, and read run records.

    2.2k GitHub stars~4.2k tokensUpdated 2 mo ago
    Auto-check: notes
  • Feishu Document Collaboration

    LeoYeAI/openclaw-master-skills

    Patches OpenClaw's Feishu extension so an edited document triggers an isolated agent session that reads the doc and replies inline, turning it into a live chat space.

    2.2k GitHub stars~2k tokensUpdated 2 mo ago
    Auto-check passed
  • Files Memory System

    LeoYeAI/openclaw-master-skills

    Multi-context memory management system for OpenClaw agents with group-isolated storage, global shared memory, workspace organization, and group-specific skills isolation.

    2.2k GitHub stars~3.8k tokensUpdated 2 mo ago
    Auto-check passed
  • GEO-Claw AI Visibility Agent

    LeoYeAI/openclaw-master-skills

    Runs a brand's AI-search visibility work end to end: diagnosing how AI platforms represent it, repositioning it, producing AI-optimized content and monitoring ongoing mentions.

    2.2k GitHub stars~4.7k tokensUpdated 2 mo ago
    Auto-check passed
  • Google Workspace CLI

    LeoYeAI/openclaw-master-skills

    Installs and authenticates the gws CLI, then automates Gmail, Drive, Sheets, Calendar, Docs, Chat and Tasks with ready-made recipes, persona bundles and security audits.

    2.2k GitHub stars~2.6k tokensUpdated 2 mo ago
    Auto-check: notes
  • HealthFit Health Advisors

    LeoYeAI/openclaw-master-skills

    Runs four advisor roles, a fitness coach, nutritionist, data analyst and TCM practitioner, to build a health profile and track workouts, diet and wellness over time.

    2.2k GitHub stars~4.4k tokensUpdated 2 mo ago
    Auto-check passed

Categories

Questions about Bagman

What does Bagman do?

Secure key management for AI agents. An agent skill from LeoYeAI/openclaw-master-skills. Bagman is an agent skill from LeoYeAI/openclaw-master-skills. Secure key management for AI agents.

When should I use Bagman?

Bagman fits situations like: handling private keys; wallet credentials; building systems that need agent-controlled funds.

How do I install Bagman in Claude Code?

Run `npx skills add LeoYeAI/openclaw-master-skills --skill bagman -a claude-code`. Or copy the skill folder (skills/master-skills in LeoYeAI/openclaw-master-skills) into .claude/skills/bagman in your project. Claude Code loads it when a task matches its description.

How do I install Bagman in Codex?

Run `npx skills add LeoYeAI/openclaw-master-skills --skill bagman -a codex`. Or copy the skill folder (skills/master-skills in LeoYeAI/openclaw-master-skills) into .agents/skills/bagman in your project. Codex loads it when a task matches its description.

Can I use Bagman in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add LeoYeAI/openclaw-master-skills --skill bagman -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/bagman, .gemini/skills/bagman, .github/skills/bagman and .opencode/skills/bagman in your project.

What does Bagman need to run?

Going by SKILL.md and its folder, Bagman needs credentials named PRIVATE_KEY. Our summary lists: Python 3; A credential in PRIVATE_KEY.

Does Bagman access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Bagman safe to install?

Our automated static check of SKILL.md found notes only (mentions a .env file), nothing it rates as a warning. It is not a guarantee. Review the folder before installing.

What licence does Bagman use?

Bagman is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Bagman use?

About 2.9k tokens (SKILL.md is roughly 12k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Bagman?

Skills that share tags, products or a category with Bagman: Bagman (profbernardoj/everclaw-community-branches, 112 stars), Agent Security Manager (ruvnet/ruflo, 74k stars), Clade Security Basics (jeremylongshore/tons-of-skills-marketplace, 2.8k stars) and Anth Security Basics (jeremylongshore/tons-of-skills-marketplace, 2.8k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Bagman?

LeoYeAI (a GitHub user) maintains it in LeoYeAI/openclaw-master-skills, which has 2,160 GitHub stars. The repository holds 1,235 skills in this directory. The repository was last updated on July 20, 2026.

Source: LeoYeAI/openclaw-master-skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.