# Custom Agent Development Guide

This guide covers how to create custom agents for specialized tasks in the multi-agent system.

## Overview

Custom agents extend the platform's capabilities by:

- Adding specialized expertise (new traditions, techniques)
- Implementing domain-specific logic
- Integrating with external tools and APIs
- Handling custom content types

## Agent Types

### 1. Domain Agents

Specialized in specific knowledge domains:

```typescript
interface DomainAgent {
  id: string;
  role: AgentRole;
  name: string;
  description: string;
  capabilities: string[];
  toolAccess: AgentToolAccess[];
  personality: AgentPersonality;
}
```

### 2. System Agents

Handle infrastructure and coordination:

```typescript
interface SystemAgent {
  name: string;
  capabilities: string[];
  autonomyLevel: 'full' | 'supervised' | 'restricted';
  status: AgentStatus;
}
```

### 3. Workflow Agents

Execute multi-step processes:

```typescript
interface WorkflowAgent {
  id: string;
  workflow: WorkflowDefinition;
  state: WorkflowState;
}
```

## Creating a Custom Agent

### Step 1: Define the Agent Role

```typescript
// Add new role to the type definition
export type AgentRole =
  | 'librarian'
  | 'curator'
  // ... existing roles
  | 'yoga_instructor'      // Your new role
  | 'breathwork_guide';    // Another new role
```

### Step 2: Define Capabilities

```typescript
const yogaInstructorCapabilities = [
  'yoga_sequence_design',
  'pose_instruction',
  'alignment_correction',
  'breath_coordination',
  'modification_suggestions'
];
```

### Step 3: Configure Tool Access

```typescript
const yogaInstructorTools: AgentToolAccess[] = [
  {
    toolName: 'search',
    permissions: ['search.yoga', 'search.anatomy'],
    rateLimit: { calls: 100, period: 'minute' }
  },
  {
    toolName: 'tts',
    permissions: ['tts.generate'],
    rateLimit: { calls: 50, period: 'minute' }
  }
];
```

### Step 4: Define Personality

```typescript
const yogaInstructorPersonality: AgentPersonality = {
  tone: 'encouraging',
  style: 'instructive',
  expertise: [
    'hatha_yoga',
    'vinyasa_flow',
    'pranayama',
    'anatomy',
    'alignment'
  ]
};
```

### Step 5: Register the Agent

```typescript
import { DomainAgentRegistry } from '../domain-agents.js';

const registry = new DomainAgentRegistry();

registry.registerAgent({
  role: 'yoga_instructor',
  name: 'Yoga Instructor',
  description: 'Guides yoga practice with precise instruction and modifications',
  capabilities: yogaInstructorCapabilities,
  toolAccess: yogaInstructorTools,
  personality: yogaInstructorPersonality
});
```

## Complete Agent Implementation

### Example: Breathwork Guide Agent

```typescript
// src/agents/breathwork-guide-agent.ts

import { DomainAgentRegistry, type DomainAgent, type AgentTask } from '../domain-agents.js';
import { AgentExecutor } from '../agent-executor.js';

export interface BreathworkSession {
  technique: BreathworkTechnique;
  duration: number;
  phases: BreathPhase[];
  instructions: string[];
}

export type BreathworkTechnique =
  | 'box_breathing'
  | '4_7_8_breathing'
  | 'alternate_nostril'
  | 'breath_of_fire'
  | 'holotropic';

export interface BreathPhase {
  type: 'inhale' | 'hold' | 'exhale' | 'pause';
  duration: number;
  instruction: string;
}

export class BreathworkGuideAgent {
  private agent: DomainAgent;
  private executor: AgentExecutor;

  constructor(registry: DomainAgentRegistry, executor: AgentExecutor) {
    this.executor = executor;

    // Register the agent
    this.agent = registry.registerAgent({
      role: 'breathwork_guide' as any,
      name: 'Breathwork Guide',
      description: 'Expert in pranayama and modern breathwork techniques',
      capabilities: [
        'breathwork_design',
        'breath_instruction',
        'timing_coordination',
        'safety_guidance'
      ],
      toolAccess: [
        {
          toolName: 'calc',
          permissions: ['calc.timing'],
          rateLimit: { calls: 200, period: 'minute' }
        },
        {
          toolName: 'tts',
          permissions: ['tts.generate'],
          rateLimit: { calls: 50, period: 'minute' }
        }
      ],
      personality: {
        tone: 'calm',
        style: 'precise',
        expertise: [
          'pranayama',
          'breathwork',
          'respiratory_physiology',
          'meditation'
        ]
      }
    });
  }

  async createSession(
    technique: BreathworkTechnique,
    duration: number
  ): Promise<BreathworkSession> {
    const task: AgentTask = {
      id: crypto.randomUUID(),
      agentId: this.agent.id,
      type: 'create_breathwork_session',
      input: { technique, duration },
      status: 'pending',
      toolsUsed: []
    };

    const result = await this.executor.execute(this.agent, task);
    return result.data as BreathworkSession;
  }

  async generateInstructions(phase: BreathPhase): Promise<string> {
    const task: AgentTask = {
      id: crypto.randomUUID(),
      agentId: this.agent.id,
      type: 'generate_breath_instruction',
      input: { phase },
      status: 'pending',
      toolsUsed: []
    };

    const result = await this.executor.execute(this.agent, task);
    return result.data as string;
  }

  getBreathingPattern(technique: BreathworkTechnique): BreathPhase[] {
    switch (technique) {
      case 'box_breathing':
        return [
          { type: 'inhale', duration: 4, instruction: 'Breathe in slowly' },
          { type: 'hold', duration: 4, instruction: 'Hold your breath' },
          { type: 'exhale', duration: 4, instruction: 'Exhale slowly' },
          { type: 'pause', duration: 4, instruction: 'Rest before next breath' }
        ];

      case '4_7_8_breathing':
        return [
          { type: 'inhale', duration: 4, instruction: 'Inhale through your nose' },
          { type: 'hold', duration: 7, instruction: 'Hold your breath' },
          { type: 'exhale', duration: 8, instruction: 'Exhale through your mouth' }
        ];

      case 'alternate_nostril':
        return [
          { type: 'inhale', duration: 4, instruction: 'Inhale through left nostril' },
          { type: 'hold', duration: 2, instruction: 'Brief pause' },
          { type: 'exhale', duration: 4, instruction: 'Exhale through right nostril' },
          { type: 'inhale', duration: 4, instruction: 'Inhale through right nostril' },
          { type: 'hold', duration: 2, instruction: 'Brief pause' },
          { type: 'exhale', duration: 4, instruction: 'Exhale through left nostril' }
        ];

      default:
        return [
          { type: 'inhale', duration: 4, instruction: 'Breathe in' },
          { type: 'exhale', duration: 4, instruction: 'Breathe out' }
        ];
    }
  }
}
```

### Example: Tradition Expert Agent

```typescript
// src/agents/tradition-expert-agent.ts

import { DomainAgentRegistry, type DomainAgent } from '../domain-agents.js';

export type TraditionType =
  | 'theravada'
  | 'mahayana'
  | 'vajrayana'
  | 'zen'
  | 'advaita'
  | 'bhakti'
  | 'kashmir_shaivism'
  | 'sufi'
  | 'christian_mysticism'
  | 'taoist';

export interface TraditionValidation {
  valid: boolean;
  score: number;
  issues: TraditionIssue[];
  suggestions: string[];
  terminology: TerminologyCheck[];
}

export interface TraditionIssue {
  type: 'terminology' | 'concept' | 'practice' | 'attribution';
  severity: 'minor' | 'moderate' | 'major';
  description: string;
  location?: string;
  suggestion?: string;
}

export interface TerminologyCheck {
  term: string;
  correct: boolean;
  tradition: TraditionType;
  suggestion?: string;
}

export class TraditionExpertAgent {
  private agents: Map<TraditionType, DomainAgent> = new Map();

  constructor(registry: DomainAgentRegistry) {
    // Create specialized agents for each tradition
    this.createTraditionAgent(registry, 'theravada', {
      name: 'Theravada Scholar',
      expertise: ['pali_canon', 'vipassana', 'abhidhamma', 'monastic_rules']
    });

    this.createTraditionAgent(registry, 'zen', {
      name: 'Zen Master',
      expertise: ['koans', 'zazen', 'soto', 'rinzai', 'chan_history']
    });

    this.createTraditionAgent(registry, 'advaita', {
      name: 'Advaita Vedanta Scholar',
      expertise: ['upanishads', 'brahman', 'self_inquiry', 'shankara']
    });

    // Add more traditions as needed
  }

  private createTraditionAgent(
    registry: DomainAgentRegistry,
    tradition: TraditionType,
    config: { name: string; expertise: string[] }
  ): void {
    const agent = registry.registerAgent({
      role: 'scholar',
      name: config.name,
      description: `Expert in ${tradition} tradition and practices`,
      capabilities: [
        'tradition_validation',
        'terminology_check',
        'concept_verification',
        'citation_generation'
      ],
      toolAccess: [
        {
          toolName: 'kg_query',
          permissions: ['kg.read', `kg.${tradition}`],
          rateLimit: { calls: 100, period: 'minute' }
        },
        {
          toolName: 'search',
          permissions: ['search.academic', `search.${tradition}`],
          rateLimit: { calls: 50, period: 'minute' }
        }
      ],
      personality: {
        tone: 'scholarly',
        style: 'precise',
        expertise: config.expertise
      }
    });

    this.agents.set(tradition, agent);
  }

  async validateContent(
    content: string,
    tradition: TraditionType
  ): Promise<TraditionValidation> {
    const agent = this.agents.get(tradition);
    if (!agent) {
      throw new Error(`No expert available for tradition: ${tradition}`);
    }

    // Perform validation using the specialized agent
    const terminologyChecks = await this.checkTerminology(content, tradition);
    const conceptChecks = await this.checkConcepts(content, tradition);

    const issues: TraditionIssue[] = [
      ...terminologyChecks.filter(t => !t.correct).map(t => ({
        type: 'terminology' as const,
        severity: 'minor' as const,
        description: `Incorrect term: ${t.term}`,
        suggestion: t.suggestion
      })),
      ...conceptChecks
    ];

    const score = this.calculateScore(issues);

    return {
      valid: score >= 0.85,
      score,
      issues,
      suggestions: this.generateSuggestions(issues),
      terminology: terminologyChecks
    };
  }

  private async checkTerminology(
    content: string,
    tradition: TraditionType
  ): Promise<TerminologyCheck[]> {
    // Implementation would use knowledge graph and LLM
    return [];
  }

  private async checkConcepts(
    content: string,
    tradition: TraditionType
  ): Promise<TraditionIssue[]> {
    // Implementation would verify concepts are accurate
    return [];
  }

  private calculateScore(issues: TraditionIssue[]): number {
    const deductions = {
      minor: 0.02,
      moderate: 0.05,
      major: 0.15
    };

    let score = 1.0;
    for (const issue of issues) {
      score -= deductions[issue.severity];
    }

    return Math.max(0, score);
  }

  private generateSuggestions(issues: TraditionIssue[]): string[] {
    return issues
      .filter(i => i.suggestion)
      .map(i => i.suggestion!);
  }
}
```

## Agent Communication

### Message Passing

```typescript
interface AgentMessage {
  id: string;
  from: string;
  to: string;
  type: 'request' | 'response' | 'broadcast';
  payload: unknown;
  timestamp: Date;
}

class AgentMessageBus {
  private subscribers: Map<string, Set<(msg: AgentMessage) => void>> = new Map();

  subscribe(agentId: string, handler: (msg: AgentMessage) => void): void {
    if (!this.subscribers.has(agentId)) {
      this.subscribers.set(agentId, new Set());
    }
    this.subscribers.get(agentId)!.add(handler);
  }

  send(message: AgentMessage): void {
    const handlers = this.subscribers.get(message.to);
    if (handlers) {
      handlers.forEach(handler => handler(message));
    }
  }

  broadcast(fromAgent: string, payload: unknown): void {
    const message: AgentMessage = {
      id: crypto.randomUUID(),
      from: fromAgent,
      to: '*',
      type: 'broadcast',
      payload,
      timestamp: new Date()
    };

    this.subscribers.forEach((handlers) => {
      handlers.forEach(handler => handler(message));
    });
  }
}
```

### Request-Response Pattern

```typescript
class AgentCoordinator {
  async request(
    fromAgent: string,
    toAgent: string,
    payload: unknown,
    timeout: number = 30000
  ): Promise<unknown> {
    return new Promise((resolve, reject) => {
      const messageId = crypto.randomUUID();
      const timer = setTimeout(() => reject(new Error('Timeout')), timeout);

      const handler = (response: AgentMessage) => {
        if (response.id === messageId && response.type === 'response') {
          clearTimeout(timer);
          resolve(response.payload);
        }
      };

      this.messageBus.subscribe(fromAgent, handler);
      this.messageBus.send({
        id: messageId,
        from: fromAgent,
        to: toAgent,
        type: 'request',
        payload,
        timestamp: new Date()
      });
    });
  }
}
```

## Testing Custom Agents

### Unit Tests

```typescript
import { describe, it, expect, beforeEach } from '@jest/globals';
import { BreathworkGuideAgent } from '../breathwork-guide-agent.js';

describe('BreathworkGuideAgent', () => {
  let agent: BreathworkGuideAgent;

  beforeEach(() => {
    const registry = new DomainAgentRegistry();
    const executor = new AgentExecutor();
    agent = new BreathworkGuideAgent(registry, executor);
  });

  describe('getBreathingPattern', () => {
    it('should return correct box breathing pattern', () => {
      const pattern = agent.getBreathingPattern('box_breathing');

      expect(pattern).toHaveLength(4);
      expect(pattern[0].type).toBe('inhale');
      expect(pattern[0].duration).toBe(4);
    });

    it('should return correct 4-7-8 pattern', () => {
      const pattern = agent.getBreathingPattern('4_7_8_breathing');

      expect(pattern).toHaveLength(3);
      expect(pattern[0].duration).toBe(4);
      expect(pattern[1].duration).toBe(7);
      expect(pattern[2].duration).toBe(8);
    });
  });

  describe('createSession', () => {
    it('should create a valid breathwork session', async () => {
      const session = await agent.createSession('box_breathing', 300);

      expect(session.technique).toBe('box_breathing');
      expect(session.duration).toBe(300);
      expect(session.phases.length).toBeGreaterThan(0);
    });
  });
});
```

### Integration Tests

```typescript
describe('Agent Integration', () => {
  it('should coordinate between multiple agents', async () => {
    const coordinator = new AgentCoordinator();

    // Create a meditation that requires multiple agents
    const result = await coordinator.executeWorkflow('meditation-with-breathwork', [
      {
        name: 'create-breathwork',
        capabilities: ['breathwork_design'],
        action: 'create_session',
        params: { technique: 'box_breathing', duration: 120 }
      },
      {
        name: 'generate-script',
        capabilities: ['content-creation'],
        action: 'generate_meditation_script',
        params: { includeBreathwork: true }
      },
      {
        name: 'validate-tradition',
        capabilities: ['tradition_validation'],
        action: 'validate',
        params: { tradition: 'buddhist' }
      }
    ]);

    expect(result.status).toBe('completed');
    expect(result.results).toHaveLength(3);
  });
});
```

## Agent Lifecycle

### Initialization

```typescript
class AgentLifecycle {
  async initialize(agent: DomainAgent): Promise<void> {
    // Load agent configuration
    await this.loadConfig(agent);

    // Connect to required tools
    await this.connectTools(agent);

    // Warm up LLM context
    await this.warmUp(agent);

    // Mark as ready
    agent.status = 'idle';
  }

  private async warmUp(agent: DomainAgent): Promise<void> {
    // Send a simple prompt to warm up the context
    await this.executor.execute(agent, {
      id: 'warmup',
      agentId: agent.id,
      type: 'warmup',
      input: { message: 'Initialize' },
      status: 'pending',
      toolsUsed: []
    });
  }
}
```

### Shutdown

```typescript
class AgentLifecycle {
  async shutdown(agent: DomainAgent): Promise<void> {
    // Complete pending tasks
    await this.drainTaskQueue(agent);

    // Disconnect tools
    await this.disconnectTools(agent);

    // Save state
    await this.saveState(agent);

    // Mark as offline
    agent.status = 'offline';
  }
}
```

## Best Practices

### 1. Single Responsibility

Each agent should have a focused purpose:

```typescript
// Good: Focused agent
const breathworkAgent = {
  capabilities: ['breathwork_design', 'breath_instruction']
};

// Avoid: Jack of all trades
const everythingAgent = {
  capabilities: ['meditation', 'yoga', 'breathwork', 'cooking', 'gardening']
};
```

### 2. Clear Capability Naming

```typescript
// Good: Specific, action-oriented
capabilities: ['generate_meditation_script', 'validate_tradition_accuracy']

// Avoid: Vague, overlapping
capabilities: ['content', 'text', 'general']
```

### 3. Appropriate Tool Access

```typescript
// Good: Minimal required permissions
toolAccess: [
  { toolName: 'search', permissions: ['search.yoga'] }
]

// Avoid: Overly broad permissions
toolAccess: [
  { toolName: 'search', permissions: ['*'] }
]
```

### 4. Error Handling

```typescript
class CustomAgent {
  async execute(task: AgentTask): Promise<TaskResult> {
    try {
      return await this.performTask(task);
    } catch (error) {
      // Log error
      console.error(`Agent ${this.agent.id} failed: ${error.message}`);

      // Update metrics
      this.agent.metrics.tasksFailed++;

      // Return structured error
      return {
        success: false,
        error: {
          code: 'EXECUTION_FAILED',
          message: error.message,
          recoverable: this.isRecoverable(error)
        }
      };
    }
  }
}
```

## Related Resources

- [Multi-Agent Architecture Guide](./multi-agent-architecture.md)
- [Prompt Engineering for Meditation](./prompt-engineering-meditation.md)
- [Content Generation API](./content-generation-api.md)
