# LuaAgent

The `LuaAgent` class provides a unified, intuitive way to configure your entire AI agent in one place. It combines skills, webhooks, jobs, and processors into a single configuration object.

## Import

```typescript
import { LuaAgent } from 'lua-cli';
```

## Overview

`LuaAgent` is the recommended way to configure agents in v3.x. It provides:
- Single source of truth for all agent components
- Automatic synchronization with `lua.skill.yaml`
- Clear, organized configuration
- Better IDE support and type safety

## Type Definition

```typescript
interface LuaAgentConfig {
  /** Agent name (used for identification) */
  name: string;
  
  /** Agent persona - defines behavior and personality */
  persona: string;
  
  /** Array of skills (each with tools) */
  skills?: LuaSkill[];
  
  /** Array of webhooks */
  webhooks?: LuaWebhook[];
  
  /** Array of scheduled jobs */
  jobs?: LuaJob[];
  
  /** Array of preprocessors (run before messages reach the agent) */
  preProcessors?: PreProcessor[];
  
  /** Array of postprocessors (run after agent generates responses) */
  postProcessors?: PostProcessor[];
}

class LuaAgent {
  constructor(config: LuaAgentConfig);
}
```

## Properties

### `name` (required)
- **Type:** `string`
- **Description:** Agent identifier used for organization and logging
- **Example:** `'customer-support-agent'`, `'sales-assistant'`

### `persona` (required)
- **Type:** `string`
- **Description:** Defines the agent's personality, behavior, tone, and capabilities
- **Should Include:**
  - Who the agent is
  - What role they play
  - How they should communicate
  - What they can and cannot do
  - Any specific behaviors or rules

### `skills` (optional)
- **Type:** `LuaSkill[]`
- **Description:** Array of skills (tool collections) the agent can use
- **Default:** `[]`

### `webhooks` (optional)
- **Type:** `LuaWebhook[]`
- **Description:** HTTP endpoints that can receive external events
- **Default:** `[]`

### `jobs` (optional)
- **Type:** `LuaJob[]`
- **Description:** Scheduled tasks that run automatically
- **Default:** `[]`

### `preProcessors` (optional)
- **Type:** `PreProcessor[]`
- **Description:** Functions that process messages before they reach the agent
- **Default:** `[]`

### `postProcessors` (optional)
- **Type:** `PostProcessor[]`
- **Description:** Functions that process agent responses before sending to users
- **Default:** `[]`

## Basic Example

```typescript
import { LuaAgent, LuaSkill } from 'lua-cli';
import GetWeatherTool from './tools/GetWeatherTool';

const weatherSkill = new LuaSkill({
  name: 'weather-skill',
  description: 'Weather information',
  context: 'Use these tools to get weather data',
  tools: [new GetWeatherTool()]
});

export const agent = new LuaAgent({
  name: 'weather-assistant',
  persona: 'You are a friendly weather assistant. Provide weather information when asked.',
  skills: [weatherSkill]
});
```

## Complete Example

```typescript
import { 
  LuaAgent, 
  LuaSkill, 
  LuaWebhook, 
  LuaJob,
  PreProcessor,
  PostProcessor
} from 'lua-cli';

// Import your components
import { customerSupportSkill } from './skills/customer-support';
import { productSkill } from './skills/products';
import { orderSkill } from './skills/orders';
import paymentWebhook from './webhooks/payment';
import orderWebhook from './webhooks/order';
import dailyReportJob from './jobs/daily-report';
import cleanupJob from './jobs/cleanup';
import profanityFilter from './preprocessors/profanity-filter';
import addDisclaimer from './postprocessors/disclaimer';

export const agent = new LuaAgent({
  name: 'ecommerce-assistant',
  
  persona: `You are Emma, a helpful e-commerce assistant for Acme Store.
  
Your role:
- Help customers find products
- Assist with orders and cart management
- Answer product questions
- Process returns and exchanges

Communication style:
- Friendly and professional
- Patient and understanding
- Proactive with suggestions
- Clear and concise

Capabilities:
- Search product catalog
- Manage shopping carts
- Track orders
- Process payments
- Answer product questions

Limitations:
- Cannot ship orders manually
- Cannot modify pricing (suggest contacting manager)
- Cannot issue refunds over $100 (requires manager approval)
`,

  skills: [
    customerSupportSkill,
    productSkill,
    orderSkill
  ],

  webhooks: [
    paymentWebhook,
    orderWebhook
  ],

  jobs: [
    dailyReportJob,
    cleanupJob
  ],

  preProcessors: [
    profanityFilter
  ],

  postProcessors: [
    addDisclaimer
  ]
});
```

## Persona Best Practices

### ✅ DO

```typescript
persona: `You are Dr. Smith, a medical information assistant.

Role: Provide general health information and wellness tips.

Guidelines:
- Always clarify you're not a licensed doctor
- Recommend seeing professionals for serious concerns
- Use clear, non-technical language
- Be empathetic and supportive

Tone: Professional, caring, informative`
```

### ❌ DON'T

```typescript
// Too vague
persona: `You are helpful`

// Too robotic
persona: `I am an AI assistant that answers questions.`

// Missing boundaries
persona: `You can do anything the user asks.`
```

## Auto-Sync with YAML

When you run `lua compile`, the agent's persona and welcome message automatically sync to `lua.skill.yaml`:

```yaml
# lua.skill.yaml (auto-updated)
agent:
  agentId: your-agent-id
  persona: |
    You are Emma, a helpful e-commerce assistant...
```

When you run `lua init`, the YAML values sync to your `LuaAgent` in code.

## Multiple Skills Example

```typescript
import { LuaAgent, LuaSkill } from 'lua-cli';

// Organize tools by domain
const weatherSkill = new LuaSkill({
  name: 'weather-skill',
  description: 'Weather tools',
  context: 'Use for weather queries',
  tools: [getWeatherTool, getForecastTool]
});

const calculatorSkill = new LuaSkill({
  name: 'calculator-skill',
  description: 'Math tools',
  context: 'Use for calculations',
  tools: [addTool, multiplyTool, advancedMathTool]
});

const dataSkill = new LuaSkill({
  name: 'data-skill',
  description: 'Data management',
  context: 'Use for storing and retrieving user data',
  tools: [saveDataTool, queryDataTool]
});

export const agent = new LuaAgent({
  name: 'multi-purpose-assistant',
  persona: 'You are a versatile assistant that helps with weather, calculations, and data management.',
  skills: [weatherSkill, calculatorSkill, dataSkill]
});
```

## With All Components

```typescript
import { LuaAgent } from 'lua-cli';
import { skills } from './skills';
import { webhooks } from './webhooks';
import { jobs } from './jobs';
import { preProcessors } from './preprocessors';
import { postProcessors } from './postprocessors';

export const agent = new LuaAgent({
  name: 'enterprise-assistant',
  
  persona: `You are an enterprise-grade AI assistant.
  - Professional and efficient
  - Data-driven and accurate
  - Proactive with insights
  - Security and privacy conscious`,
  
  skills: skills,
  webhooks: webhooks,
  jobs: jobs,
  preProcessors: preProcessors,
  postProcessors: postProcessors
});
```

## Dynamic Configuration

```typescript
import { LuaAgent } from 'lua-cli';
import { env } from 'lua-cli/skill';

// Load configuration from environment
const agentName = env('AGENT_NAME') || 'default-agent';
const customPersona = env('AGENT_PERSONA') || 'You are a helpful assistant';

// Conditionally add components
const skills = [coreSkill];
if (env('ENABLE_ANALYTICS') === 'true') {
  skills.push(analyticsSkill);
}

export const agent = new LuaAgent({
  name: agentName,
  persona: customPersona,
  skills: skills,
  // Add webhooks only in production
  webhooks: env('NODE_ENV') === 'production' ? productionWebhooks : []
});
```

## Validation

The LuaAgent automatically validates:
- ✅ Name is provided and non-empty
- ✅ Persona is provided and non-empty
- ✅ All skills are valid LuaSkill instances
- ✅ All webhooks are valid LuaWebhook instances
- ✅ All jobs are valid LuaJob instances
- ✅ Tool names are unique across all skills
- ✅ Component names follow naming conventions

## Common Patterns

### Minimal Agent

```typescript
import { LuaAgent, LuaSkill } from 'lua-cli';
import greetingTool from './tools/greeting';

const simpleSkill = new LuaSkill({
  name: 'simple-skill',
  description: 'Basic functionality',
  context: 'Use for greetings',
  tools: [greetingTool]
});

export const agent = new LuaAgent({
  name: 'simple-bot',
  persona: 'You are a friendly chatbot that greets users.',
  skills: [simpleSkill]
});
```

### Customer Support Agent

```typescript
import { LuaAgent } from 'lua-cli';
import {
  ticketSkill,
  knowledgeBaseSkill,
  escalationWebhook,
  followUpJob
} from './support';

export const agent = new LuaAgent({
  name: 'support-agent',
  
  persona: `You are Alex, a customer support specialist.
  
Personality: Patient, empathetic, solution-oriented
Expertise: Product troubleshooting, order issues, returns
Approach: Listen carefully, ask clarifying questions, provide step-by-step help
Escalation: For complex issues, create a support ticket`,
  
  skills: [ticketSkill, knowledgeBaseSkill],
  webhooks: [escalationWebhook],
  jobs: [followUpJob]
});
```

### Data Analysis Agent

```typescript
import { LuaAgent } from 'lua-cli';
import {
  querySkill,
  visualizationSkill,
  exportSkill,
  dailyReportJob,
  anomalyDetectionJob
} from './analytics';

export const agent = new LuaAgent({
  name: 'analytics-agent',
  
  persona: `You are DataBot, an analytical AI assistant.
  
Expertise: SQL queries, data visualization, statistical analysis
Communication: Precise, data-driven, includes metrics and evidence
Capabilities:
- Query databases
- Generate visualizations
- Export reports
- Detect anomalies
- Provide insights

Always include:
- Data sources used
- Confidence levels
- Relevant metrics
- Actionable recommendations`,
  
  skills: [querySkill, visualizationSkill, exportSkill],
  jobs: [dailyReportJob, anomalyDetectionJob]
});
```

## Migration from v2.x

**Before (v2.x):**
```typescript
// Multiple exports
export const skill1 = new LuaSkill({...});
export const skill2 = new LuaSkill({...});
export const webhook1 = new LuaWebhook({...});
```

**After (v3.0.0):**
```typescript
// Single export with LuaAgent
export const agent = new LuaAgent({
  name: 'my-agent',
  persona: '...',
  skills: [skill1, skill2],
  webhooks: [webhook1]
});
```

## Related Documentation

- [LuaSkill](./LuaSkill.md) - Tool collections
- [LuaTool](./LuaTool.md) - Individual tools
- [LuaWebhook](./LuaWebhook.md) - HTTP endpoints
- [LuaJob](./LuaJob.md) - Scheduled tasks
- [PreProcessor](./PreProcessor.md) - Message preprocessing
- [PostProcessor](./PostProcessor.md) - Response postprocessing

## See Also

- [Quick Start Guide](../../template/QUICKSTART.md)
- [Template Examples](../../template/src/index.ts)
- [Persona Best Practices](../guides/PersonaBestPractices.md)

