UNPKG

myaidev-method

Version:

Comprehensive development framework with SPARC methodology for AI-assisted software development, multi-platform publishing (WordPress, PayloadCMS, Astro, Docusaurus, Mintlify), and Coolify deployment

751 lines (568 loc) 17.4 kB
# Coolify Deployment Agent Optimized Coolify deployment agent for Claude Code 2.0 with modern agent patterns, efficient API utilities, and scriptable deployment workflows. ## Overview The Coolify deployment agent is a specialized subagent optimized for deploying applications to Coolify infrastructure. It follows Claude Code 2.0 best practices: - **Lightweight pattern** (<3k tokens) for fast operations - **Extended thinking** support for complex deployment decisions - **Subagent delegation** for parallel multi-component deployments - **Security-first** with permission scoping and credential safety ## Features ✅ **Application Deployment** - Git, Docker, Nixpacks, Docker Compose ✅ **Resource Management** - Servers, projects, databases, services ✅ **Environment Configuration** - Secure env var and secret management ✅ **Monitoring & Logs** - Real-time deployment tracking ✅ **Scriptable API** - Reusable utilities for automation ✅ **Claude Code 2.0 Optimized** - Modern agent patterns ## Installation ```bash npm install myaidev-method # or npx myaidev-method@latest init --claude ``` ## Configuration Add Coolify credentials to `.env`: ```bash COOLIFY_URL=https://coolify.myai1.ai COOLIFY_API_KEY=your_api_key_here ``` **Get API Key:** 1. Login to Coolify 2. Go to Settings → Keys & Tokens 3. Create API Token 4. Copy token to `.env` **Verify Configuration:** ```bash npm run coolify:status ``` ## Quick Start ### Using Slash Command (Recommended) ```bash # Check status /myai-coolify-deploy status # List resources /myai-coolify-deploy list servers /myai-coolify-deploy list applications # Deploy application /myai-coolify-deploy deploy --repo https://github.com/user/app --name myapp ``` ### Using NPM Scripts ```bash # Check Coolify status npm run coolify:status # List all servers npm run coolify:list -- --type servers # List applications with details npm run coolify:list -- --type applications --detailed # Get JSON output npm run coolify:list -- --type all --json ``` ### Using Utilities Directly ```javascript import { CoolifyUtils } from 'myaidev-method/src/lib/coolify-utils.js'; const coolify = new CoolifyUtils(); // List servers const servers = await coolify.listServers(); console.log(servers); // Deploy application const deployment = await coolify.deployApplication(uuid, { force: true, instant: false }); // Wait for deployment const result = await coolify.waitForDeployment(uuid); console.log(result.success ? '✓ Deployed' : '✗ Failed'); ``` ## Agent Usage ### Pattern 1: Simple Deployment For standard deployments, use the lightweight pattern: ```bash /myai-coolify-deploy deploy --repo https://github.com/user/nextjs-app --name production ``` **Agent workflow:** 1. Verifies Coolify connectivity (script) 2. Lists available servers (script) 3. Selects optimal server (logic) 4. Creates application (API) 5. Triggers deployment (API) 6. Monitors progress (script) 7. Reports URL and status **Token usage:** ~2-3k tokens **Duration:** 2-5 minutes (depends on build) ### Pattern 2: Extended Thinking For complex decisions, use extended thinking: ```bash /myai-coolify-deploy think about optimal deployment strategy for multi-region app ``` **Thinking triggers:** - `think` - Standard analysis (~4k tokens) - `think hard` - Deep analysis (~10k tokens) - `think harder` - Comprehensive analysis (~20k tokens) - `ultrathink` - Maximum depth (~32k tokens) **Use cases:** - Server selection optimization - Deployment troubleshooting - Architecture planning - Performance optimization ### Pattern 3: Subagent Delegation For multi-component applications, delegate to subagents: ```bash /myai-coolify-deploy deploy-stack --config full-stack.json ``` **Agent creates parallel subagents:** ``` Main Agent ├─ Database SubagentDeploy PostgreSQL ├─ Cache SubagentDeploy Redis ├─ API SubagentDeploy Backend (waits for DB) └─ Frontend SubagentDeploy Frontend (waits for API) ``` **Benefits:** - Parallel execution (faster) - Focused responsibility (reliable) - Independent context (efficient) - Clear interfaces (maintainable) ## Available Scripts ### Resource Management ```bash # System status npm run coolify:status npm run coolify:status -- --comprehensive # List resources npm run coolify:list -- --type servers npm run coolify:list -- --type projects npm run coolify:list -- --type applications npm run coolify:list -- --type databases npm run coolify:list -- --type services npm run coolify:list -- --type all --detailed ``` ### Deployment Operations ```bash # Deploy application node src/scripts/coolify-deploy-app.js \ --name "myapp" \ --repo "https://github.com/user/myapp" \ --branch "main" \ --server-uuid "server-uuid" \ --project-uuid "project-uuid" \ --build-pack "nixpacks" \ --port "3000" \ --domain "myapp.example.com" # Watch deployment node src/scripts/coolify-watch-deployment.js --uuid <app-uuid> # Restart application node src/scripts/coolify-restart-app.js --uuid <app-uuid> # Stop application node src/scripts/coolify-stop-app.js --uuid <app-uuid> ``` ### Environment Variables ```bash # Get environment variables node src/scripts/coolify-get-env.js --uuid <app-uuid> # Set environment variables node src/scripts/coolify-set-env.js \ --uuid <app-uuid> \ --key "API_KEY" \ --value "secret123" # Load from file node src/scripts/coolify-set-env.js \ --uuid <app-uuid> \ --file ".env.production" ``` ### Logs & Debugging ```bash # View logs node src/scripts/coolify-logs.js --uuid <app-uuid> # Follow logs node src/scripts/coolify-logs.js --uuid <app-uuid> --follow # Deployment report node src/scripts/coolify-deployment-report.js --uuid <app-uuid> ``` ## Library API ### CoolifyUtils Class ```javascript import { CoolifyUtils } from 'myaidev-method/src/lib/coolify-utils.js'; const coolify = new CoolifyUtils({ url: 'https://coolify.myai1.ai', apiKey: 'your-api-key' }); // Or auto-load from .env const coolify = new CoolifyUtils(); ``` ### Server Management ```javascript // List all servers const servers = await coolify.listServers(); // Get server details const server = await coolify.getServer(uuid); // Get server resources const resources = await coolify.getServerResources(uuid); // Find server by name const server = await coolify.findServerByName('production'); // Format for display const formatted = coolify.formatServerList(servers); ``` ### Project Management ```javascript // List projects const projects = await coolify.listProjects(); // Get project const project = await coolify.getProject(uuid); // Create project const newProject = await coolify.createProject({ name: 'My Project', description: 'Production applications' }); // Find by name const project = await coolify.findProjectByName('My Project'); ``` ### Application Management ```javascript // List applications const apps = await coolify.listApplications(); // Get application const app = await coolify.getApplication(uuid); // Create application const config = coolify.buildApplicationConfig({ name: 'myapp', repository: 'https://github.com/user/myapp', branch: 'main', buildPack: 'nixpacks', ports: '3000', domains: ['myapp.example.com'], projectUuid: 'project-uuid', serverUuid: 'server-uuid', envVars: { NODE_ENV: 'production', PORT: '3000' } }); const app = await coolify.createApplication(config); // Update application await coolify.updateApplication(uuid, { domains: ['app.example.com', 'www.app.example.com'] }); // Delete application await coolify.deleteApplication(uuid); ``` ### Deployment Operations ```javascript // Deploy application const deployment = await coolify.deployApplication(uuid, { force: true, // Force rebuild instant: false, // Instant deploy (skip queue) deployConfig: {} // Additional config }); // Deploy by tag const deployment = await coolify.deployApplication(null, { tag: 'v1.0.0' }); // Wait for deployment to complete const result = await coolify.waitForDeployment(uuid, { maxAttempts: 60, // 5 minutes interval: 5000 // Check every 5s }); if (result.success) { console.log('Deployment successful!'); } else { console.log(`Deployment failed: ${result.status}`); } // Get deployment logs const logs = await coolify.getDeploymentLogs(uuid); // Restart/Stop application await coolify.restartApplication(uuid); await coolify.stopApplication(uuid); ``` ### Environment Variables ```javascript // Get environment variables const envVars = await coolify.getEnvironmentVariables(uuid); // Update environment variables await coolify.updateEnvironmentVariables(uuid, { API_KEY: 'secret123', DATABASE_URL: 'postgresql://...', NODE_ENV: 'production' }); ``` ### Database Management ```javascript // List databases const databases = await coolify.listDatabases(); // Get database const db = await coolify.getDatabase(uuid); // Create database const dbConfig = coolify.buildDatabaseConfig({ name: 'myapp-db', type: 'postgresql', version: '16', projectUuid: 'project-uuid', serverUuid: 'server-uuid', publicPort: 5432, envVars: { POSTGRES_USER: 'admin', POSTGRES_PASSWORD: 'secure-password', POSTGRES_DB: 'myapp' } }); const db = await coolify.createDatabase(dbConfig); ``` ### Health & Status ```javascript // Health check const healthy = await coolify.healthCheck(); // System status const status = await coolify.getSystemStatus(); // Returns: { healthy, servers: {...}, projects: {...}, applications: {...} } ``` ## Deployment Patterns ### Pattern 1: Single Application ```javascript const coolify = new CoolifyUtils(); // 1. Verify connectivity const healthy = await coolify.healthCheck(); if (!healthy) throw new Error('Coolify not reachable'); // 2. Find or create project let project = await coolify.findProjectByName('Production'); if (!project) { project = await coolify.createProject({ name: 'Production' }); } // 3. Select server const servers = await coolify.listServers(); const server = servers.find(s => s.is_usable && s.is_reachable); // 4. Create application const config = coolify.buildApplicationConfig({ name: 'myapp', repository: 'https://github.com/user/myapp', branch: 'main', buildPack: 'nixpacks', projectUuid: project.uuid, serverUuid: server.uuid, ports: '3000', domains: ['myapp.example.com'] }); const app = await coolify.createApplication(config); // 5. Deploy const deployment = await coolify.deployApplication(app.uuid); // 6. Wait for completion const result = await coolify.waitForDeployment(app.uuid, { maxAttempts: 120, interval: 5000 }); console.log(result.success ? '✓ Deployed!' : '✗ Failed'); ``` ### Pattern 2: Full Stack with Database ```javascript const coolify = new CoolifyUtils(); // Deploy database first const dbConfig = coolify.buildDatabaseConfig({ name: 'myapp-db', type: 'postgresql', version: '16', projectUuid: projectUuid, serverUuid: serverUuid }); const db = await coolify.createDatabase(dbConfig); // Wait for database to be ready await new Promise(resolve => setTimeout(resolve, 30000)); // Get database connection string const connectionString = db.internal_db_url; // Deploy application with database connection const appConfig = coolify.buildApplicationConfig({ name: 'myapp', repository: 'https://github.com/user/myapp', projectUuid: projectUuid, serverUuid: serverUuid, envVars: { DATABASE_URL: connectionString, NODE_ENV: 'production' } }); const app = await coolify.createApplication(appConfig); await coolify.deployApplication(app.uuid); ``` ### Pattern 3: Multi-Environment ```javascript const coolify = new CoolifyUtils(); const environments = [ { name: 'staging', branch: 'develop', domain: 'staging.app.com' }, { name: 'production', branch: 'main', domain: 'app.com' } ]; for (const env of environments) { const config = coolify.buildApplicationConfig({ name: `myapp-${env.name}`, repository: 'https://github.com/user/myapp', branch: env.branch, domains: [env.domain], projectUuid: projectUuid, serverUuid: serverUuid, envVars: { NODE_ENV: env.name } }); const app = await coolify.createApplication(config); await coolify.deployApplication(app.uuid); console.log(`✓ Deployed ${env.name} environment`); } ``` ## Agent Integration Examples ### Example 1: Agent-Driven Deployment **User:** "Deploy my Next.js app to Coolify" **Agent workflow (using utilities):** ```javascript // 1. Read package.json to detect Next.js const packageJson = JSON.parse(await readFile('package.json')); const isNextJS = packageJson.dependencies?.next; // 2. Connect to Coolify const coolify = new CoolifyUtils(); await coolify.healthCheck(); // Verify connectivity // 3. List available servers const servers = await coolify.listServers(); const usableServers = servers.filter(s => s.is_usable && s.is_reachable); // 4. Prompt user for server (if multiple) const selectedServer = usableServers[0]; // Or ask user // 5. Build configuration const config = coolify.buildApplicationConfig({ name: 'nextjs-app', repository: await detectGitRemote(), // Or prompt branch: 'main', buildPack: 'nixpacks', projectUuid: await getOrCreateProject(), serverUuid: selectedServer.uuid, ports: '3000', domains: [] // Or prompt for domain }); // 6. Create and deploy const app = await coolify.createApplication(config); await coolify.deployApplication(app.uuid); // 7. Monitor deployment const result = await coolify.waitForDeployment(app.uuid); // 8. Report to user if (result.success) { console.log(`✓ Deployed successfully!`); console.log(`URL: ${app.fqdn || 'Configure domain in Coolify'}`); } else { console.log(`✗ Deployment failed: ${result.status}`); const logs = await coolify.getDeploymentLogs(app.uuid); console.log('Logs:', logs); } ``` ### Example 2: Multi-Agent Orchestration **User:** "Set up full production environment with database and Redis" **Main agent delegates to subagents:** ```markdown Main Agent (orchestration) ├─ Database Agent │ └─ Deploy PostgreSQL database │ └─ Return connection string ├─ Cache Agent │ └─ Deploy Redis cache │ └─ Return connection string ├─ Backend Agent (waits for DB + Redis) │ └─ Deploy API with connections │ └─ Run migrations │ └─ Return API URL └─ Frontend Agent (waits for Backend) └─ Deploy frontend with API URL └─ Configure domains └─ Return app URL ``` Each subagent uses `CoolifyUtils` independently with focused responsibilities. ## Security Best Practices ### Credential Management ```bash # .env file (never commit) COOLIFY_URL=https://coolify.myai1.ai COOLIFY_API_KEY=1|xxxxxxxxxxxx # .env.example (commit this) COOLIFY_URL=https://your-coolify-instance.com COOLIFY_API_KEY=your_api_key_here ``` ### Permission Scoping Agent frontmatter limits tool access: ```yaml --- name: coolify-deploy tools: Bash, Read allowed-directories: [".env", "src/scripts/coolify-*.js"] forbidden-commands: ["rm -rf", "sudo", "chmod 777"] --- ``` ### Production Gates Always confirm production deployments: ```javascript if (environment === 'production') { const confirm = await promptUser('Deploy to PRODUCTION? (yes/no)'); if (confirm !== 'yes') { console.log('Deployment cancelled'); process.exit(0); } } ``` ## Troubleshooting ### Connection Issues ```bash # Test API connectivity curl -H "Authorization: Bearer $COOLIFY_API_KEY" \ https://coolify.myai1.ai/api/v1/servers # Check credentials cat .env | grep COOLIFY # Verify status npm run coolify:status ``` ### Deployment Failures ```bash # Check logs node src/scripts/coolify-logs.js --uuid <app-uuid> # Get detailed report node src/scripts/coolify-deployment-report.js --uuid <app-uuid> # Retry deployment node src/scripts/coolify-deploy-app.js --uuid <app-uuid> --force ``` ### Common Errors **"API key invalid"** - Regenerate API key in Coolify - Update `.env` file - Verify no extra spaces in `.env` **"Server not reachable"** - Check server status in Coolify - Verify SSH connectivity - Check firewall rules **"Build failed"** - Review build logs - Check repository accessibility - Verify build pack compatibility ## Performance Optimization ### Caching Nixpacks automatically caches dependencies: - Node.js: `node_modules` cached - Python: Virtual env cached - Docker: Layer caching enabled ### Parallel Builds Configure concurrent builds in server settings: ```javascript // Default: 2 concurrent builds per server // Increase for faster multi-app deployments ``` ### Resource Allocation Set appropriate limits: ```javascript const config = coolify.buildApplicationConfig({ // ... other config settings: { memory_limit: '512m', cpu_limit: '1.0' } }); ``` ## Contributing To extend the Coolify agent: 1. Add functions to `src/lib/coolify-utils.js` 2. Create scripts in `src/scripts/coolify-*.js` 3. Update agent documentation 4. Add npm scripts to `package.json` ## Resources - [Coolify Documentation](https://coolify.io/docs) - [Coolify API Reference](https://coolify.io/docs/api-reference) - [Claude Code 2.0 Best Practices](https://docs.claude.com/en/docs/claude-code) - [Agent Engineering Guide](https://www.anthropic.com/engineering/claude-code-best-practices) ## License MIT - See LICENSE file for details