> ## 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.

# Platform APIs

> Built-in APIs for common operations

## Overview

Lua CLI provides built-in APIs for common operations, so you don't have to build everything from scratch.

```typescript theme={null}
import { Agents, User, Data, CDN, Products, Baskets, Orders, Templates } from 'lua-cli';
```

<CardGroup cols={3}>
  <Card title="Agents" icon="robot">
    Invoke another agent through the full chat pipeline
  </Card>

  <Card title="User" icon="user">
    Per-user persistent storage for state, preferences, and workflow data
  </Card>

  <Card title="Data" icon="database">
    Custom data with vector search
  </Card>

  <Card title="CDN" icon="cloud">
    File upload and retrieval
  </Card>

  <Card title="Products" icon="box">
    E-commerce product catalog
  </Card>

  <Card title="Baskets" icon="cart-shopping">
    Shopping cart management
  </Card>

  <Card title="Orders" icon="receipt">
    Order processing
  </Card>

  <Card title="Templates" icon="message">
    Template messaging (WhatsApp)
  </Card>
</CardGroup>

## Agents API

**Agent-to-agent invocation** — call a target agent through its full processing pipeline (billing, persistence, skills, preprocessors, postprocessors) from any sandbox code.

```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 with usage and tool info
const result = await Agents.invoke('legal-agent', {
  prompt: 'Review this clause for risks.',
  threadId: 'contract-456',
  systemPrompt: 'Be concise.',
});
```

### Use Cases

<Tabs>
  <Tab title="Tool Routing">
    ```typescript theme={null}
    // Inside a tool — caller's user is used automatically
    const analysis = await Agents.invoke('data-analyst-agent', {
      prompt: `Analyse this dataset: ${JSON.stringify(data)}`,
      threadId: `analysis-${jobId}`,
    });
    return { report: analysis.text };
    ```
  </Tab>

  <Tab title="Webhook Delegation">
    ```typescript theme={null}
    // Inside a webhook — pass userId from the event payload
    execute: async (event) => {
      const { customerId, orderId } = event.body;
      await Agents.invoke('notification-agent', {
        prompt: `Order ${orderId} has shipped. Notify the customer.`,
        userId: customerId, // provide the user to run as
      });
      return { notified: true };
    }
    ```
  </Tab>

  <Tab title="Scheduled Job">
    ```typescript theme={null}
    // Inside a LuaJob — no ambient user, no conversation history stored
    execute: async (job) => {
      const result = await Agents.invoke('digest-agent', {
        prompt: 'Generate the daily digest.',
        // userId omitted — invocation runs without user identity
      });
      return { digest: result.text };
    }
    ```
  </Tab>
</Tabs>

<Card title="Full API Reference" icon="book" href="/api/agents">
  Complete Agents API documentation
</Card>

## User API

**Persistent per-user storage** that survives across conversations and sessions. Store any data — onboarding state, workflow progress, preferences, cart contents, verification results — as direct properties on the user object.

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

const user = await User.get();

// Write any property — it persists across conversations
user.onboardingStep = 'verified';
user.plan = 'enterprise';
user.collectedData = { company: 'Acme', role: 'admin' };
user.lastInteraction = new Date().toISOString();
await user.save();

// Read it back anytime (even days later, in a different conversation)
const returning = await User.get();
console.log(returning.onboardingStep); // 'verified'
console.log(returning.plan);           // 'enterprise'
```

### Example: Stateful Onboarding Tool

```typescript theme={null}
export class CheckOnboardingTool implements LuaTool {
  name = "check_onboarding";
  description = "Check and advance the user's onboarding progress";
  inputSchema = z.object({});

  async execute(input: any) {
    const user = await User.get();
    const step = user.onboardingStep || 'not_started';

    if (step === 'complete') {
      return { message: `Welcome back, ${user.name}! You're all set up.` };
    }

    return {
      currentStep: step,
      completedSteps: user.completedSteps || [],
      message: `You're on step: ${step}. Let's continue!`
    };
  }
}
```

<Card title="Full API Reference" icon="book" href="/api/user">
  Complete User API documentation
</Card>

## Data API

Store and retrieve custom data with semantic search capabilities.

### Key Features

* 🗄️ **Custom Collections**: Store any JSON data
* 🔍 **Vector Search**: Semantic similarity search
* 📊 **Filtering**: Query by field values
* 📄 **Pagination**: Handle large datasets

### Quick Example

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

// Create with search indexing
await Data.create('movies', {
  title: 'Inception',
  director: 'Christopher Nolan',
  year: 2010
}, 'Inception Christopher Nolan 2010 sci-fi thriller dreams');

// Semantic search
const results = await Data.search('movies', 'mind-bending thriller', 10, 0.7);
// Finds "Inception" even though query doesn't contain exact words!
```

### Use Cases

<Tabs>
  <Tab title="Knowledge Base">
    ```typescript theme={null}
    await Data.create('kb_articles', {
      title: 'How to reset password',
      content: 'Step by step guide...',
      category: 'Account'
    }, `password reset account help`);

    const results = await Data.search('kb_articles', 
      'forgot my password', 10, 0.7);
    ```
  </Tab>

  <Tab title="Customer Notes">
    ```typescript theme={null}
    await Data.create('customers', {
      name: 'John Doe',
      company: 'Acme Corp',
      notes: 'Interested in enterprise plan'
    }, `John Doe Acme Corp enterprise`);

    const results = await Data.search('customers',
      'enterprise customers', 20, 0.6);
    ```
  </Tab>

  <Tab title="Product Recommendations">
    ```typescript theme={null}
    await Data.create('products', {
      name: 'Wireless Headphones',
      description: 'Noise cancelling...',
      category: 'Electronics'
    }, `wireless headphones noise cancelling bluetooth`);

    const results = await Data.search('products',
      'best headphones for travel', 5, 0.75);
    ```
  </Tab>
</Tabs>

<Card title="Full API Reference" icon="book" href="/api/data">
  Complete Data API documentation
</Card>

## CDN API

Upload and retrieve files from the Lua CDN.

### Key Features

* 📤 **Upload Files**: Store any file type
* 📥 **Retrieve Files**: Get files by ID
* 🖼️ **Image Optimization**: Automatic WebP compression
* 🤖 **AI Integration**: Use with AI for image analysis

### Quick Example

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

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

// Retrieve by ID
const retrievedFile = await CDN.get(fileId);
console.log(retrievedFile.name); // 'document.pdf'
```

### Use Cases

<Tabs>
  <Tab title="Document Storage">
    ```typescript theme={null}
    // Store a document
    const doc = new File([content], 'report.pdf', { 
      type: 'application/pdf' 
    });
    const fileId = await CDN.upload(doc);

    // Save reference
    await Data.create('documents', {
      title: 'Q4 Report',
      fileId: fileId,
      uploadedAt: new Date().toISOString()
    });
    ```
  </Tab>

  <Tab title="Image Analysis">
    ```typescript theme={null}
    // Get image from CDN
    const file = await CDN.get(imageFileId);
    const buffer = Buffer.from(await file.arrayBuffer());

    // Analyze with AI
    const analysis = await AI.generate(
      'Describe this image.',
      [{ type: 'image', image: buffer, mediaType: file.type }]
    );
    ```
  </Tab>

  <Tab title="User Uploads">
    ```typescript theme={null}
    // Save user upload
    const file = new File([userData], 'profile.jpg', { 
      type: 'image/jpeg' 
    });
    const fileId = await CDN.upload(file);

    // Update user profile
    await User.update({ avatarFileId: fileId });
    ```
  </Tab>
</Tabs>

<Card title="Full API Reference" icon="book" href="/api/cdn">
  Complete CDN API documentation
</Card>

## Products API

Manage e-commerce product catalog.

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

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

// Create product
await Products.create({
  name: 'MacBook Pro',
  price: 1999.99,
  category: 'Computers',
  sku: 'MBP-14-001',
  inStock: true
});

// Get by ID
const product = await Products.getById('product_abc123');
```

<Card title="Full API Reference" icon="book" href="/api/products">
  Complete Products API documentation
</Card>

## Baskets API

Shopping cart management for e-commerce.

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

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

// Add items
await Baskets.addItem(basket.id, {
  id: 'product_xyz',
  price: 29.99,
  quantity: 2,
  SKU: 'PROD-001'
});

// Checkout
const order = await Baskets.placeOrder({
  shippingAddress: {...},
  paymentMethod: 'stripe'
}, basket.id);
```

### Basket Statuses

<Tabs>
  <Tab title="ACTIVE">
    Currently being used for shopping
  </Tab>

  <Tab title="CHECKED_OUT">
    Converted to an order
  </Tab>

  <Tab title="ABANDONED">
    User left without checkout
  </Tab>

  <Tab title="EXPIRED">
    TTL exceeded
  </Tab>
</Tabs>

<Card title="Full API Reference" icon="book" href="/api/baskets">
  Complete Baskets API documentation
</Card>

## Orders API

Order creation and management.

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

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

// Update status
await Orders.updateStatus(OrderStatus.FULFILLED, order.id);

// Get orders
const userOrders = await Orders.get(OrderStatus.PENDING);
```

### Order Statuses

<Steps>
  <Step title="PENDING">
    Created, not yet confirmed
  </Step>

  <Step title="CONFIRMED">
    Confirmed, being processed
  </Step>

  <Step title="FULFILLED">
    Completed and delivered
  </Step>

  <Step title="CANCELLED">
    Cancelled by user or system
  </Step>
</Steps>

<Card title="Full API Reference" icon="book" href="/api/orders">
  Complete Orders API documentation
</Card>

## Templates API

Send template messages across different channels. Currently supports WhatsApp templates.

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

// List WhatsApp templates
const result = await Templates.whatsapp.list(channelId, { search: 'order' });

// Get specific template
const template = await Templates.whatsapp.get(channelId, templateId);

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

### Use Cases

* 📦 **Order notifications** - Shipping updates, delivery confirmations
* 📅 **Appointment reminders** - Healthcare, salon, service bookings
* 🎉 **Marketing campaigns** - Promotions, announcements
* 🔐 **Authentication** - OTP codes, verification messages

<Card title="Full API Reference" icon="book" href="/api/templates">
  Complete Templates API documentation
</Card>

## Combining APIs

Most real-world applications combine multiple APIs:

### E-commerce Flow Example

```typescript theme={null}
export class QuickCheckoutTool implements LuaTool {
  async execute(input: any) {
    // 1. Search for product
    const products = await Products.search(input.productName);
    const product = products.products[0];
    
    // 2. Create basket
    const basket = await Baskets.create({ currency: 'USD' });
    
    // 3. Add product
    await Baskets.addItem(basket.id, {
      id: product.id,
      price: product.price,
      quantity: input.quantity
    });
    
    // 4. Create order
    const order = await Baskets.placeOrder({
      shippingAddress: input.address,
      paymentMethod: 'stripe'
    }, basket.id);
    
    return {
      orderId: order.id,
      total: basket.common.totalAmount
    };
  }
}
```

### CRM with Custom Data Example

```typescript theme={null}
export class CreateCustomerTool implements LuaTool {
  async execute(input: any) {
    // Get current user
    const user = await User.get();
    
    // Create customer record
    const customer = await Data.create('customers', {
      name: input.name,
      email: input.email,
      company: input.company,
      createdBy: user.email,
      createdAt: new Date().toISOString()
    }, `${input.name} ${input.company} ${input.email}`);
    
    // Log interaction
    await Data.create('interactions', {
      customerId: customer.id,
      type: 'created',
      notes: 'Initial contact',
      timestamp: new Date().toISOString()
    });
    
    return { customerId: customer.id };
  }
}
```

## API Comparison

| API           | Best For                  | Key Feature                                  |
| ------------- | ------------------------- | -------------------------------------------- |
| **Agents**    | Multi-agent orchestration | Full pipeline invocation with auth & billing |
| **User**      | Per-user persistent state | Schemaless key-value store across sessions   |
| **Data**      | Custom schemas            | Vector search                                |
| **CDN**       | File storage              | Upload/retrieve files                        |
| **Products**  | E-commerce                | Pre-built catalog                            |
| **Baskets**   | Shopping carts            | TTL & status                                 |
| **Orders**    | Order tracking            | Status workflow                              |
| **Templates** | Proactive messaging       | WhatsApp templates                           |

## Next Steps

<CardGroup cols={2}>
  <Card title="API Reference" icon="book" href="/api/overview">
    Complete API documentation with examples
  </Card>

  <Card title="Tool Examples" icon="layer-group" href="/examples/overview">
    See working examples using all APIs
  </Card>

  <Card title="Build Your First Skill" icon="hammer" href="/getting-started/first-skill">
    Step-by-step tutorial
  </Card>

  <Card title="Environment Variables" icon="key" href="/concepts/environment-variables">
    Learn about configuration management
  </Card>
</CardGroup>
