
# Kollabor Agent System

Comprehensive guide to agents, skills, and the agent orchestrator system in Kollabor CLI.

---

## Table of Contents

- [Overview](#overview)
- [Agent Architecture](#agent-architecture)
- [Agent Structure](#agent-structure)
- [Built-in Agents](#built-in-agents)
- [Creating Custom Agents](#creating-custom-agents)
- [Skills System](#skills-system)
- [Prompt Rendering](#prompt-rendering)
- [Agent Orchestrator](#agent-orchestrator)
- [CLI Commands](#cli-commands)
- [Configuration](#configuration)

---

## Overview

The Kollabor Agent System provides a flexible framework for creating specialized AI assistants that can be activated dynamically during conversations. Agents have their own system prompts, skills, and optionally preferred LLM profiles.

### Key Concepts

- **Agents**: Specialized AI assistants with unique system prompts and skills
- **Skills**: Dynamic context modules that can be loaded/unloaded on demand
- **Local vs Global**: Project-specific agents override global user agents
- **Prompt Rendering**: Dynamic content via `<trender>` tags
- **Agent Orchestrator**: Parallel sub-agent execution via XML commands

---

## Agent Architecture

### Directory Structure

```
~/.kollabor-cli/agents/           # Global agents (user defaults)
  ├── default/
  ├── coder/
  ├── research/
  └── ...

.kollabor-cli/agents/               # Local agents (project-specific)
  ├── my-agent/
  └── ...                          # Overrides global agents with same name
```

### Discovery Order

1. Global agents loaded first (`~/.kollabor-cli/agents/`)
2. Local agents loaded second (`.kollabor-cli/agents/`)
3. Local agents **override** global agents with same name

### Agent Manager

The `AgentManager` class (`kollabor/llm/agent_manager.py`) handles:
- Agent discovery from directories
- Dynamic skill loading/unloading
- Active agent management
- Default skill persistence

---

## Agent Structure

Each agent is a directory containing:

### Required Files

```
my-agent/
  └── system_prompt.md     # Base system prompt (required)
```

### Optional Files

```
my-agent/
  ├── agent.json           # Configuration (optional)
  ├── skill-one.md         # Skill files (optional)
  ├── skill-two.md
  └── ...
```

### agent.json Format

```json
{
  "description": "Human-readable description of the agent",
  "profile": "preferred-llm-profile",
  "default_skills": ["skill-one", "skill-two"]
}
```

Fields:
- `description`: Human-readable agent description
- `profile`: Preferred LLM profile name (optional)
- `default_skills`: Skills to auto-load when agent is activated

---

## Built-in Agents

### Default Agent

The main Kollabor assistant with comprehensive development capabilities.

**Location**: `bundles/agents/default/`

**Features**:
- Modular system prompt with 23+ sections
- Investigation-first philosophy
- Tool execution capabilities
- Git workflow integration
- Code quality and testing

**Skills**: None (modular via `sections/` includes)

**Description**: "Specialized agent for fixing linting errors and code quality issues"

### Coder Agent

Fast implementation agent that ships code aggressively.

**Location**: `bundles/agents/coder/`

**Skills**:
- `code-review.md` - Comprehensive code review methodology
- `cli-pretty.md` - Pretty CLI output formatting
- `api-integration.md` - API integration patterns
- `database-design.md` - Database design principles
- `debugging.md` - Debugging techniques
- `dependency-management.md` - Dependency handling
- `git-workflow.md` - Git best practices
- `refactoring.md` - Refactoring strategies
- `security-hardening.md` - Security practices
- `tdd.md` - Test-driven development

**Description**: "Fast implementation agent - ships code aggressively with less questioning"

### Kollabor Agent

Meta-agent for building agents and skills.

**Location**: `bundles/agents/kollabor/`

**Skills**:
- `analyze-plugin-lifecycle.md` - Plugin lifecycle debugging
- `analyze-terminal-rendering.md` - Terminal rendering analysis
- `debug-mcp-integration.md` - MCP integration debugging
- `debug-plugin-hooks.md` - Plugin hook debugging
- `code-review.md` - Code review
- `debugging.md` - General debugging
- `dependency-management.md` - Dependency management
- `git-workflow.md` - Git workflow
- `inspect-llm-conversation.md` - LLM conversation inspection
- `monitor-event-bus.md` - Event bus monitoring
- `profile-performance.md` - Performance profiling
- `refactoring.md` - Refactoring
- `trace-command-execution.md` - Command execution tracing
- `validate-config.md` - Configuration validation

**Description**: Meta-agent for building agents and skills

### Research Agent

Deep investigation and analysis specialist.

**Location**: `bundles/agents/research/`

**Philosophy**: "UNDERSTAND COMPLETELY, CHANGE NOTHING"

**Skills**: Project-specific investigation capabilities

### Creative Writer Agent

Fiction and prose writing collaborator.

**Location**: `bundles/agents/creative-writer/`

**Philosophy**: "STORY FIRST, CRAFT ALWAYS"

**Skills**: Narrative and prose assistance

### Technical Writer Agent

Documentation and technical writing specialist.

**Location**: `bundles/agents/technical-writer/`

**Philosophy**: "CLARITY IS KING"

**Skills**:
- `api-documentation.md` - API documentation
- `changelog-management.md` - Changelog maintenance
- `readme-writing.md` - README writing
- `style-guide.md` - Style guide
- `tutorial-creation.md` - Tutorial creation

### Data Analyst Agent

Data analysis and visualization specialist.

**Location**: `bundles/agents/data-analyst/`

**Skills**:
- `data-visualization.md` - Data visualization
- `exploratory-data-analysis.md` - EDA techniques
- `pandas-data-manipulation.md` - Pandas operations
- `sql-query-optimization.md` - SQL optimization
- `statistical-analysis.md` - Statistical methods

---

## Creating Custom Agents

### Manual Creation

1. Create agent directory:
```bash
mkdir .kollabor-cli/agents/my-agent
```

2. Create system prompt:
```bash
cat > .kollabor-cli/agents/my-agent/system_prompt.md << 'EOF'
my-agent v0.1

i am my-agent, a specialized assistant.

core philosophy: YOUR PHILOSOPHY HERE

session context:
  time:              <trender>date '+%Y-%m-%d %H:%M:%S %Z'</trender>
  system:            <trender>uname -s</trender> <trender>uname -m</trender>
  user:              <trender>whoami</trender>
  working directory:  <trender>pwd</trender>

## Your Mission

Describe what this agent does.

## Approach

1. Step 1
2. Step 2
3. Step 3
EOF
```

3. Optional: Create agent.json:
```bash
cat > .kollabor-cli/agents/my-agent/agent.json << 'EOF'
{
  "description": "Brief description of my-agent",
  "profile": null
}
EOF
```

4. Refresh agent discovery:
```bash
# Agent will be auto-discovered on next run
```

### Programmatic Creation

Use the AgentManager API:

```python
from kollabor.llm.agent_manager import AgentManager

agent_manager = AgentManager(config)

agent = agent_manager.create_agent(
    name="my-agent",
    description="Brief description",
    profile=None,  # or "gpt-4", etc.
    system_prompt="my-agent v0.1\n\ni am a specialized assistant...",
    default_skills=["skill-one"]
)
```

---

## Skills System

### What Are Skills?

Skills are markdown files containing instructions or context that can be dynamically loaded into an agent's active context during a conversation.

### Skill File Format

```
skill-name.md:

<!-- Description: Brief description of this skill -->

# Skill Name

Detailed skill content here.

## Methodology

Step 1: ...
Step 2: ...
Step 3: ...
```

The HTML comment at the top is extracted as the skill description.

### Creating Skills

1. Create skill file in agent directory:
```bash
cat > .kollabor-cli/agents/my-agent/my-skill.md << 'EOF'
<!-- Description: Adds capability for task X -->

# My Skill

This skill enables the agent to do X.

## Methodology

1. Analyze the situation
2. Apply X technique
3. Verify results
EOF
```

2. The skill is now available in the agent

### Loading/Unloading Skills

**Via API**:
```python
# Load skill
agent_manager.load_skill("my-skill", agent_name="my-agent")

# Unload skill
agent_manager.unload_skill("my-skill", agent_name="my-agent")
```

**Via conversation**:
Use slash commands or natural language to request skill loading.

### Default Skills

Set skills that auto-load when agent is activated:

```json
{
  "default_skills": ["skill-one", "skill-two"]
}
```

Or toggle via API:
```python
success, is_default = agent_manager.toggle_default_skill(
    "my-skill",
    agent_name="my-agent",
    scope="project"  # or "global"
)
```

---

## Prompt Rendering

### `<trender>` Commands

Execute shell commands dynamically in system prompts:

```markdown
session context:
  time:              <trender>date '+%Y-%m-%d %H:%M:%S %Z'</trender>
  user:              <trender>whoami</trender>
  working directory:  <trender>pwd</trender>

git status:
<trender>
git status --short 2>/dev/null | head -10 || echo "not a git repo"
</trender>
```

### `<trender type="include">` Tags

Include external markdown files:

```markdown
<trender type="include" path="sections/01-header.md" />
<trender type="include" path="sections/02-workflow.md" />
```

### Modular System Prompts

The `default` agent uses this pattern:

```
bundles/agents/default/
  ├── system_prompt.md     # Main file with includes
  └── sections/           # Modular sections
      ├── 00-header.md
      ├── 01-session-context.md
      ├── 02-tool-workflow.md
      └── ...
```

**system_prompt.md**:
```markdown
<trender type="include" path="sections/00-header.md" />
<trender type="include" path="sections/01-session-context.md" />
<trender type="include" path="sections/02-tool-workflow.md" />
...
```

Benefits:
- Easy maintenance
- Reusable sections
- Clear organization

---

## Agent Orchestrator

The Agent Orchestrator plugin enables parallel sub-agent execution via XML commands.

### Commands

#### Spawn Agents

```xml
<agent>
  <agent-name>
    <task>
    objective: What to accomplish

    context:
    - Relevant constraints
    - Background info

    todo:
    [ ] Step 1
    [ ] Step 2

    success: How to verify completion
    </task>
    <files>
      <file>path/to/file.py</file>
    </files>
  </agent-name>
</agent>
```

#### Other Commands

```xml
<!-- Send message to running agent -->
<message to="agent-name">Your message here</message>

<!-- Capture output from agent -->
<capture>agent-name 200</capture>

<!-- Stop agent -->
<stop>agent-name</stop>

<!-- Check status of all agents -->
<status></status>

<!-- Clone agent with conversation context -->
<clone>
  <agent-name>
    <task>New task for clone</task>
  </agent-name>
</clone>

<!-- Spawn team lead -->
<team lead="lead-name" max-workers="5">
  <agent-name>
    <task>Coordinate team task</task>
  </agent-name>
</team>

<!-- Broadcast message to agents matching pattern -->
<broadcast pattern="research-*">Important update</broadcast>
```

### Agent Behavior

- Agents run in separate tmux sessions
- Auto-completion when idle (MD5 hash unchanged for 6 seconds)
- Results injected back to main conversation
- Files in `<files>` auto-attached to agent context

### Slash Commands

```
/subagent list                    List all active agents
/subagent status <name>           Get status of specific agent
/subagent capture <name> [lines]  Capture output from agent
/subagent stop <name>             Stop an agent
/subagent message <name> <msg>    Send message to agent
```

Aliases: `/sa`

### CLI Arguments

```bash
kollab --session agent-name                Interact with specific session
kollab --session agent-name --capture 100  Capture output from session
kollab --list-agents                      List all active agents and exit
```

---

## CLI Commands

### Agent Selection

```bash
# Select agent via CLI
kollab --agent coder

# Set project default agent
# Edit .kollabor-cli/config.json
{
  "default_agent": "coder"
}
```

### Agent Management

Available commands (via slash commands or plugins):

- List agents: `/subagent list`
- View agent info: `/agent info <name>`
- Load skill: `/skill load <name>`
- Unload skill: `/skill unload <name>`
- Create agent: Via API or manual creation
- Delete agent: Via API (only local agents)

---

## Configuration

### Environment Variables

No specific environment variables for agents. Agents use the general LLM configuration.

### Config Files

**Project Config** (`.kollabor-cli/config.json`):
```json
{
  "default_agent": "coder"
}
```

**Global Config** (`~/.kollabor-cli/config.json`):
```json
{
  "default_agent": "default"
}
```

Priority: CLI argument > Project config > Global config > "default" agent

### Plugin Config

Agent Orchestrator plugin configuration:

```json
{
  "plugins": {
    "agent_orchestrator": {
      "enabled": true,
      "poll_interval": 2,
      "idle_threshold": 3,
      "capture_lines": 500,
      "max_concurrent": 10,
      "enable_mode": "keyword",
      "trigger_delay": "0"
    }
  }
}
```

Options:
- `enabled`: Enable/disable orchestrator
- `poll_interval`: Seconds between status checks
- `idle_threshold`: Seconds of inactivity before completion
- `capture_lines`: Default lines to capture on stop
- `max_concurrent`: Maximum parallel agents
- `enable_mode`: "startup" (inject in system prompt) or "keyword" (trigger on keywords)
- `trigger_delay`: "0" (once), "60s" (every 60s), "5m" (every 5 messages)

---

## Best Practices

### Agent Design

1. **Specific Purpose**: Each agent should have a clear, focused purpose
2. **Modular Skills**: Break complex capabilities into reusable skills
3. **Clear Philosophy**: State core philosophy upfront for consistent behavior
4. **Session Context**: Include `<trender>` commands for dynamic context
5. **Description**: Provide clear description in `agent.json`

### Skill Design

1. **HTML Comment**: Use `<!-- Description: ... -->` for skill descriptions
2. **Methodology First**: Structure skills with clear methodology
3. **Reusable**: Design skills that can be loaded independently
4. **Context-Aware**: Skills should work with agent's base prompt

### Prompt Rendering

1. **Cache Friendly**: Use commands with consistent output
2. **Error Handling**: Provide fallbacks for failed commands
3. **Performance**: Avoid long-running commands in `<trender>`
4. **Modular**: Use includes for organization

### Agent Orchestrator

1. **Parallel Tasks**: Use agents for independent parallel work
2. **Clear Tasks**: Provide detailed task specifications
3. **File Attachments**: Include necessary files via `<files>` tags
4. **Monitoring**: Check agent status regularly via `/subagent status`

---

## Examples

### Example Agent: Python Debugger

**Create agent**:
```bash
mkdir -p .kollabor-cli/agents/python-debugger
```

**system_prompt.md**:
```markdown
python-debugger v0.1

i am python-debugger, a Python debugging specialist.

core philosophy: TRACE THE BUG, FIX THE ROOT
identify the root cause before proposing fixes.

session context:
  time:              <trender>date '+%Y-%m-%d %H:%M:%S %Z'</trender>
  working directory:  <trender>pwd</trender>

python environment:
<trender>
python --version 2>&1 || echo "python not found"
</trender>

## Debugging Methodology

1. Reproduce the bug
2. Identify error location
3. Trace execution flow
4. Understand root cause
5. Propose minimal fix
6. Verify fix works
```

**agent.json**:
```json
{
  "description": "Python debugging specialist",
  "profile": null
}
```

### Example Skill: Performance Profiling

**Create skill**:
```bash
cat > .kollabor-cli/agents/python-debugger/performance-profiling.md << 'EOF'
<!-- Description: Adds performance profiling capabilities -->

# Performance Profiling

This skill enables systematic performance profiling.

## Methodology

1. Identify performance bottleneck
2. Use cProfile for function-level profiling
3. Use memory_profiler for memory analysis
4. Analyze hot spots
5. Propose optimizations
6. Verify improvements

## Commands

Profile function execution:
<terminal>python -m cProfile -o profile.stats script.py</terminal>

View top functions by time:
<terminal>python -c "import pstats; p=pstats.Stats('profile.stats'); p.sort_stats('cumulative'); p.print_stats(20)"</terminal>

Memory profile:
<terminal>python -m memory_profiler script.py</terminal>
EOF
```

### Example: Parallel Agent Workflow

**Main agent spawns researchers**:
```xml
<agent>
  <researcher-1>
    <task>
    objective: Analyze component A

    context:
    - Component A handles user authentication
    - We need to identify security vulnerabilities

    success: Report all security findings
    </task>
    <files>
      <file>src/auth.py</file>
    </files>
  </researcher-1>
  <researcher-2>
    <task>
    objective: Analyze component B

    context:
    - Component B handles data storage
    - We need to identify performance bottlenecks

    success: Report all performance issues
    </task>
    <files>
      <file>src/storage.py</file>
    </files>
  </researcher-2>
</agent>
```

**Monitor progress**:
```xml
<status></status>
```

**Capture specific agent output**:
```xml
<capture>researcher-1 100</capture>
```

**Stop agent when done**:
```xml
<stop>researcher-1</stop>
```

---

## API Reference

### AgentManager

```python
from kollabor.llm.agent_manager import AgentManager

agent_manager = AgentManager(config)

# Agent discovery
agents = agent_manager.list_agents()
agent = agent_manager.get_agent("coder")

# Active agent
agent = agent_manager.get_active_agent()
agent_manager.set_active_agent("coder")
name = agent_manager.active_agent_name

# Agent creation
agent = agent_manager.create_agent(
    name="new-agent",
    description="Description",
    system_prompt="prompt content"
)

# Agent deletion
success = agent_manager.delete_agent("old-agent")

# Skill management
skills = agent_manager.list_skills("coder")
agent_manager.load_skill("code-review", "coder")
agent_manager.unload_skill("code-review", "coder")

# Default skills
success, is_default = agent_manager.toggle_default_skill(
    "code-review",
    agent_name="coder",
    scope="project"
)

# System prompt
prompt = agent_manager.get_system_prompt()

# Refresh discovery
agent_manager.refresh()
```

### Agent

```python
from kollabor.llm.agent_manager import Agent

agent = Agent.from_directory(agent_dir)

# Properties
agent.name              # Agent name
agent.description       # Description
agent.system_prompt     # Base prompt
agent.skills           # Dict of available skills
agent.active_skills     # List of active skill names
agent.profile          # Preferred profile

# Methods
prompt = agent.get_full_system_prompt()  # With active skills
agent.load_skill("skill-name")
agent.unload_skill("skill-name")
skills = agent.list_skills()
skill = agent.get_skill("skill-name")
```

### Skill

```python
from kollabor.llm.agent_manager import Skill

skill = Skill.from_file(skill_file)

# Properties
skill.name            # Skill name (filename without extension)
skill.description     # Extracted from HTML comment
skill.content         # Full content
skill.file_path       # Path to file

# Methods
skill_dict = skill.to_dict()
```

---

## Troubleshooting

### Agent Not Discovered

**Problem**: New agent not showing up

**Solution**:
1. Verify directory structure: `.kollabor-cli/agents/my-name/`
2. Check `system_prompt.md` exists
3. Refresh agent discovery: Restart application or call `agent_manager.refresh()`
4. Check logs for errors during discovery

### Skills Not Loading

**Problem**: Skill load fails

**Solution**:
1. Verify skill file exists in agent directory
2. Check skill file is valid markdown
3. Check skill name (without `.md` extension)
4. Review logs for specific error

### Agent Orchestrator Not Working

**Problem**: XML commands not executing

**Solution**:
1. Verify plugin is enabled in config
2. Check `enable_mode` setting ("startup" or "keyword")
3. For keyword mode, ensure trigger keywords present in user input
4. Verify tmux is installed: `tmux -V`
5. Check plugin logs for errors

### Prompt Rendering Issues

**Problem**: `<trender>` commands not executing

**Solution**:
1. Verify command syntax: `<trender>command</trender>`
2. Check command works in shell
3. Avoid commands with special output (escape codes, interactive prompts)
4. Check logs for rendering errors

### Include Paths Not Found

**Problem**: `<trender type="include">` fails

**Solution**:
1. Verify path is relative to agent directory
2. Check file exists at specified path
3. Ensure no typos in path
4. Use forward slashes (even on Windows)

---

## Resources

### Related Documentation

- [FEATURES.md](FEATURES.md) - Complete feature list
- [README.md](README.md) - Project overview
- [CONFIGURATION.md](CONFIGURATION.md) - Configuration reference

### Code References

- `kollabor/llm/agent_manager.py` - Agent management implementation
- `plugins/agent_orchestrator/` - Parallel agent execution
- `kollabor/utils/prompt_renderer.py` - Prompt rendering
- `bundles/agents/` - Built-in agents and skills

### Agent Examples

- `bundles/agents/default/` - Modular agent with sections
- `bundles/agents/coder/` - Agent with multiple skills
- `bundles/agents/kollabor/` - Meta-agent for building agents

---

## Changelog

### v0.4.18
- Agent orchestrator with parallel sub-agent execution
- XML-based agent commands
- Activity monitoring and auto-completion
- Tmux-based session management

### v0.4.x
- Agent system with dynamic skill loading
- Local vs global agent discovery
- Prompt rendering with `<trender>` tags
- Modular system prompts with includes

---

## Contributing

When adding new agents or skills:

1. **Follow Conventions**: Match existing agent structure
2. **Clear Purpose**: Document what the agent does
3. **Test Skills**: Ensure skills work independently
4. **Document**: Include descriptions in agent.json and skill headers
5. **Modular Design**: Use skills for reusability

Submit agents as PRs to the main repository for inclusion in global agents directory.
