UNPKG

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
# Lua CLI > Build, test, and deploy AI agents with custom tools, webhooks, and scheduled jobs [![npm version](https://img.shields.io/npm/v/lua-cli.svg)](https://www.npmjs.com/package/lua-cli) [![License](https://img.shields.io/npm/l/lua-cli.svg)](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)