> ## Documentation Index
> Fetch the complete documentation index at: https://docs.heylua.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# API Overview

> Complete API reference for building Lua AI skills

## Available APIs

Lua CLI provides a comprehensive set of APIs for building AI agents:

<CardGroup cols={2}>
  <Card title="Core Classes" icon="puzzle-piece">
    **LuaAgent, LuaSkill, LuaTool** - Agent configuration and building blocks
  </Card>

  <Card title="Automation" icon="clock">
    **LuaJob, LuaWebhook** - Scheduled tasks and HTTP endpoints
  </Card>

  <Card title="Message Processing" icon="filter">
    **PreProcessor, PostProcessor** - Filter and format messages
  </Card>

  <Card title="External Tools" icon="plug">
    **LuaMCPServer** - Connect MCP servers for external tool integrations
  </Card>

  <Card title="Platform APIs" icon="server">
    **AI, Agents, User, Data, CDN, Products, Baskets, Orders, Jobs, Templates** - Built-in services
  </Card>

  <Card title="Environment" icon="key">
    **env()** - Secure configuration management
  </Card>
</CardGroup>

<Note>
  LuaAgent, LuaJob, LuaWebhook, PreProcessor, PostProcessor, and Jobs API for comprehensive agent development.
</Note>

## Installation

<CodeGroup>
  ```bash npm theme={null}
  npm install lua-cli zod
  ```

  ```bash yarn theme={null}
  yarn add lua-cli zod
  ```

  ```bash pnpm theme={null}
  pnpm add lua-cli zod
  ```
</CodeGroup>

<Note>
  `zod` is a peer dependency required for schema validation
</Note>

## Quick Start

### Import APIs

```typescript theme={null}
// Core classes
import { 
  LuaAgent, 
  LuaSkill, 
  LuaTool, 
  LuaWebhook, 
  LuaJob,
  LuaMCPServer,
  PreProcessor,
  PostProcessor
} from 'lua-cli';

// Platform APIs
import { AI, Agents, User, Data, CDN, Products, Baskets, Orders, Jobs, Templates } from 'lua-cli';

// Utilities
import { env } from 'lua-cli';

// Type definitions
import { BasketStatus, OrderStatus } from 'lua-cli';

// Schema validation
import { z } from 'zod';
```

### Create an Agent

```typescript theme={null}
import { LuaAgent, LuaSkill, LuaTool } from 'lua-cli';
import { z } from 'zod';

// Define a tool
class MyTool implements LuaTool {
  name = "my_tool";
  description = "What the tool does";
  inputSchema = z.object({
    param: z.string()
  });

  async execute(input: any) {
    return { result: "success" };
  }
}

// Create a skill
const skill = new LuaSkill({
  name: "my-skill",
  description: "My custom skill",
  context: "When to use this skill and its tools",
  tools: [new MyTool()]
});

// Create agent
export const agent = new LuaAgent({
  name: "my-agent",
  persona: "You are a helpful assistant...",
  skills: [skill]
});
```

## Core Classes

### Agent Configuration

<CardGroup cols={2}>
  <Card title="LuaAgent" icon="robot" href="/api/luaagent">
    Unified agent configuration

    ```typescript theme={null}
    new LuaAgent({
      name: "my-agent",
      persona: "...",
      skills: [...],
      webhooks: [...],
      jobs: [...]
    })
    ```
  </Card>
</CardGroup>

### Building Blocks

<CardGroup cols={2}>
  <Card title="LuaSkill" icon="puzzle-piece" href="/api/luaskill">
    Collection of related tools

    ```typescript theme={null}
    new LuaSkill({
      name: "skill-name",
      tools: [...]
    })
    ```
  </Card>

  <Card title="LuaTool" icon="wrench" href="/api/luatool">
    Individual function the AI can call

    ```typescript theme={null}
    class MyTool implements LuaTool {
      name = "tool_name"
      execute(input) { ... }
    }
    ```
  </Card>
</CardGroup>

### Automation

<CardGroup cols={2}>
  <Card title="LuaWebhook" icon="webhook" href="/api/luawebhook">
    HTTP endpoints for external events

    ```typescript theme={null}
    new LuaWebhook({
      name: "payment-webhook",
      execute: async (event) => { ... }
    })
    ```
  </Card>

  <Card title="LuaJob" icon="clock" href="/api/luajob">
    Scheduled tasks

    ```typescript theme={null}
    new LuaJob({
      name: "daily-report",
      schedule: { type: "cron", pattern: "0 9 * * *" },
      execute: async (job) => { ... }
    })
    ```
  </Card>
</CardGroup>

### Message Processing

<CardGroup cols={2}>
  <Card title="PreProcessor" icon="filter" href="/api/preprocessor">
    Filter messages before agent

    ```typescript theme={null}
    new PreProcessor({
      name: "profanity-filter",
      execute: async (message, user) => { ... }
    })
    ```
  </Card>

  <Card title="PostProcessor" icon="paper-plane" href="/api/postprocessor">
    Format responses after agent

    ```typescript theme={null}
    new PostProcessor({
      name: "add-disclaimer",
      execute: async (user, message, response, channel) => { ... }
    })
    ```
  </Card>
</CardGroup>

## Platform APIs

### AI API

**New!** Generate AI responses with custom context in your tools:

```typescript theme={null}
import { AI } from 'lua-cli';

const response = await AI.generate(
  'You are a helpful sales assistant.',
  [{ type: 'text', text: 'What products do you recommend?' }]
);
```

**Use cases:**

* Product descriptions
* Image analysis
* Content summarization
* Translation
* Recommendations
* Document Q\&A

<Card title="Full Documentation" href="/api/ai" />

### Agents API

**New!** Invoke another agent from within your tool, webhook, job, or processor:

```typescript theme={null}
import { Agents } from 'lua-cli';

// Simplified — returns plain text
const reply = await Agents.invoke('support-agent', 'What is the refund policy?');

// Full options — returns structured output
const result = await Agents.invoke('legal-agent', {
  prompt: 'Review this clause.',
  threadId: 'contract-456',
});
console.log(result.text, result.usage);
```

**Use cases:**

* Route requests to specialist agents
* Build multi-agent pipelines
* Delegate from webhooks/jobs to conversational agents

<Card title="Full Documentation" href="/api/agents" />

### User API

Access user information:

```typescript theme={null}
import { User } from 'lua-cli';

// Get current user (from conversation context)
const user = await User.get();

// Get specific user by ID (useful in webhooks/jobs)
const specificUser = await User.get(userId);

// Direct property access
console.log(user.name);
console.log(user.email);
```

**Use cases:**

* Get current user in tools
* Get specific user in webhooks (payment notifications)
* Send messages to specific users in jobs
* Update user profiles

<Card title="Full Documentation" href="/api/user" />

### Data API

Custom data storage with vector search:

```typescript theme={null}
import { Data } from 'lua-cli';

// Create
await Data.create('collection', data, searchText);

// Search semantically
const results = await Data.search('collection', 'query', 10, 0.7);

// Get/Update/Delete
await Data.get('collection', filter);
await Data.update('collection', id, data);
await Data.delete('collection', id);
```

<Card title="Full Documentation" href="/api/data" />

### CDN API

Upload and retrieve files from the CDN:

```typescript theme={null}
import { CDN } from 'lua-cli';

// Upload a file
const file = new File([buffer], 'image.png', { type: 'image/png' });
const fileId = await CDN.upload(file);

// Get file by ID
const retrievedFile = await CDN.get(fileId);
console.log(retrievedFile.name, retrievedFile.type);
```

**Use cases:**

* Store user uploads
* Image storage for AI analysis
* Document management
* Asset management

<Card title="Full Documentation" href="/api/cdn" />

### Products API

E-commerce product catalog:

```typescript theme={null}
import { Products } from 'lua-cli';

// Search
const products = await Products.search('laptop');

// CRUD
await Products.create({ name, price });
await Products.update({ price }, id);
await Products.getById(id);
await Products.delete(id);
```

<Card title="Full Documentation" href="/api/products" />

### Baskets API

Shopping cart management:

```typescript theme={null}
import { Baskets, BasketStatus } from 'lua-cli';

// Create basket
const basket = await Baskets.create({ currency: 'USD' });

// Add items
await Baskets.addItem(basket.id, {
  id: productId,
  price: 29.99,
  quantity: 2
});

// Checkout
const order = await Baskets.placeOrder(orderData, basket.id);
```

<Card title="Full Documentation" href="/api/baskets" />

### Orders API

Order processing and tracking:

```typescript theme={null}
import { Orders, OrderStatus } from 'lua-cli';

// Create order
const order = await Orders.create({
  basketId,
  data: { shippingAddress, paymentMethod }
});

// Update status
await Orders.updateStatus(OrderStatus.FULFILLED, orderId);
```

<Card title="Full Documentation" href="/api/orders" />

### Jobs API

Dynamically create scheduled tasks from tools:

```typescript theme={null}
import { Jobs } from 'lua-cli';

// Create a reminder job
const job = await Jobs.create({
  name: 'user-reminder',
  metadata: { message: 'Meeting in 10 minutes' },
  schedule: {
    type: 'once',
    executeAt: new Date(Date.now() + 600000)
  },
  execute: async (jobInstance) => {
    const user = await jobInstance.user();
    await user.send([{
      type: 'text',
      text: jobInstance.metadata.message
    }]);
  }
});
```

<Card title="Full Documentation" href="/api/jobs" />

### Templates API

Send template messages across different channels:

```typescript theme={null}
import { Templates } from 'lua-cli';

// List WhatsApp templates
const result = await Templates.whatsapp.list(channelId);

// Send template message
await Templates.whatsapp.send(channelId, templateId, {
  phoneNumbers: ['+447551166594'],
  values: {
    body: { name: 'John', order_number: '12345' }
  }
});
```

**Supported template types:**

* `Templates.whatsapp` - WhatsApp Business templates

<Card title="Full Documentation" href="/api/templates" />

## Environment Variables

Secure configuration management:

```typescript theme={null}
import { env } from 'lua-cli';

const apiKey = env('EXTERNAL_API_KEY');
const baseUrl = env('API_BASE_URL') || 'https://default.com';
```

<Card title="Full Documentation" href="/api/environment" />

## Type Definitions

All APIs are fully typed for TypeScript:

```typescript theme={null}
import { 
  LuaSkill, 
  LuaTool, 
  BasketStatus, 
  OrderStatus 
} from 'lua-cli';

// Autocomplete and type checking work everywhere
const user = await User.get();  // user is typed
const products = await Products.get(); // products is typed
```

## Common Patterns

### External API Integration

```typescript theme={null}
export class WeatherTool implements LuaTool {
  name = "get_weather";
  description = "Get current weather";
  inputSchema = z.object({ city: z.string() });

  async execute(input: any) {
    const response = await fetch(
      `https://api.weather.com?city=${input.city}`
    );
    return await response.json();
  }
}
```

### Using Platform APIs

```typescript theme={null}
export class ShoppingTool implements LuaTool {
  async execute(input: any) {
    // Search products
    const products = await Products.search(input.query);
    
    // Create basket
    const basket = await Baskets.create({ currency: 'USD' });
    
    // Add item
    await Baskets.addItem(basket.id, {
      id: products.products[0].id,
      price: products.products[0].price,
      quantity: 1
    });
    
    return { basketId: basket.id };
  }
}
```

### Custom Data with Search

```typescript theme={null}
export class CreateNoteTool implements LuaTool {
  async execute(input: any) {
    // Create with search indexing
    const note = await Data.create('notes', {
      title: input.title,
      content: input.content
    }, `${input.title} ${input.content}`);
    
    return { noteId: note.id };
  }
}

export class SearchNotesTool implements LuaTool {
  async execute(input: any) {
    // Semantic search
    const results = await Data.search(
      'notes',
      input.query,
      10,
      0.7
    );
    
    return {
      notes: results.map(entry => ({
        id: entry.id,
        title: entry.title,
        content: entry.content,
        relevance: entry.score
      }))
    };
  }
}
```

## API Reference Pages

### Core Classes

<CardGroup cols={3}>
  <Card title="LuaAgent" href="/api/luaagent" icon="robot">
    Agent configuration
  </Card>

  <Card title="LuaSkill" href="/api/luaskill" icon="puzzle-piece">
    Skill class API
  </Card>

  <Card title="LuaTool" href="/api/luatool" icon="wrench">
    Tool interface
  </Card>

  <Card title="LuaWebhook" href="/api/luawebhook" icon="webhook">
    HTTP webhooks
  </Card>

  <Card title="LuaJob" href="/api/luajob" icon="clock">
    Scheduled tasks
  </Card>

  <Card title="LuaMCPServer" href="/api/luamcpserver" icon="plug">
    MCP external tools
  </Card>

  <Card title="PreProcessor" href="/api/preprocessor" icon="filter">
    Message filtering
  </Card>

  <Card title="PostProcessor" href="/api/postprocessor" icon="paper-plane">
    Response formatting
  </Card>

  <Card title="defineDevice" href="/api/device-definition" icon="microchip">
    Server-side device + trigger definitions
  </Card>

  <Card title="LuaVoice" href="/api/voice" icon="microphone">
    Voice agent definition
  </Card>
</CardGroup>

### Runtime APIs

<CardGroup cols={3}>
  <Card title="Lua" href="/api/lua" icon="moon">
    Request context API
  </Card>

  <Card title="AI" href="/api/ai" icon="brain">
    AI generation API
  </Card>

  <Card title="Agents" href="/api/agents" icon="robot">
    Agent invocation API
  </Card>

  <Card title="User" href="/api/user" icon="user">
    User data API
  </Card>

  <Card title="Data" href="/api/data" icon="database">
    Custom data API
  </Card>

  <Card title="CDN" href="/api/cdn" icon="cloud">
    File storage API
  </Card>

  <Card title="Products" href="/api/products" icon="box">
    Products API
  </Card>

  <Card title="Baskets" href="/api/baskets" icon="cart-shopping">
    Baskets API
  </Card>

  <Card title="Orders" href="/api/orders" icon="receipt">
    Orders API
  </Card>

  <Card title="Jobs" href="/api/jobs" icon="plus">
    Jobs API
  </Card>

  <Card title="Templates" href="/api/templates" icon="message">
    Template messaging
  </Card>
</CardGroup>

### Voice

<CardGroup cols={3}>
  <Card title="LuaVoice" href="/api/voice" icon="microphone">
    Define voices in code
  </Card>

  <Card title="Voice Plugins" href="/api/voice-plugins" icon="puzzle-piece">
    Deepgram, ElevenLabs, OpenAI, Google, xAI
  </Card>
</CardGroup>

### Utilities

<CardGroup cols={3}>
  <Card title="Environment" href="/api/environment" icon="key">
    Environment utilities
  </Card>
</CardGroup>

## Best Practices

<AccordionGroup>
  <Accordion title="Use TypeScript">
    All APIs are fully typed. Use TypeScript for:

    * Autocomplete
    * Type checking
    * Better IDE support
  </Accordion>

  <Accordion title="Validate Inputs">
    Always use Zod schemas for input validation:

    ```typescript theme={null}
    inputSchema = z.object({
      email: z.string().email(),
      age: z.number().min(0)
    });
    ```
  </Accordion>

  <Accordion title="Handle Errors">
    Implement proper error handling:

    ```typescript theme={null}
    try {
      const result = await api.call();
      return result;
    } catch (error) {
      throw new Error(`Operation failed: ${error.message}`);
    }
    ```
  </Accordion>

  <Accordion title="Use Environment Variables">
    Never hardcode secrets:

    ```typescript theme={null}
    const apiKey = env('API_KEY');
    if (!apiKey) {
      throw new Error('API_KEY not configured');
    }
    ```
  </Accordion>
</AccordionGroup>

## Next Steps

<Steps>
  <Step title="Explore Core Classes">
    Learn about [LuaSkill](/api/luaskill) and [LuaTool](/api/luatool)
  </Step>

  <Step title="Study Platform APIs">
    Explore [User](/api/user), [Data](/api/data), [Products](/api/products), etc.
  </Step>

  <Step title="See Examples">
    Check out [Tool Examples](/examples/overview) for working code
  </Step>

  <Step title="Build Something">
    Follow the [First Skill tutorial](/getting-started/first-skill)
  </Step>
</Steps>
