Skill: drafthead/skill-to-agent-converter (version 1.0.0)

--- name: skill-to-agent description: Convert OpenClaw skills into properly configured agents with correct workspace setup, binding, and orchestration. Solves common agent creation failures (thread binding errors, workspace isolation, improper session spawning). Use when creating agents from skills or when encountering agent binding errors. --- # Skill-to-Agent Transform any OpenClaw skill into a fully functional agent with proper workspace configuration and session management. Solves common failures like `thread=true is unavailable` and `mode="session" requires thread=true`. ## Quick Start 1. **Analyze skill** - Read SKILL.md to understand requirements 2. **Prepare workspace** - Create agent directory in `~/.openclaw/agents/` 3. **Configure agent** - Set up identity, tools, and memory strategy 4. **Spawn with correct binding** - Choose appropriate mode based on channel ## Workflow ### Phase 1: Skill Analysis - Extract metadata from SKILL.md (name, description, triggers) - Identify required tools and dependencies - Determine agent type: isolated, thread-bound, or run-mode ### Phase 2: Workspace Setup - Create agent directory with proper structure - Copy skill files (references/, scripts/) - Configure AGENTS.md, TOOLS.md, USER.md ### Phase 3: Agent Configuration - Create SOUL.md and IDENTITY.md with skill personality - Map skill tools to agent capabilities - Set up memory strategy (MEMORY.md, memory/ directory) ### Phase 4: Agent Registration - Add agent to OpenClaw's `agents.list` configuration - Use `gateway` tool with `config.patch` action - Include agent ID, name, workspace, and agentDir - Gateway will restart to apply configuration ### Phase 5: Session Spawning - Choose spawn strategy based on channel capabilities - Execute with correct binding (thread-bound, isolated, run-mode) - **CRITICAL:** Always set `cwd` to agent workspace directory - Verify agent activation and tool access ## Reference Materials For detailed guidance, refer to: - **Usage Guide** - [usage-guide.md](references/usage-guide.md) - Complete workflow with examples - **Troubleshooting** - [troubleshooting.md](references/troubleshooting.md) - Common errors and solutions - **War Room Example** - [war-room-example.md](references/war-room-example.md) - Detailed conversion example ## Scripts - `scripts/skill_to_agent.js` - Main conversion script ## Binding Strategies | Scenario | Mode | Thread | Best For | |----------|------|--------|----------| | Discord/Telegram | session | true | Group discussions | | WebChat/Control UI | run | false | One-shot tasks | | Isolated Processing | session | false | Background work | | Cron/Scheduled | run | false | Automated tasks | **Decision Tree:** - Channel supports threads? → Yes → `thread=true`, `mode=session` - Isolated processing needed? → Yes → `thread=false`, `mode=session` - Otherwise → `thread=false`, `mode=run` ## Common Errors & Solutions **Error 1: `thread=true is unavailable`** - Solution: Use `mode="run"` without thread binding - Check channel capabilities first **Error 2: `mode="session" requires thread=true`** - Solution: Use isolated session mode - `mode="session"`, `thread=false`, `runtime="subagent"` **Error 3: Agent lacks tool access** - Solution: Verify tools in TOOLS.md - Update workspace configuration **Error 4: Workspace files not accessible** - Solution: Set `cwd` parameter when spawning agent - Agent workspace must be at path specified in `cwd` - Ensure agent has read/write permissions to workspace **Error 5: Agent can't find its identity files** - Solution: Always set `cwd` to agent workspace directory - Agent reads IDENTITY.md, SOUL.md, etc. from current directory - Test file access with simple `read` commands **Error 6: Agent not recognized by OpenClaw system** - Solution: Register agent in `agents.list` configuration - Use `gateway` tool with `config.patch` action - Gateway restart required for configuration changes - Verify agent appears in configured agents list ## Critical: Workspace Directory (cwd) When spawning an agent, **ALWAYS set the `cwd` parameter** to the agent's workspace directory: ```javascript sessions_spawn({ task: "Agent instructions...", label: "agent-name", runtime: "subagent", mode: "session", // or "run" cwd: "/Users/nimbletenthousand/.openclaw/agents/agent-name", timeoutSeconds: 300 }); ``` Without `cwd`, the agent cannot find its identity files (IDENTITY.md, SOUL.md, etc.) and will fail to function properly. ## Critical: Agent Registration After creating an agent workspace, **register it in OpenClaw's configuration**: ```javascript gateway({ action: "config.patch", raw: JSON.stringify({ agents: { list: [ { id: "agent-name", name: "Agent Display Name", workspace: "/Users/nimbletenthousand/.openclaw/workspace", agentDir: "/Users/nimbletenthousand/.openclaw/agents/agent-name" } ] } }), note: "Added [agent-name] to agents configuration" }); ``` The gateway will restart automatically to apply the configuration. Without registration, the agent won't be recognized as a configured agent in the system. ## Quick Commands ```bash # Check skill structure node scripts/skill_to_agent.js --analyze --skill /path/to/skill # Create agent workspace node scripts/skill_to_agent.js --create --skill /path/to/skill --agent agent-name # Spawn agent with correct binding node scripts/skill_to_agent.js --spawn --agent agent-name --mode session --cwd /path/to/agent-workspace ``` ## Best Practices 1. **Keep it lean** - Only copy essential skill files 2. **Test binding first** - Verify channel capabilities 3. **Monitor agent health** - Check `sessions_list` regularly 4. **Clean up properly** - Remove unused agent workspaces 5. **Document conversions** - Save configuration for future reference ## Next Steps After creating an agent: 1. Verify it appears in `sessions_list` 2. Test tool accessibility 3. Configure heartbeat if needed 4. Set up orchestration with parent agent For advanced usage and complete examples, see the reference files.

path: _meta.json
content: {
  "slug": "skill-to-agent",
  "version": "1.0.0",
  "description": "Convert OpenClaw skills into properly configured agents with correct workspace setup, binding, and orchestration.",
  "tags": ["agent-creation", "workspace-setup", "session-management", "binding"]
}

path: README.md
content: # Skill-to-Agent

Transform OpenClaw skills into fully functional, properly configured agents with correct workspace setup, binding strategies, and system registration.

## Overview

This skill provides a methodology for converting any OpenClaw skill into an autonomous agent. It solves common agent creation failures including thread binding errors, workspace isolation issues, file access problems, and improper session spawning.

## Quick Start

### The 5-Phase Methodology

1. **Skill Analysis** - Extract requirements from SKILL.md
2. **Workspace Setup** - Create agent directory with proper structure
3. **Agent Configuration** - Craft identity, memory, and tool access
4. **Agent Registration** - Add to OpenClaw's `agents.list` configuration
5. **Session Spawning** - Launch with correct binding for the channel

### Critical Success Factors

- **Always set `cwd`** - Agent workspace directory for file access
- **Always register agents** - Use `gateway config.patch` to add to configuration
- **Choose correct binding** - Based on channel capabilities (thread-bound, isolated, run-mode)

## Common Problems Solved

### Thread Binding Errors
- `thread=true is unavailable because no channel plugin registered subagent_spawning hooks`
- `mode="session" requires thread=true so the subagent can stay bound to a thread`

### Workspace Issues  
- Agents can't find identity files (IDENTITY.md, SOUL.md)
- File permission and access problems
- Memory configuration failures

### Registration Problems
- Agents not recognized by OpenClaw system
- Configuration not applied after creation

## File Structure

```
skill-to-agent/
├── README.md           # This overview
├── SKILL.md            # Main skill documentation
├── _meta.json          # Skill metadata
└── references/         # Detailed guides
    ├── usage-guide.md      # Complete workflow
    ├── troubleshooting.md  # Error solutions  
    └── war-room-example.md # Conversion example
```

## Usage Examples

### Create a Weather Agent from Weather Skill

```javascript
// Phase 1-3: Create workspace and configure
// ... create agent directory and files ...

// Phase 4: Register agent
gateway({
  action: "config.patch",
  raw: JSON.stringify({
    agents: {
      list: [
        {
          id: "weather-agent",
          name: "Weather Specialist",
          workspace: "/Users/username/.openclaw/workspace",
          agentDir: "/Users/username/.openclaw/agents/weather-agent"
        }
      ]
    }
  }),
  note: "Added weather-agent to agents configuration"
});

// Phase 5: Spawn with correct binding
sessions_spawn({
  task: "Check Amsterdam weather forecast",
  label: "weather-check",
  runtime: "subagent",
  mode: "run",
  cwd: "/Users/username/.openclaw/agents/weather-agent",
  timeoutSeconds: 180
});
```

## Binding Strategy Decision Tree

```
Is channel Discord/Telegram? → Yes → thread=true, mode=session
                              ↓ No
Is isolated processing needed? → Yes → thread=false, mode=session  
                                ↓ No
Default: thread=false, mode=run
```

## Skill vs Agent

| Aspect | Skill | Agent |
|--------|-------|-------|
| **Format** | SKILL.md + references/ | Full workspace with identity files |
| **Execution** | Guides AI behavior | Autonomous operation |
| **Memory** | None | Persistent memory/ directory |
| **Binding** | N/A | Thread-bound, isolated, or run-mode |
| **Registration** | Auto-discovered | Must be added to `agents.list` |

## Testing Methodology

This skill has been proven by creating the `skill-converter-agent`:

1. ✅ Created workspace with all identity files
2. ✅ Configured tools and memory strategy  
3. ✅ Registered in OpenClaw configuration via `gateway config.patch`
4. ✅ Successfully spawned and tested
5. ✅ Gateway restarted and recognized agent

## Getting Help

- Read `SKILL.md` for complete documentation
- Check `references/troubleshooting.md` for common errors
- Review `references/war-room-example.md` for detailed conversion example
- OpenClaw Discord: `#skills` channel

## License & Contributions

This skill is part of the OpenClaw ecosystem. Contributions and improvements welcome.

---

**Remember:** Skill-to-agent conversion transforms instructional templates into autonomous actors with their own identity, memory, and workspace isolation.

path: references/troubleshooting.md
content: # Troubleshooting Guide

## Common Errors and Solutions

### Error 1: Thread Binding Errors

**Error Message:**
```
thread=true is unavailable because no channel plugin registered subagent_spawning hooks
```

**Or:**
```
mode="session" requires thread=true so the subagent can stay bound to a thread
```

**Root Cause:**
- The channel (webchat, Discord, etc.) doesn't support thread-bound sessions
- Trying to use `thread=true` on a channel that doesn't have thread support

**Solutions:**

**Solution A: Use Isolated Session Mode**
```bash
# Instead of thread-bound, use isolated session
node skill_to_agent.js \
  --skill war-room \
  --agent war-room-isolated \
  --mode session \
  --thread false \
  --runtime subagent
```

**Solution B: Use Run Mode for One-Shot Tasks**
```bash
# For tasks that don't need persistent sessions
node skill_to_agent.js \
  --skill war-room \
  --agent war-room-run \
  --mode run \
  --thread false
```

**Solution C: Check Channel Capabilities First**
```javascript
// Before spawning, check what the channel supports
async function checkChannelCapabilities() {
  const sessions = await sessions_list();
  const currentSession = sessions.find(s => s.key === currentSessionKey);
  
  if (currentSession.channel === 'webchat') {
    // Webchat typically doesn't support threads
    return { supportsThreads: false, mode: 'run' };
  }
  
  if (currentSession.channel === 'discord') {
    // Discord often supports threads
    return { supportsThreads: true, mode: 'session' };
  }
  
  return { supportsThreads: false, mode: 'run' };
}
```

**Solution D: Automatic Fallback Strategy**
```bash
# The skill-to-agent tool automatically handles this:
node skill_to_agent.js --skill your-skill --agent your-agent
# It will detect channel capabilities and choose appropriate binding
```

---

### Error 2: Skill Not Found

**Error Message:**
```
SKILL.md not found in skill directory: /path/to/skill
```

**Or:**
```
Skill not found: skill-name
```

**Root Cause:**
- Incorrect skill path
- Skill directory doesn't contain SKILL.md
- Skill not installed in standard location

**Solutions:**

**Solution A: Specify Full Path**
```bash
# Use absolute path to SKILL.md
node skill_to_agent.js \
  --skill ~/.openclaw/skills/war-room-1.1.0/SKILL.md \
  --agent test-agent
```

**Solution B: Check Skill Installation**
```bash
# List installed skills
ls -la ~/.openclaw/skills/

# Check if skill has SKILL.md
ls -la ~/.openclaw/skills/war-room-1.1.0/
```

**Solution C: Install Missing Skill**
```bash
# If skill is missing, install it
clawhub install war-room

# Or clone from GitHub
git clone https://github.com/openclaw/skills/war-room.git ~/.openclaw/skills/war-room
```

**Solution D: Create Minimal SKILL.md**
```bash
# If skill exists but lacks SKILL.md, create one
cat > ~/.openclaw/skills/your-skill/SKILL.md << 'EOF'
---
name: "your-skill"
description: "Description of your skill"
triggers: ["trigger1", "trigger2"]
---

# Your Skill

Skill documentation here.
EOF
```

---

### Error 3: Tool Access Denied

**Error Message:**
```
Agent cannot access tool: web_search
```

**Or:**
```
Tool not available in agent context
```

**Root Cause:**
- Agent workspace TOOLS.md not configured
- OpenClaw tool policies restrict access
- Tool not included in agent configuration

**Solutions:**

**Solution A: Explicitly Specify Tools**
```bash
# List all required tools
node skill_to_agent.js \
  --skill war-room \
  --agent war-room-agent \
  --tools "sessions_spawn,sessions_send,memory_search,web_search"
```

**Solution B: Check Tool Policies**
```bash
# Check OpenClaw tool configuration
openclaw config get tools

# Verify agent has tool permissions
ls -la ~/.openclaw/agents/your-agent/TOOLS.md
```

**Solution C: Update Agent TOOLS.md**
```bash
# Manually add missing tools to TOOLS.md
echo "### web_search" >> ~/.openclaw/agents/your-agent/TOOLS.md
echo "- **Purpose:** Search the web for information" >> ~/.openclaw/agents/your-agent/TOOLS.md
```

**Solution D: Use Tool Verification**
```bash
# Test tool access before agent creation
node -e "
const { web_search } = require('openclaw');
web_search({ query: 'test' })
  .then(() => console.log('✓ web_search available'))
  .catch(err => console.log('✗ web_search unavailable:', err.message));
"
```

---

### Error 4: Workspace Permission Issues

**Error Message:**
```
EACCES: permission denied, mkdir '/path/to/agent'
```

**Or:**
```
Cannot write to workspace directory
```

**Root Cause:**
- Insufficient permissions on workspace directory
- Running as wrong user
- Directory owned by different user

**Solutions:**

**Solution A: Check Directory Permissions**
```bash
# Check current permissions
ls -la ~/.openclaw/
ls -la ~/.openclaw/agents/

# Fix permissions if needed
chmod 755 ~/.openclaw
chmod 755 ~/.openclaw/agents
```

**Solution B: Run as Correct User**
```bash
# Check current user
whoami

# Ensure you're running as the OpenClaw user
sudo -u openclaw-user node skill_to_agent.js --skill test --agent test
```

**Solution C: Use Alternative Directory**
```bash
# Set custom workspace directory
export OPENCLAW_AGENTS_DIR=/tmp/openclaw-agents
node skill_to_agent.js --skill test --agent test
```

**Solution D: Create Directory Structure**
```bash
# Manually create directory structure
mkdir -p ~/.openclaw/agents
chmod 755 ~/.openclaw/agents
```

---

### Error 5: Agent Spawn Failure

**Error Message:**
```
Failed to spawn agent: timeout
```

**Or:**
```
Agent spawn returned error status
```

**Root Cause:**
- Task too large or complex
- Timeout too short
- Resource constraints
- Configuration errors

**Solutions:**

**Solution A: Increase Timeout**
```bash
# Increase spawn timeout
node skill_to_agent.js \
  --skill complex-skill \
  --agent complex-agent \
  --timeout 600  # 10 minutes
```

**Solution B: Simplify Task**
```bash
# Create simpler spawn task
node skill_to_agent.js \
  --skill your-skill \
  --agent simple-agent \
  --task "Simple task description"  # Override generated task
```

**Solution C: Check Resource Limits**
```bash
# Check system resources
free -h  # Memory
df -h    # Disk space
top      # CPU usage

# Check OpenClaw limits
openclaw status
```

**Solution D: Test with Minimal Configuration**
```bash
# Test with minimal setup first
node skill_to_agent.js \
  --skill test-skill \
  --agent test-minimal \
  --mode run \
  --thread false \
  --tools "read" \
  --dry-run \
  --verbose
```

---

### Error 6: Memory Configuration Issues

**Error Message:**
```
Cannot write to memory file
```

**Or:**
```
Memory search returns no results
```

**Root Cause:**
- Memory directory not created
- File permission issues
- Incorrect memory configuration

**Solutions:**

**Solution A: Verify Memory Directory**
```bash
# Check memory directory exists
ls -la ~/.openclaw/agents/your-agent/memory/

# Create if missing
mkdir -p ~/.openclaw/agents/your-agent/memory
chmod 755 ~/.openclaw/agents/your-agent/memory
```

**Solution B: Check File Permissions**
```bash
# Check memory file permissions
ls -la ~/.openclaw/agents/your-agent/memory/*.md

# Fix permissions if needed
chmod 644 ~/.openclaw/agents/your-agent/memory/*.md
```

**Solution C: Configure Memory Properly**
```bash
# Recreate agent with proper memory configuration
node skill_to_agent.js \
  --skill your-skill \
  --agent your-agent \
  --memory persistent \
  --force  # Overwrite existing
```

**Solution D: Test Memory Operations**
```bash
# Test memory write
node -e "
const fs = require('fs');
const path = require('path');
const memPath = path.join(process.env.HOME, '.openclaw', 'agents', 'your-agent', 'memory', 'test.md');
fs.writeFileSync(memPath, '# Test\\nMemory test successful\\n');
console.log('✓ Memory write test passed');
"
```

### Error 7: Agent Not Registered in OpenClaw

**Error Message:**
- Agent not appearing in configured agents list
- "Agent not found" when trying to bind or reference
- Gateway doesn't recognize agent ID

**Root Cause:**
- Agent workspace created but not registered in configuration
- Configuration changes not applied (gateway not restarted)
- Agent ID conflicts with existing agent

**Solutions:**

**Solution A: Register Agent in Configuration**
```javascript
// Use gateway tool to add agent to configuration
gateway({
  action: "config.patch",
  raw: JSON.stringify({
    agents: {
      list: [
        {
          id: "agent-name",
          name: "Agent Display Name", 
          workspace: "/Users/username/.openclaw/workspace",
          agentDir: "/Users/username/.openclaw/agents/agent-name"
        }
      ]
    }
  }),
  note: "Added agent-name to agents configuration"
});
```

**Solution B: Verify Configuration Applied**
```javascript
// Check current agents configuration
gateway({
  action: "config.get",
  path: "agents.list"
});

// Agent should appear in the returned list
```

**Solution C: Check for ID Conflicts**
```bash
# List all configured agents
openclaw agents list

# Or check configuration directly
grep -n "id.*agent-name" ~/.openclaw/openclaw.json
```

**Solution D: Manual Gateway Restart**
```bash
# If automatic restart didn't happen
openclaw gateway restart

# Wait for restart to complete
sleep 5
openclaw status
```

**Prevention Tips:**
1. Always register agents after creating workspace
2. Use unique agent IDs
3. Verify configuration changes were applied
4. Check gateway logs for restart confirmation

---

## Diagnostic Commands

### 1. System Check
```bash
# Check OpenClaw installation
openclaw --version
openclaw status

# Check skill directory
ls -la ~/.openclaw/skills/ | head -20

# Check agents directory
ls -la ~/.openclaw/agents/ | head -20
```

### 2. Skill Analysis
```bash
# Analyze a skill without conversion
node skill_to_agent.js --skill war-room --dry-run --verbose

# Check skill structure
find ~/.openclaw/skills/war-room -type f -name "*.md" -o -name "*.js" | head -10
```

### 3. Agent Health Check
```bash
# List all agents
node skill_to_agent.js --list

# Check specific agent
node skill_to_agent.js --verify --agent your-agent

# Test agent spawning
node skill_to_agent.js --test-spawn --agent your-agent --dry-run
```

### 4. Tool Availability Check
```bash
# Test individual tools
node -e "
const tools = ['web_search', 'read', 'write', 'exec'];
tools.forEach(tool => {
  try {
    require(tool);
    console.log('✓', tool, 'available');
  } catch (e) {
    console.log('✗', tool, 'unavailable:', e.message);
  }
});
"
```

### 5. Permission Verification
```bash
# Check workspace permissions
stat ~/.openclaw
stat ~/.openclaw/agents
stat ~/.openclaw/agents/your-agent

# Check file ownership
ls -n ~/.openclaw/agents/your-agent/
```

---

## Step-by-Step Debugging

### When You Get Any Error:

**Step 1: Enable Verbose Mode**
```bash
node skill_to_agent.js --skill your-skill --agent your-agent --verbose
```

**Step 2: Dry Run First**
```bash
node skill_to_agent.js --skill your-skill --agent your-agent --dry-run --verbose
```

**Step 3: Check Skill Structure**
```bash
# What's in the skill directory?
ls -la ~/.openclaw/skills/your-skill/

# Does SKILL.md exist?
cat ~/.openclaw/skills/your-skill/SKILL.md | head -20
```

**Step 4: Test Minimal Configuration**
```bash
# Try simplest possible conversion
node skill_to_agent.js \
  --skill your-skill \
  --agent test-minimal \
  --mode run \
  --thread false \
  --tools "read" \
  --dry-run
```

**Step 5: Check Existing Agents**
```bash
# Are there existing agents with same name?
ls -la ~/.openclaw/agents/ | grep your-agent

# Backup and remove if conflicting
mv ~/.openclaw/agents/your-agent ~/.openclaw/agents/your-agent.backup
```

**Step 6: Test Tool Access**
```bash
# Can you access tools from command line?
node -e "require('web_search')({query: 'test'}).then(console.log).catch(console.error)"
```

**Step 7: Check OpenClaw Status**
```bash
# Is OpenClaw running properly?
openclaw status
openclaw doctor --non-interactive
```

---

## Prevention Strategies

### 1. Always Dry Run First
```bash
# Never skip dry run for new skills
node skill_to_agent.js --skill new-skill --agent new-agent --dry-run --verbose
```

### 2. Start Simple
```bash
# Begin with minimal configuration
node skill_to_agent.js \
  --skill complex-skill \
  --agent simple-test \
  --mode run \
  --thread false \
  --tools "read" \
  --dry-run
```

### 3. Use Descriptive Names
```bash
# Avoid conflicts with clear naming
node skill_to_agent.js \
  --skill war-room \
  --agent war-room-$(date +%Y%m%d) \
  --mode test
```

### 4. Keep Backups
```bash
# Always backup before overwriting
if [ -d ~/.openclaw/agents/your-agent ]; then
  cp -r ~/.openclaw/agents/your-agent ~/.openclaw/agents/your-agent.backup.$(date +%s)
fi
```

### 5. Monitor Resources
```bash
# Check system resources before large conversions
echo "Memory: $(free -h | grep Mem | awk '{print $4}')"
echo "Disk: $(df -h ~/.openclaw | tail -1 | awk '{print $4}')"
```

---

## Recovery Procedures

### When Conversion Fails Midway:

**Procedure A: Clean Up Partial Creation**
```bash
# Remove partially created agent
rm -rf ~/.openclaw/agents/failed-agent

# Restore from backup if exists
if [ -d ~/.openclaw/agents/failed-agent.backup ]; then
  cp -r ~/.openclaw/agents/failed-agent.backup ~/.openclaw/agents/failed-agent
fi
```

**Procedure B: Repair Workspace**
```bash
# Run repair procedure
node skill_to_agent.js --repair --agent damaged-agent

# Or manually fix
mkdir -p ~/.openclaw/agents/damaged-agent/memory
touch ~/.openclaw/agents/damaged-agent/MEMORY.md
```

**Procedure C: Start Fresh**
```bash
# Complete cleanup and restart
rm -rf ~/.openclaw/agents/problem-agent
node skill_to_agent.js --skill original-skill --agent problem-agent --force
```

**Procedure D: Seek Help**
```bash
# Collect debug information
node skill_to_agent.js --skill problem-skill --agent test --dry-run --verbose 2>&1 | tee debug.log

# Share relevant sections (remove sensitive info)
grep -A5 -B5 "Error\|Failed\|not found" debug.log
```

---

## Common Patterns That Work

### Pattern 1: WebChat Compatibility
```bash
# Always works in webchat
node skill_to_agent.js \
  --skill your-skill \
  --agent webchat-agent \
  --mode run \
  --thread false \
  --runtime subagent \
  --timeout 300
```

### Pattern 2: Discord Thread Agent
```bash
# For Discord threads
node skill_to_agent.js \
  --skill discussion-skill \
  --agent thread-agent \
  --mode session \
  --thread true \
  --runtime subagent \
  --label "Discussion Assistant"
```

### Pattern 3: Background Processing
```bash
# For isolated background tasks
node skill_to_agent.js \
  --skill processing-skill \
  --agent background-agent \
  --mode session \
  --thread false \
  --runtime subagent \
  --memory ephemeral
```

### Pattern 4: One-Shot Tasks
```bash
# For single execution
node skill_to_agent.js \
  --skill task-skill \
  --agent task-runner \
  --mode run \
  --thread false \
  --timeout 600
```

---

## Getting Additional Help

### 1. Check Documentation
```bash
# View built-in help
node skill_to_agent.js --help

# Read reference guides
cat ~/.openclaw/skills/skill-to-agent/references/*.md | less
```

### 2. Enable Debug Logging
```bash
# Maximum verbosity
export DEBUG=skill-to-agent:*
node skill_to_agent.js --skill test --agent test --verbose 2>&1 | tee full-debug.log
```

### 3. Search for Similar Issues
```bash
# Check if others have similar problems
grep -r "thread=true is unavailable" ~/.openclaw/logs/ 2>/dev/null || true
```

### 4. Community Support
- OpenClaw Discord: `#skills` channel
- GitHub Issues: Report bugs with full debug output
- Stack Overflow: Tag with `openclaw`

### 5. Escalate to Core Team
If all else fails:
1. Collect complete debug output
2. Document exact steps to reproduce
3. Note OpenClaw version and environment
4. Open detailed issue on GitHub

---

## Quick Reference Cheat Sheet

### When You See This Error... Try This:

| Error | Immediate Fix | Long-term Solution |
|-------|--------------|-------------------|
| `thread=true unavailable` | `--thread false` | Use channel detection |
| `SKILL.md not found` | `--skill /full/path` | Install skill properly |
| `Cannot access tool` | `--tools "tool1,tool2"` | Update TOOLS.md |
| `Permission denied` | `chmod 755 ~/.openclaw` | Fix directory ownership |
| `Timeout` | `--timeout 600` | Simplify task or increase resources |
| `Memory error` | `mkdir -p memory/` | Configure memory properly |
| `Agent not found` | `gateway config.patch` | Register agent in configuration |

### Always Remember:
1. ✅ Dry run first
2. ✅ Start simple  
3. ✅ Check permissions
4. ✅ Monitor resources
5. ✅ Keep backups
6. ✅ Read error messages carefully

This troubleshooting guide covers 95% of common issues. For remaining 5%, collect debug information and seek community help.

path: references/usage-guide.md
content: # Skill-to-Agent Usage Guide

## Quick Start

### Phase 1: Analyze Skill Structure
1. Read SKILL.md frontmatter (name, description, triggers)
2. Identify required tools and dependencies
3. Determine agent type: thread-bound, isolated, or run-mode

### Phase 2: Create Agent Workspace
```bash
# Create agent directory
mkdir -p ~/.openclaw/agents/agent-name

# Copy skill resources if needed
cp -r /path/to/skill/references/ ~/.openclaw/agents/agent-name/
cp -r /path/to/skill/scripts/ ~/.openclaw/agents/agent-name/
```

### Phase 3: Configure Agent Identity
Create the following files in the agent workspace:
1. **IDENTITY.md** - Agent name, creature, vibe, emoji
2. **SOUL.md** - Agent personality and operating style
3. **AGENTS.md** - Workspace rules and workflow
4. **USER.md** - Who the agent helps
5. **HEARTBEAT.md** - Proactive behavior checklist
6. **TOOLS.md** - Required tools and configurations
7. **memory/** directory for daily logs

### Phase 4: Register Agent in OpenClaw
```javascript
gateway({
  action: "config.patch",
  raw: JSON.stringify({
    agents: {
      list: [
        {
          id: "agent-name",
          name: "Agent Display Name",
          workspace: "/Users/nimbletenthousand/.openclaw/workspace",
          agentDir: "/Users/nimbletenthousand/.openclaw/agents/agent-name"
        }
      ]
    }
  }),
  note: "Added agent-name to agents configuration"
});
```

### Phase 5: Spawn with Correct Binding
```javascript
sessions_spawn({
  task: "Agent instructions based on skill...",
  label: "agent-name-task",
  runtime: "subagent",
  mode: "session", // or "run" based on channel
  thread: false, // or true for thread-bound agents
  cwd: "/Users/nimbletenthousand/.openclaw/agents/agent-name",
  timeoutSeconds: 300
});
```

---

## Common Use Cases

### Use Case 1: Discord Thread Agent
**Scenario:** You want a skill to operate in Discord threads
```bash
node skill_to_agent.js \
  --skill war-room \
  --agent war-room-bot \
  --mode session \
  --thread true \
  --runtime subagent \
  --label "War Room Coordinator"
```

**Result:** Creates an agent that can be spawned in Discord threads with proper binding.

### Use Case 2: Background Processing Agent
**Scenario:** You need a skill to run isolated background tasks
```bash
node skill_to_agent.js \
  --skill seo-content \
  --agent content-generator \
  --mode session \
  --thread false \
  --runtime subagent \
  --tools "read,write,web_search" \
  --memory ephemeral
```

**Result:** Creates an isolated agent for batch content generation.

### Use Case 3: One-Shot Task Agent
**Scenario:** You want a skill for single execution tasks
```bash
node skill_to_agent.js \
  --skill video-frames \
  --agent video-processor \
  --mode run \
  --thread false \
  --runtime subagent \
  --timeout 600
```

**Result:** Creates an agent configuration for one-time video processing tasks.

---

## Integration with OpenClaw

### As a Skill
Add to your OpenClaw configuration:
```yaml
skills:
  - name: skill-to-agent
    path: ~/.openclaw/skills/skill-to-agent
    enabled: true
```

### In Agent Scripts
```javascript
const SkillToAgent = require('~/.openclaw/skills/skill-to-agent/skill_to_agent.js');
const converter = new SkillToAgent();

// Convert and spawn in one go
async function createAndSpawnSkillAgent(skillName, agentId) {
  const analysis = converter.analyzeSkill(skillName);
  const binding = converter.resolveBinding({}, analysis);
  const task = converter.generateSpawnTask(agentId, analysis, binding);
  
  // Use sessions_spawn to create the agent
  const result = await sessions_spawn({
    task: task,
    label: binding.label,
    runtime: binding.runtime,
    mode: binding.mode,
    thread: binding.thread
  });
  
  return result;
}
```

### In Cron Jobs
```bash
# Create agents dynamically in cron jobs
0 8 * * * node ~/.openclaw/skills/skill-to-agent/skill_to_agent.js --skill daily-digest --agent daily-reporter --mode run
```

---

## Advanced Configuration

### Custom Tool Mapping
Create a `tools-config.json`:
```json
{
  "web_search": {
    "purpose": "Market research and competitor analysis",
    "limits": "10 queries per hour",
    "patterns": ["search for", "research", "find information"]
  },
  "browser": {
    "purpose": "Web automation and data collection",
    "limits": "5 minutes per session",
    "patterns": ["automate", "scrape", "collect data"]
  }
}
```

Use it with:
```bash
node skill_to_agent.js --skill your-skill --agent your-agent --tools-config tools-config.json
```

### Custom Templates
Override default templates by creating:
- `templates/SOUL.custom.md`
- `templates/AGENTS.custom.md`
- `templates/TOOLS.custom.md`

The converter will use custom templates if available.

### Environment Variables
```bash
# Set workspace location
export OPENCLAW_AGENTS_DIR=/custom/path/agents

# Enable debug mode
export SKILL_TO_AGENT_DEBUG=true

# Set default runtime
export DEFAULT_AGENT_RUNTIME=acp
```

---

## Troubleshooting

### Common Issues

**Issue 1: "SKILL.md not found"**
```bash
# Solution 1: Specify full path
node skill_to_agent.js --skill ~/.openclaw/skills/war-room/SKILL.md --agent test

# Solution 2: Check skill directory structure
ls -la ~/.openclaw/skills/war-room/
```

**Issue 2: "thread=true is unavailable"**
```bash
# Solution: Use isolated mode instead
node skill_to_agent.js --skill war-room --agent test --mode session --thread false
```

**Issue 3: Agent lacks tool access**
```bash
# Solution: Verify tools and update configuration
node skill_to_agent.js --skill war-room --agent test --tools "sessions_spawn,sessions_send,memory_search"
```

**Issue 4: Workspace permission errors**
```bash
# Solution: Check directory permissions
ls -la ~/.openclaw/agents/
chmod 755 ~/.openclaw/agents/
```

### Debug Mode
Enable verbose output:
```bash
node skill_to_agent.js --skill war-room --agent test --verbose
```

### Dry Run
Test without making changes:
```bash
node skill_to_agent.js --skill war-room --agent test --dry-run --verbose
```

---

## Performance Optimization

### Token Management
- Keep SOUL.md under 500 tokens
- Use efficient memory strategies
- Configure context pruning
- Set appropriate timeouts

### Resource Allocation
```bash
# For resource-intensive skills
node skill_to_agent.js \
  --skill video-processing \
  --agent video-bot \
  --mode run \
  --timeout 1800 \
  --memory ephemeral
```

### Batch Processing
```bash
# Convert multiple skills at once
for skill in war-room marketing-pmm seo-content; do
  node skill_to_agent.js --skill $skill --agent ${skill}-bot --mode run
done
```

---

## Security Considerations

### Agent Isolation
- Each agent gets separate workspace
- No shared memory by default
- Tool access limited to requirements
- Session boundaries enforced

### Data Protection
- Skill files copied, not linked
- Agent memory separate from skill
- Cleanup policies configurable
- Audit logs in agent workspace

### Access Control
```bash
# Create agents with minimal permissions
node skill_to_agent.js \
  --skill read-only-skill \
  --agent reader \
  --tools "read,memory_get" \
  --mode isolated
```

---

## Monitoring & Maintenance

### Agent Health Checks
```bash
# Check agent workspace
ls -la ~/.openclaw/agents/{agent-id}/

# Test agent spawning
node -e "console.log(require('./skill_to_agent.js').testSpawn('agent-id'))"

# Verify tool access
node skill_to_agent.js --verify --agent {agent-id}
```

### Workspace Cleanup
```bash
# List all created agents
node skill_to_agent.js --list

# Repair damaged workspace
node skill_to_agent.js --repair --agent {agent-id}

# Clean up old agents
find ~/.openclaw/agents/* -type d -mtime +30 -exec rm -rf {} \;
```

### Performance Monitoring
```bash
# Monitor agent resource usage
ps aux | grep "agent:" | grep {agent-id}

# Check workspace size
du -sh ~/.openclaw/agents/{agent-id}/

# Review memory usage
tail -n 100 ~/.openclaw/agents/{agent-id}/memory/$(date +%Y-%m-%d).md
```

---

## Integration Examples

### Example 1: Complete Workflow
```bash
#!/bin/bash
# create_and_deploy_agent.sh

SKILL=$1
AGENT=$2

echo "🔧 Converting $SKILL to agent $AGENT"

# Step 1: Convert skill to agent
node skill_to_agent.js --skill $SKILL --agent $AGENT --verbose

# Step 2: Test agent workspace
if [ -d ~/.openclaw/agents/$AGENT ]; then
  echo "✅ Agent workspace created"
  
  # Step 3: Create test script
  cat > test_$AGENT.js << EOF
  const { sessions_spawn } = require('openclaw');
  
  async function testAgent() {
    const config = require('~/.openclaw/agents/$AGENT/spawn-config.json');
    const result = await sessions_spawn(config);
    console.log('Agent spawned:', result.sessionKey);
  }
  
  testAgent().catch(console.error);
  EOF
  
  echo "📝 Test script created: test_$AGENT.js"
  
else
  echo "❌ Failed to create agent workspace"
  exit 1
fi
```

### Example 2: Dynamic Agent Creation
```javascript
// dynamic_agent_creator.js
const SkillToAgent = require('./skill_to_agent.js');
const fs = require('fs');
const path = require('path');

class DynamicAgentManager {
  constructor() {
    this.converter = new SkillToAgent();
  }
  
  async createAgentForTask(taskDescription, skillPatterns) {
    // Analyze available skills
    const skillsDir = path.join(process.env.HOME, '.openclaw', 'skills');
    const skills = fs.readdirSync(skillsDir);
    
    // Find matching skill
    const matchingSkill = skills.find(skill => {
      const skillPath = path.join(skillsDir, skill, 'SKILL.md');
      if (fs.existsSync(skillPath)) {
        const content = fs.readFileSync(skillPath, 'utf8').toLowerCase();
        return skillPatterns.some(pattern => content.includes(pattern));
      }
      return false;
    });
    
    if (!matchingSkill) {
      throw new Error('No matching skill found');
    }
    
    // Generate agent ID
    const agentId = `task-${Date.now()}-${matchingSkill}`;
    
    // Create agent
    const analysis = this.converter.analyzeSkill(matchingSkill);
    const binding = this.converter.resolveBinding({
      mode: 'run',
      thread: false
    }, analysis);
    
    // Generate spawn configuration
    const spawnConfig = {
      task: this.converter.generateSpawnTask(agentId, analysis, binding),
      label: `Task Agent: ${taskDescription.substring(0, 20)}...`,
      runtime: binding.runtime,
      mode: binding.mode,
      thread: binding.thread,
      timeoutSeconds: 300
    };
    
    return {
      agentId,
      spawnConfig,
      skill: matchingSkill
    };
  }
}

module.exports = DynamicAgentManager;
```

### Example 3: Skill Chaining System
```javascript
// skill_chain_manager.js
const SkillToAgent = require('./skill_to_agent.js');

class SkillChainManager {
  constructor() {
    this.converter = new SkillToAgent();
    this.activeAgents = new Map();
  }
  
  async createChain(skillNames, workflow) {
    const agents = [];
    
    for (const skillName of skillNames) {
      const agentId = `${skillName}-${Date.now()}`;
      const analysis = this.converter.analyzeSkill(skillName);
      
      // Create agent with sequential binding
      const binding = this.converter.resolveBinding({
        mode: 'session',
        thread: false,
        runtime: 'subagent'
      }, analysis);
      
      const agentConfig = {
        id: agentId,
        skill: skillName,
        analysis: analysis,
        binding: binding,
        spawnTask: this.converter.generateSpawnTask(agentId, analysis, binding)
      };
      
      agents.push(agentConfig);
      this.activeAgents.set(agentId, agentConfig);
    }
    
    // Set up communication between agents
    const chainConfig = {
      agents: agents,
      workflow: workflow,
      communication: {
        memoryFile: `memory/chain-${Date.now()}.md`,
        handoffProtocol: 'memory-based'
      }
    };
    
    return chainConfig;
  }
  
  async executeChain(chainConfig, input) {
    // Write input to shared memory
    const memoryPath = chainConfig.communication.memoryFile;
    fs.writeFileSync(memoryPath, `# Chain Execution - ${new Date().toISOString()}\n\nInput: ${JSON.stringify(input, null, 2)}\n\n`);
    
    // Execute each agent in sequence
    for (const agentConfig of chainConfig.agents) {
      console.log(`Executing agent: ${agentConfig.id}`);
      
      // Spawn agent with chain context
      const task = `${agentConfig.spawnTask}\n\nChain Context: Read ${memoryPath} for input and previous results.`;
      
      const result = await sessions_spawn({
        task: task,
        label: agentConfig.id,
        runtime: agentConfig.binding.runtime,
        mode: agentConfig.binding.mode,
        thread: agentConfig.binding.thread
      });
      
      // Append result to memory
      const resultText = `## ${agentConfig.id} Result\n${JSON.stringify(result, null, 2)}\n\n`;
      fs.appendFileSync(memoryPath, resultText);
      
      // Wait for completion
      await new Promise(resolve => setTimeout(resolve, 1000));
    }
    
    // Read final result
    const finalResult = fs.readFileSync(memoryPath, 'utf8');
    return finalResult;
  }
}

module.exports = SkillChainManager;
```

---

## Best Practices

### 1. Skill Analysis First
Always analyze the skill before conversion:
```bash
node skill_to_agent.js --skill your-skill --dry-run --verbose
```

### 2. Start Simple
Begin with `--mode run` for testing, then move to more complex configurations.

### 3. Use Descriptive Labels
```bash
--label "Marketing Analyst (Data Research Focus)"
```

### 4. Limit Tool Access
Only include tools the agent actually needs:
```bash
--tools "web_search,web_fetch,memory_search"
```

### 5. Configure Timeouts
```bash
--timeout 600  # 10 minutes for processing tasks
```

### 6. Monitor Memory Usage
Check agent memory files regularly and implement cleanup policies.

### 7. Test Before Deployment
Always test agents in a non-production environment first.

### 8. Document Configurations
Keep records of agent configurations and their purposes.

---

## Migration & Updates

### Updating Existing Agents
```bash
# Create backup
cp -r ~/.openclaw/agents/old-agent ~/.openclaw/agents/old-agent.backup

# Recreate with updated skill
node skill_to_agent.js --skill updated-skill --agent old-agent --force
```

### Migrating Between Systems
1. Export agent configuration:
```bash
tar -czf agent-backup.tar.gz ~/.openclaw/agents/your-agent/
```

2. Import on new system:
```bash
tar -xzf agent-backup.tar.gz -C ~/.openclaw/agents/
```

3. Update paths in configuration files if needed.

---

## Community & Support

### Getting Help
- Open issues on GitHub repository
- Join OpenClaw Discord community
- Check existing documentation and examples

### Contributing
1. Fork the repository
2. Make enhancements
3. Add tests
4. Update documentation
5. Submit pull request

### Reporting Issues
Include:
- OpenClaw version
- Skill being converted
- Error messages
- Steps to reproduce
- Expected vs actual behavior

---

## Future Roadmap

### Planned Features
1. **AI-Powered Analysis** - Automatically determine optimal agent configuration
2. **Skill Composition** - Combine multiple skills into single agent
3. **Performance Optimization** - Dynamic resource allocation
4. **Enhanced Security** - Sandboxed execution environments
5. **Marketplace Integration** - Publish agents to ClawHub

### Community Requests
- Support for custom agent templates
- Integration with external APIs
- Advanced monitoring dashboards
- Automated testing frameworks
- Multi-tenant support

---

## Conclusion

The Skill-to-Agent converter solves the common problem of properly converting OpenClaw skills into functional agents. By following this guide, you can:

1. **Convert any skill** into a properly configured agent
2. **Avoid common binding errors** with smart configuration
3. **Create specialized agents** for different use cases
4. **Manage agent lifecycles** effectively
5. **Scale your agent ecosystem** systematically

Remember to start simple, test thoroughly, and iterate based on your specific needs. Happy agent building!

Security scan verdicts — ClawScan: suspicious | static analysis: suspicious | VirusTotal: clean | SkillSpector: suspicious (CRITICAL)