lua-cli
Version:
Build, test, and deploy AI agents with custom tools, webhooks, and scheduled jobs. Features LuaAgent unified configuration, streaming chat, and batch deployment.
865 lines (636 loc) β’ 18.7 kB
Markdown
# Lua CLI
> Build, test, and deploy AI agents with custom tools, webhooks, and scheduled jobs
[](https://www.npmjs.com/package/lua-cli)
[](https://github.com/heylua/lua-cli/blob/main/LICENSE)
**Lua CLI** is a command-line interface for building intelligent AI agents on the Lua AI platform. Create custom tools, integrate with external APIs, schedule automated tasks, and deploy to productionβall from your terminal.
## β¨ Features
- π€ **LuaAgent** - Unified agent configuration with persona, skills, webhooks, and jobs
- π οΈ **Custom Tools** - Build TypeScript tools with full type safety and Zod validation
- πͺ **Webhooks** - HTTP endpoints for external integrations (Stripe, Shopify, etc.)
- β° **Scheduled Jobs** - Cron-based and one-time background tasks
- π₯ **Preprocessors** - Filter and route messages before they reach your agent
- π€ **Postprocessors** - Transform and format agent responses
- π¬ **Streaming Chat** - Real-time chat interface with typing indicators
- π§ͺ **Local Testing** - Test tools, webhooks, and jobs before deploying
- π **Batch Deployment** - Push all components with one command
- π **Auto-Sync** - YAML and code stay synchronized automatically
- π **CI/CD Ready** - Environment variable support for automated deployments
## π¦ Installation
### Global Installation (Recommended)
```bash
npm install -g lua-cli
```
### Project Installation
```bash
npm install lua-cli
```
### Verify Installation
```bash
lua --version
```
## π Quick Start
### 1. Authenticate
```bash
lua auth configure
```
Enter your API key when prompted (get one at https://admin.heylua.ai).
### 2. Initialize Project
```bash
mkdir my-agent
cd my-agent
lua init
```
Follow the prompts to:
- Select or create an agent
- Configure persona and welcome message
- Set up your project
### 3. Test Your Agent
```bash
# Test individual tools
lua test
# Chat with your agent
lua chat
```
### 4. Deploy to Production
```bash
# Interactive deployment
lua push
# Or batch deployment
lua push all --force --auto-deploy
```
## π― Core Concepts
### LuaAgent
The unified configuration for your AI agent:
```typescript
import { LuaAgent, LuaSkill, LuaWebhook, LuaJob } from 'lua-cli';
export const agent = new LuaAgent({
name: 'my-assistant',
persona: 'You are a helpful AI assistant...',
welcomeMessage: 'Hello! How can I help you today?',
skills: [customerSupportSkill, productSkill],
webhooks: [paymentWebhook],
jobs: [dailyReportJob],
preProcessors: [messageFilter],
postProcessors: [responseFormatter]
});
```
### Skills
Group related tools together:
```typescript
import { LuaSkill } from 'lua-cli';
const weatherSkill = new LuaSkill({
name: 'weather-skill',
description: 'Weather information tools',
context: 'Use these tools to get weather data for any location',
tools: [
new GetWeatherTool(),
new GetForecastTool()
]
});
```
### Tools
Individual functions your agent can use:
```typescript
import { LuaTool } from 'lua-cli/skill';
import { z } from 'zod';
export default class GetWeatherTool implements LuaTool {
name = 'get_weather';
description = 'Get current weather for a city';
inputSchema = z.object({
city: z.string()
});
async execute(input: z.infer<typeof this.inputSchema>) {
// Your logic here
return { temperature: 72, condition: 'sunny' };
}
}
```
### Webhooks
Receive HTTP requests from external systems:
```typescript
import { LuaWebhook } from 'lua-cli';
import { z } from 'zod';
export default new LuaWebhook({
name: 'payment-webhook',
version: '1.0.0',
description: 'Handle payment notifications',
bodySchema: z.object({
orderId: z.string(),
amount: z.number(),
status: z.string()
}),
execute: async ({ body, headers, query }) => {
// Process payment event
return {
status: 200,
body: { received: true }
};
}
});
```
### Jobs
Schedule automated tasks:
```typescript
import { LuaJob } from 'lua-cli';
export default new LuaJob({
name: 'daily-cleanup',
version: '1.0.0',
description: 'Clean up old data daily',
schedule: {
type: 'cron',
pattern: '0 0 * * *' // Midnight every day
},
execute: async (job) => {
// Cleanup logic
return { success: true, deleted: 42 };
}
});
```
## π Available APIs
Access powerful APIs in your tools and jobs:
### User API
```typescript
import { User } from 'lua-cli';
const user = await User.get();
await user.update({ preferences: 'dark-mode' });
await user.send([{ type: 'text', text: 'Hello!' }]);
```
### Products API
```typescript
import { Products } from 'lua-cli';
const products = await Products.get();
const product = await Products.create({ name: 'Widget', price: 29.99 });
await product.update({ price: 24.99 });
await product.delete();
```
### Baskets API
```typescript
import { Baskets } from 'lua-cli';
const basket = await Baskets.create();
await basket.addItem({ productId: '123', quantity: 2 });
await basket.placeOrder();
```
### Orders API
```typescript
import { Orders } from 'lua-cli';
const orders = await Orders.get();
await Orders.updateStatus('confirmed', orderId);
```
### Custom Data API
```typescript
import { Data } from 'lua-cli';
const movies = await Data.get('movies');
await Data.create('movies', { title: 'Inception', year: 2010 });
const results = await Data.search('movies', 'action thriller');
```
### Jobs API
```typescript
import { Jobs } from 'lua-cli';
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 };
}
});
```
## π οΈ CLI Commands
### Project Setup
```bash
lua auth configure # Set up API key
lua init # Initialize new project
```
### Development
```bash
lua compile # Compile TypeScript to deployable format
lua test # Test tools/webhooks/jobs interactively
lua chat # Interactive chat with your agent
```
### Deployment
```bash
lua push # Push new version (interactive)
lua push all --force # Push all components without prompts
lua deploy # Deploy version to production
```
### Management
```bash
lua production # View production status
lua env # Manage environment variables
lua persona # Update agent persona
lua logs # View agent logs
lua skills # Manage skills
lua webhooks # Manage webhooks
lua jobs # Manage scheduled jobs
```
### Utilities
```bash
lua admin # Open admin dashboard
lua docs # Open documentation
lua channels # Manage chat channels
```
## π§ Advanced Features
### Streaming Chat
Real-time chat responses with typing indicators:
```bash
lua chat
```
- β
Animated typing indicator while waiting
- β
Text streams character-by-character as AI generates
- β
Custom welcome message from `lua.skill.yaml`
- β
Sandbox and production environments
### Batch Deployment
Deploy all components at once:
```bash
# Push everything without prompts
lua push all --force
# Push and deploy to production
lua push all --force --auto-deploy
```
Perfect for CI/CD pipelines:
- β
Auto-bumps patch versions
- β
No user interaction required
- β
Handles all component types
- β
Comprehensive error handling
### API Key Fallback
Flexible authentication for different environments:
**Priority:**
1. System keychain (macOS Keychain, Windows Credential Vault, Linux libsecret)
2. `LUA_API_KEY` environment variable
3. `LUA_API_KEY` in `.env` file
```bash
# CI/CD usage
export LUA_API_KEY=your-api-key
lua push all --force --auto-deploy
```
### Auto-Sync Configuration
Your `lua.skill.yaml` and `LuaAgent` stay synchronized:
- Run `lua init` β Syncs agent metadata to both YAML and code
- Run `lua compile` β Syncs LuaAgent changes back to YAML
- Edit either file β Changes propagate automatically
## π Example Tool
```typescript
import { LuaTool, User } from 'lua-cli/skill';
import { z } from 'zod';
import axios from 'axios';
export default class WeatherTool implements LuaTool {
name = 'get_weather';
description = 'Get current weather for any city';
inputSchema = z.object({
city: z.string().describe('City name'),
units: z.enum(['metric', 'imperial']).optional()
});
outputSchema = z.object({
temperature: z.number(),
condition: z.string(),
city: z.string()
});
async execute(input: z.infer<typeof this.inputSchema>) {
const response = await axios.get('https://api.weather.com/current', {
params: {
city: input.city,
units: input.units || 'metric',
apiKey: process.env.WEATHER_API_KEY
}
});
return {
temperature: response.data.temp,
condition: response.data.condition,
city: input.city
};
}
}
```
## ποΈ Project Structure
```
your-project/
βββ src/
β βββ index.ts # LuaAgent configuration
β βββ skills/ # Tool collections
β β βββ tools/ # Individual tools
β β βββ *.skill.ts # Skill definitions
β βββ webhooks/ # HTTP endpoints
β βββ jobs/ # Scheduled tasks
β βββ preprocessors/ # Message filters
β βββ postprocessors/ # Response formatters
β βββ services/ # Shared utilities
βββ lua.skill.yaml # Agent metadata
βββ .env # Environment variables
βββ package.json
βββ tsconfig.json
```
## π Security
### API Keys
- β
Stored securely in system keychain
- β
Never committed to version control
- β
Environment variable fallback for CI/CD
- β
Per-environment configuration
### Webhooks
- β
Signature validation support
- β
Request body validation with Zod
- β
HTTPS endpoints only
- β
Rate limiting ready
### User Data
- β
Encrypted at rest
- β
Scoped to authenticated users
- β
GDPR-compliant deletion
- β
Privacy-first design
## π§ͺ Testing
### Test Individual Components
```bash
# Test a tool
lua test
# Select: Tool β get_weather
# Input: { city: "London" }
# Output: { temperature: 15, condition: "cloudy" }
# Test a webhook
lua test
# Select: Webhook β payment-webhook
# Input body, headers, query
# See response
# Test a job
lua test
# Select: Job β daily-cleanup
# Execute immediately
# See results
```
### Interactive Chat Testing
```bash
lua chat
# Select environment: Sandbox or Production
# Chat with your agent
# See tools in action
```
## π Deployment
### Development Workflow
```bash
# 1. Make changes to your code
vim src/skills/tools/MyTool.ts
# 2. Test locally
lua test
# 3. Test with chat
lua chat # Sandbox mode
# 4. Compile
lua compile
# 5. Push to server
lua push
# 6. Deploy to production
lua deploy
```
### CI/CD Workflow
```yaml
# .github/workflows/deploy.yml
- name: Deploy Agent
run: lua push all --force --auto-deploy
env:
LUA_API_KEY: ${{ secrets.LUA_API_KEY }}
```
## π Configuration
### lua.skill.yaml
Central configuration file:
```yaml
agent:
agentId: your-agent-id
orgId: your-org-id
persona: |
You are a helpful AI assistant...
welcomeMessage: Hello! How can I help you today?
skills:
- name: general-skill
version: 1.0.0
skillId: skill-id-123
webhooks:
- name: payment-webhook
version: 1.0.0
webhookId: webhook-id-456
jobs:
- name: daily-cleanup
version: 1.0.0
jobId: job-id-789
schedule:
type: cron
pattern: "0 0 * * *"
```
### Environment Variables
```.env
# Lua Platform
LUA_API_KEY=your-lua-api-key # Optional: for CI/CD
# External Services
OPENAI_API_KEY=sk-...
STRIPE_SECRET_KEY=sk_live_...
PINECONE_API_KEY=...
# Custom Configuration
BASE_URL=https://api.example.com
```
## π Documentation
### Getting Started
- **[Quick Start Guide](template/QUICKSTART.md)** - Complete step-by-step tutorial
- **[Template README](template/README.md)** - Comprehensive project guide
- **[CLI Reference](#cli-commands)** - All available commands
### API Documentation
- **[Complete API Reference](docs/README.md)** - Full API documentation
- **[API Index](docs/API_INDEX.md)** - Quick reference table
- **Core APIs:**
- [LuaAgent](docs/api/LuaAgent.md) - Agent configuration
- [LuaSkill](docs/api/LuaSkill.md) - Tool collections
- [LuaTool](docs/api/LuaTool.md) - Creating tools
- **Runtime APIs:**
- [AI API](docs/api/AI.md) - AI text generation and analysis
- [User API](docs/api/User.md) - User data management
- [Products API](docs/api/Products.md) - Product catalog
- [Data API](docs/api/Data.md) - Custom data storage
- [Jobs API](docs/api/Jobs.md) - Dynamic job creation
### Advanced Topics
- [Webhooks & Jobs Guide](WEBHOOKS_JOBS_USAGE_GUIDE.md) - External integrations
- [Processors Guide](PROCESSORS_GUIDE.md) - Message processing
- [Dynamic Jobs](DYNAMIC_JOB_CREATION_API.md) - Creating jobs programmatically
- [Agent Configuration](LUAAGENT_IMPLEMENTATION.md) - LuaAgent deep dive
### Examples
- [Template Project](template/) - Full working example with 30+ tools
- [Example Skills](template/src/skills/) - Organized skill examples
- [Example Webhooks](template/src/webhooks/) - Webhook patterns
- [Example Jobs](template/src/jobs/) - Scheduled task examples
## π» Development
### Prerequisites
- Node.js 16+
- npm or yarn
- TypeScript 5+
### Building from Source
```bash
# Clone repository
git clone https://github.com/heylua/lua-cli.git
cd lua-cli
# Install dependencies
npm install
# Build
npm run build
# Link globally
npm link
# Run tests
npm test
```
### Project Scripts
```bash
npm run build # Compile TypeScript
npm run build:react # Build web interface
npm run clean # Clean dist folder
npm test # Run test suite
```
## π What's New in v3.0.0
### Major Features
#### LuaAgent - Unified Configuration
- β
Single source of truth for all agent components
- β
Cleaner, more intuitive API
- β
Automatic sync with `lua.skill.yaml`
#### Streaming Chat Interface
- β
Real-time text streaming as AI generates responses
- β
Animated typing indicators
- β
Custom welcome messages from YAML
- β
Improved user experience
#### Batch Deployment
- β
`lua push all --force` - Deploy everything at once
- β
Auto-bump patch versions
- β
`--auto-deploy` flag for production
- β
Perfect for CI/CD pipelines
#### Enhanced Bundling
- β
Optimized bundle sizes (excludes lua-cli internals)
- β
Better import resolution
- β
Faster compilation
- β
Reduced deployment size
#### Improved Authentication
- β
Multi-source API key loading
- β
Environment variable support
- β
`.env` file fallback
- β
CI/CD friendly
### Breaking Changes from v2.x
- **LuaAgent required** - Use `new LuaAgent()` instead of exporting individual skills
- **Streaming endpoints** - Chat uses `/chat/stream` instead of `/chat/generate`
- **Jobs.create signature** - Metadata field recommended for passing data
See [CHANGELOG.md](CHANGELOG.md) for complete list of changes.
## π€ Contributing
We welcome contributions! Please see our contributing guidelines:
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request
### Development Setup
```bash
git clone https://github.com/heylua/lua-cli.git
cd lua-cli
npm install
npm run build
npm link
```
## π Use Cases
### Customer Support
- Handle product queries
- Process returns and refunds
- Escalate complex issues
- Track support tickets
### E-commerce
- Product recommendations
- Shopping cart management
- Order processing
- Payment integration
### Data Analysis
- Query databases
- Generate reports
- Visualize data
- Schedule analytics jobs
### Automation
- Scheduled reminders
- Data synchronization
- Health monitoring
- Batch processing
## π Support
### Getting Help
- **Documentation:** https://docs.heylua.ai
- **Email:** support@heylua.ai
- **GitHub Issues:** https://github.com/heylua/lua-cli/issues
- **Community:** https://community.heylua.ai
### Common Issues
**Q: How do I get an API key?**
Visit https://admin.heylua.ai and create an account.
**Q: Can I use this in production?**
Yes! v3.0.0 is production-ready with comprehensive testing and error handling.
**Q: How do I update to the latest version?**
```bash
npm install -g lua-cli@latest
```
**Q: Does this work with TypeScript?**
Yes! Full TypeScript support with type definitions included.
**Q: Can I deploy from CI/CD?**
Yes! Use environment variables and `lua push all --force --auto-deploy`.
## π License
MIT License - see [LICENSE](LICENSE) file for details.
## π Acknowledgments
Built with:
- [TypeScript](https://www.typescriptlang.org/)
- [Zod](https://zod.dev/) - Schema validation
- [esbuild](https://esbuild.github.io/) - Fast bundling
- [Commander.js](https://github.com/tj/commander.js/) - CLI framework
- [Inquirer](https://github.com/SBoudrias/Inquirer.js/) - Interactive prompts
## π Links
- **Website:** https://heylua.ai
- **Documentation:** https://docs.heylua.ai
- **Admin Dashboard:** https://admin.heylua.ai
- **npm Package:** https://www.npmjs.com/package/lua-cli
- **GitHub:** https://github.com/heylua/lua-cli
## π Roadmap
### Coming Soon
- π Real-time collaboration tools
- π Built-in analytics dashboard
- π¨ Visual skill builder
- π More integration templates
- π± Mobile SDK
### In Progress
- β
Enhanced error reporting
- β
Performance optimizations
- β
More example templates
- β
Improved documentation
## π¬ Community
Join the Lua community:
- **Discord:** Coming soon
- **Twitter:** @heylua_ai
- **Blog:** https://heylua.ai/blog
Share your agents, get help, and learn from others!
*Made with β€οΈ by the Lua team*
**Version:** 3.0.0
**Last Updated:** October 2025
## Quick Links
- [Quick Start β](template/QUICKSTART.md)
- [API Documentation β](API_REFERENCE.md)
- [Template Examples β](template/)
- [Changelog β](CHANGELOG.md)