# Platform API Reference

Complete reference for all lua-cli runtime APIs available in your tools, webhooks, jobs, and processors.

---

## Overview

When your code runs in the Lua platform (either in sandbox or production), you have access to powerful APIs for managing users, products, data, and more. These APIs are injected as globals into the VM execution environment.

**Import APIs in your code:**
```typescript
import { User, Products, Data, Jobs, AI } from 'lua-cli';
```

---

## Table of Contents

### Core Primitives
- [LuaAgent](#luaagent) - Agent configuration
- [LuaSkill](#luaskill) - Tool collections
- [LuaTool](#luatool) - Individual tools
- [LuaWebhook](#luawebhook) - HTTP endpoints
- [LuaJob](#luajob) - Scheduled tasks
- [PreProcessor](#preprocessor) - Message preprocessing
- [PostProcessor](#postprocessor) - Response postprocessing

### Runtime APIs
- [User API](#user-api) - User data management
- [Products API](#products-api) - Product catalog
- [Data API](#data-api) - Custom data storage
- [Baskets API](#baskets-api) - Shopping carts
- [Orders API](#orders-api) - Order management
- [Jobs API](#jobs-api) - Dynamic job creation
- [AI API](#ai-api) - AI text generation
- [Templates API](#templates-api) - WhatsApp templates
- [CDN API](#cdn-api) - File upload/download

### Utilities
- [env()](#env) - Environment variables
- [Lua Runtime](#lua-runtime) - Request context

---

## Quick Reference

### Import Everything

```typescript
import {
  // Core Primitives
  LuaAgent,
  LuaSkill,
  LuaTool,
  LuaWebhook,
  LuaJob,
  PreProcessor,
  PostProcessor,

  // Runtime APIs
  User,
  Products,
  Baskets,
  Orders,
  Data,
  Jobs,
  AI,
  Templates,
  CDN,

  // Utilities
  env,
  Lua
} from 'lua-cli';
```

### Common Patterns

**Create a Tool:**
```typescript
import { LuaTool } from 'lua-cli/skill';
import { z } from 'zod';

export default class MyTool implements LuaTool {
  name = 'my_tool';
  description = 'Tool description';
  inputSchema = z.object({ param: z.string() });

  async execute(input: z.infer<typeof this.inputSchema>) {
    return { result: 'success' };
  }
}
```

**Access User Data:**
```typescript
import { User } from 'lua-cli';

const user = await User.get();
await user.update({ preferences: 'dark-mode' });
await user.send([{ type: 'text', text: 'Hello!' }]);
```

**Use Custom Storage:**
```typescript
import { Data } from 'lua-cli';

await Data.create('notes', { text: 'Hello' });
const notes = await Data.get('notes');
const results = await Data.search('notes', 'query');
```

---

## Core Primitives

### LuaAgent

Unified agent configuration that combines skills, webhooks, jobs, and processors.

**Documentation:** [docs/api/LuaAgent.md](./api/LuaAgent.md)

**Quick Example:**
```typescript
import { LuaAgent, LuaSkill } from 'lua-cli';

export const agent = new LuaAgent({
  name: 'my-agent',
  persona: 'You are a helpful assistant...',
  skills: [skill1, skill2],
  webhooks: [webhook1],
  jobs: [job1],
  preProcessors: [preProcessor1],
  postProcessors: [postProcessor1]
});
```

---

### LuaSkill

Group related tools together with shared context.

**Documentation:** [docs/api/LuaSkill.md](./api/LuaSkill.md)

**Quick Example:**
```typescript
import { LuaSkill } from 'lua-cli';

export default new LuaSkill({
  name: 'weather-skill',
  description: 'Weather information tools',
  context: 'Use these tools to get weather data',
  tools: [tool1, tool2]
});
```

---

### LuaTool

Individual function your agent can call.

**Documentation:** [docs/api/LuaTool.md](./api/LuaTool.md)

**Quick Example:**
```typescript
import { LuaTool } from 'lua-cli/skill';
import { z } from 'zod';

export default class GetWeatherTool implements LuaTool {
  name = 'get_weather';
  description = 'Get current weather';

  inputSchema = z.object({
    city: z.string()
  });

  async execute(input) {
    return { temperature: 72, condition: 'sunny' };
  }
}
```

---

### LuaWebhook

HTTP endpoint for external integrations.

**Documentation:** [docs/api/LuaWebhook.md](./api/LuaWebhook.md)

**Quick Example:**
```typescript
import { LuaWebhook } from 'lua-cli';
import { z } from 'zod';

export default new LuaWebhook({
  name: 'payment-webhook',
  description: 'Handle payment notifications',

  bodySchema: z.object({
    orderId: z.string(),
    amount: z.number()
  }),

  execute: async ({ body, headers, query }) => {
    return { status: 200, body: { received: true } };
  }
});
```

---

### LuaJob

Scheduled task that runs automatically.

**Documentation:** [docs/api/LuaJob.md](./api/LuaJob.md)

**Quick Example:**
```typescript
import { LuaJob } from 'lua-cli';

export default new LuaJob({
  name: 'daily-cleanup',
  description: 'Clean up old data',

  schedule: {
    type: 'cron',
    pattern: '0 0 * * *'  // Midnight daily
  },

  execute: async (job) => {
    return { success: true, deleted: 42 };
  }
});
```

---

### PreProcessor

Filter or modify messages before they reach your agent.

**Documentation:** [docs/api/PreProcessor.md](./api/PreProcessor.md)

**Quick Example:**
```typescript
import { PreProcessor } from 'lua-cli';

export default new PreProcessor({
  name: 'spam-filter',
  description: 'Block spam messages',

  execute: async (message) => {
    if (message.text.includes('spam')) {
      return { action: 'BLOCK' };
    }
    return { action: 'PROCEED' };
  }
});
```

---

### PostProcessor

Transform or format agent responses.

**Documentation:** [docs/api/PostProcessor.md](./api/PostProcessor.md)

**Quick Example:**
```typescript
import { PostProcessor } from 'lua-cli';

export default new PostProcessor({
  name: 'response-formatter',
  description: 'Format responses',

  execute: async (response) => {
    return response.toUpperCase() + ' 🎉';
  }
});
```

---

## Runtime APIs

### User API

Access and manage user data.

**Documentation:** [docs/api/User.md](./api/User.md)

**Methods:**
- `User.get()` - Get current user
- `user.update(data)` - Update user data
- `user.send(messages)` - Send messages to user
- `user.getChatHistory()` - Get conversation history

**Example:**
```typescript
import { User } from 'lua-cli';

const user = await User.get();
console.log(user.name, user.email);

await user.update({ preferences: 'dark-mode' });

await user.send([
  { type: 'text', text: 'Hello!' },
  { type: 'image', url: 'https://example.com/image.jpg' }
]);

const history = await user.getChatHistory();
```

---

### Products API

Manage product catalog.

**Documentation:** [docs/api/Products.md](./api/Products.md)

**Methods:**
- `Products.get(filter?)` - List products
- `Products.getById(id)` - Get single product
- `Products.search(query, filter?)` - Search products
- `Products.create(data)` - Create product
- `product.update(data)` - Update product
- `product.delete()` - Delete product

**Example:**
```typescript
import { Products } from 'lua-cli';

// List all products
const products = await Products.get();

// Search products
const results = await Products.search('laptop', {
  category: 'electronics',
  inStock: true
});

// Create product
const product = await Products.create({
  name: 'MacBook Pro',
  price: 2499,
  category: 'electronics',
  stock: 10
});

// Update
await product.update({ price: 2299 });

// Delete
await product.delete();
```

---

### Data API

Custom data storage with vector search.

**Documentation:** [docs/api/Data.md](./api/Data.md)

**Methods:**
- `Data.get(collection, filter?)` - List entries
- `Data.getEntry(collection, id)` - Get single entry
- `Data.search(collection, query)` - Vector search
- `Data.create(collection, data)` - Create entry
- `entry.update(data)` - Update entry
- `entry.delete()` - Delete entry

**Example:**
```typescript
import { Data } from 'lua-cli';

// Create
await Data.create('notes', {
  title: 'Meeting Notes',
  content: 'Discussed Q1 roadmap...',
  tags: ['meeting', 'planning']
});

// List
const notes = await Data.get('notes', { tags: 'meeting' });

// Search (vector similarity)
const results = await Data.search('notes', 'roadmap planning');

// Update
const entry = await Data.getEntry('notes', 'entry-id');
await entry.update({ title: 'Updated Title' });

// Delete
await entry.delete();
```

---

### Baskets API

Shopping cart management.

**Documentation:** [docs/api/Baskets.md](./api/Baskets.md)

**Methods:**
- `Baskets.get()` - List baskets
- `Baskets.create()` - Create basket
- `Baskets.getById(id)` - Get basket
- `basket.addItem(item)` - Add item
- `basket.removeItem(productId)` - Remove item
- `basket.clear()` - Clear basket
- `basket.placeOrder()` - Convert to order

**Example:**
```typescript
import { Baskets } from 'lua-cli';

// Create basket
const basket = await Baskets.create();

// Add items
await basket.addItem({
  productId: 'prod-123',
  quantity: 2,
  price: 29.99
});

// Place order
const order = await basket.placeOrder();
```

---

### Orders API

Order management and fulfillment.

**Documentation:** [docs/api/Orders.md](./api/Orders.md)

**Methods:**
- `Orders.get(filter?)` - List orders
- `Orders.getById(id)` - Get order
- `Orders.create(data)` - Create order
- `Orders.updateStatus(status, orderId)` - Update status
- `order.updateData(data)` - Update order data

**Example:**
```typescript
import { Orders } from 'lua-cli';

// List orders
const orders = await Orders.get({ status: 'pending' });

// Update status
await Orders.updateStatus('confirmed', 'order-123');

// Get order
const order = await Orders.getById('order-123');
console.log(order.items, order.total, order.status);
```

---

### Jobs API

Create jobs dynamically from tools.

**Documentation:** [docs/api/Jobs.md](./api/Jobs.md)

**Methods:**
- `Jobs.create(config)` - Create job
- `Jobs.getJob(jobId)` - Get job
- `Jobs.getAll()` - List all jobs
- `job.user()` - Get job's user
- `job.delete()` - Delete job

**Example:**
```typescript
import { Jobs } from 'lua-cli';

// Create reminder job
const job = await Jobs.create({
  name: 'remind-user',
  metadata: { message: 'Meeting in 1 hour' },
  schedule: {
    type: 'once',
    executeAt: new Date(Date.now() + 3600000)
  },
  execute: async (job) => {
    const user = await job.user();
    await user.send([{
      type: 'text',
      text: job.metadata.message
    }]);
    return { success: true };
  }
});
```

---

### AI API

Generate AI text responses.

**Documentation:** [docs/api/AI.md](./api/AI.md)

**Methods:**
- `AI.generate(prompt, options?)` - Generate text

**Example:**
```typescript
import { AI } from 'lua-cli';

const response = await AI.generate('Summarize this text: ...', {
  maxTokens: 100,
  temperature: 0.7
});

console.log(response.text);
```

---

### Templates API

Send WhatsApp template messages.

**Documentation:** [docs/api/Templates.md](./api/Templates.md)

**Methods:**
- `Templates.whatsapp.list()` - List templates
- `Templates.whatsapp.get(name)` - Get template
- `Templates.whatsapp.send(config)` - Send template

**Example:**
```typescript
import { Templates } from 'lua-cli';

const templates = await Templates.whatsapp.list();

await Templates.whatsapp.send({
  templateName: 'order_confirmation',
  to: '+1234567890',
  parameters: {
    order_id: '12345',
    amount: '$99.99'
  }
});
```

---

### CDN API

Upload and download files.

**Documentation:** [docs/api/CDN.md](./api/CDN.md)

**Methods:**
- `CDN.upload(file, options)` - Upload file
- `CDN.get(fileId)` - Get file URL

**Example:**
```typescript
import { CDN } from 'lua-cli';

const result = await CDN.upload(fileBuffer, {
  filename: 'report.pdf',
  contentType: 'application/pdf'
});

const url = await CDN.get(result.fileId);
```

---

## Utilities

### env()

Access environment variables.

**Usage:**
```typescript
import { env } from 'lua-cli';

const apiKey = env('OPENAI_API_KEY');
const baseUrl = env('BASE_URL') || 'https://api.example.com';
```

**Setting Environment Variables:**
```bash
# Via CLI
lua env set OPENAI_API_KEY sk-...

# Via .env file (local only)
OPENAI_API_KEY=sk-...
```

---

### Lua Runtime

Access request context information.

**Usage:**
```typescript
import { Lua } from 'lua-cli';

if (Lua.request.channel === 'whatsapp') {
  // WhatsApp-specific logic
}

if (Lua.request.webhook) {
  // Running in webhook context
  console.log('Webhook:', Lua.request.webhook.name);
}
```

**Properties:**
- `Lua.request.channel` - Channel type (`'whatsapp'`, `'web'`, `'api'`)
- `Lua.request.webhook` - Webhook info (if running in webhook)

---

## Type Definitions

### Instance Classes

These are returned by API calls and provide instance methods:

| Instance | Methods | Description |
|----------|---------|-------------|
| `UserDataInstance` | `update()`, `send()`, `save()` | User with data access |
| `ProductInstance` | `update()`, `delete()`, `save()` | Product with CRUD |
| `BasketInstance` | `addItem()`, `removeItem()`, `placeOrder()` | Shopping cart |
| `OrderInstance` | `updateStatus()`, `updateData()` | Order management |
| `DataEntryInstance` | `update()`, `delete()`, `save()` | Custom data entry |
| `JobInstance` | `user()`, `delete()` | Job with metadata |

### Enums

```typescript
// Basket status
enum BasketStatus {
  ACTIVE = 'ACTIVE',
  CHECKED_OUT = 'CHECKED_OUT',
  ABANDONED = 'ABANDONED',
  EXPIRED = 'EXPIRED'
}

// Order status
enum OrderStatus {
  PENDING = 'PENDING',
  CONFIRMED = 'CONFIRMED',
  FULFILLED = 'FULFILLED',
  CANCELLED = 'CANCELLED'
}
```

---

## Complete API Index

| API | Purpose | Key Methods |
|-----|---------|-------------|
| [User](./api/User.md) | User data | `get()`, `update()`, `send()` |
| [Products](./api/Products.md) | Product catalog | `get()`, `search()`, `create()` |
| [Data](./api/Data.md) | Custom storage | `get()`, `search()`, `create()` |
| [Baskets](./api/Baskets.md) | Shopping carts | `create()`, `addItem()`, `placeOrder()` |
| [Orders](./api/Orders.md) | Order management | `get()`, `updateStatus()` |
| [Jobs](./api/Jobs.md) | Dynamic jobs | `create()`, `getAll()` |
| [AI](./api/AI.md) | AI generation | `generate()` |
| [Templates](./api/Templates.md) | WhatsApp templates | `list()`, `send()` |
| [CDN](./api/CDN.md) | File storage | `upload()`, `get()` |

---

## Usage by Category

### Building an Agent
1. [LuaAgent](./api/LuaAgent.md) - Configure agent
2. [LuaSkill](./api/LuaSkill.md) - Organize tools
3. [LuaTool](./api/LuaTool.md) - Create tools

### E-commerce
1. [Products API](./api/Products.md) - Manage catalog
2. [Baskets API](./api/Baskets.md) - Shopping carts
3. [Orders API](./api/Orders.md) - Process orders

### Automation
1. [LuaJob](./api/LuaJob.md) - Scheduled tasks
2. [Jobs API](./api/Jobs.md) - Dynamic jobs
3. [LuaWebhook](./api/LuaWebhook.md) - HTTP triggers

### Data Management
1. [User API](./api/User.md) - User data
2. [Data API](./api/Data.md) - Custom storage
3. [CDN API](./api/CDN.md) - File storage

---

## Best Practices

### Error Handling

Always wrap API calls in try-catch:
```typescript
try {
  const user = await User.get();
  await user.send([{ type: 'text', text: 'Hello!' }]);
} catch (error) {
  console.error('Failed to send message:', error);
  return { error: error.message };
}
```

### Type Safety

Use TypeScript types for better IDE support:
```typescript
import { UserDataInstance, ProductInstance } from 'lua-cli';

const user: UserDataInstance = await User.get();
const product: ProductInstance = await Products.getById('prod-123');
```

### Environment Variables

Never hardcode secrets:
```typescript
// ❌ Bad
const apiKey = 'sk-1234567890';

// ✅ Good
import { env } from 'lua-cli';
const apiKey = env('OPENAI_API_KEY');
```

### Async/Await

All API calls are async:
```typescript
// ❌ Bad (missing await)
const user = User.get();

// ✅ Good
const user = await User.get();
```

---

## See Also

- [Getting Started Guide](./GETTING_STARTED.md) - Step-by-step tutorial
- [CLI Reference](./CLI_REFERENCE.md) - All commands
- [Main README](../README.md) - Project overview
- [API Index](./API_INDEX.md) - Quick reference table

---

**Version:** 3.5.0-alpha.3
**Last Updated:** February 2026
