AgentDAO Developers

    Getting Started

    Agent Sites

    Core Skills

    API Reference

    Integrations

    Frameworks

    Guides

    Examples

    Platform Features

    AgentDAO ships a full template platform for agent landers, a developers portal on every deployed domain, and a public key hub on this control plane. This page summarizes the latest features and how they connect.

    Template platform

    • Dashboard → Templates — browse catalog, clone to a deployment, edit drafts, preview, publish live to Cloudflare KV.
    • 12 category landers (content, developer, finance, etc.) plus AgentDAO retro and a dedicated /developers page template.
    • MCP-assisted edits — propose → review → apply → publish. See Template MCP guide.
    • Publish writes homepage KV, domain:developers, and default legal pages (privacy, terms, contact).

    Developers page & API keys

    Every deployed agent exposes https://{your-domain}/developers with a 4-step inline flow:

    1. You — name and email (required first)
    2. Tier — test (free, 10 calls/day) or production (ADAO)
    3. Review — confirm details
    4. Go — test key issued via POST /api/claim-key (worker → control plane)

    Production keys use PayDirect checkout. Keys are stored in developer_api_keys with key_tier (test | production).

    Key Portal (control plane)

    • /keys — public hub for guests (claim test key, prefilled from agent site query params).
    • Dashboard → Key Portal — same flow while signed in; copy shareable link for your consumers.
    • Dashboard → API Keys — manage all keys per agent; create test or production keys when logged in.
    GET  /api/public/keys?email=&domain=     # usage status (no secret)
    POST /api/public/keys                     # claim test key
    POST /api/agent/claim-key                 # worker proxy (same as above)
    POST /api/agent/execute                   # rate limits + billing

    Legal pages & contact (all templates)

    Every published agent includes footer links and KV pages:

    • /privacy — privacy policy
    • /terms — terms of service
    • /contact — contact page

    Contact uses the Domain Directory inquire widget only (not offer/partner). Leads post to Domain Directory → VNOC:

    <script src="https://www.domaindirectory.com/widget/dd-forms.js" defer></script>
    <div data-dd-form="inquire" data-dd-domain="yourdomain.com"></div>

    LLM provider interop

    Multi-provider chat via skill llm.chat (OpenAI, Claude, Gemini) with install surfaces on every live agent.

    • Key order: agent deployment keys → developer provider keys → .env fallback
    • GET /openapi.json and GET /.well-known/mcp.json on the agent domain
    • Dashboard → My Agents → LLM Provider Interop for defaults, fallbacks, and test chat

    Full guide: LLM Provider Interop

    Dynamic external API keys

    Store named credentials per deployment (OpenAI, Anthropic, Google, SocialAgent, ContentAgent, etc.) in external_api_credentials. Skills and proxies resolve keys at runtime without redeploying the worker.

    Database migrations

    Run on Neon (see docs/migrations-to-run.md):

    • 0056_cf_agent_pages.sql
    • 0057_template_platform.sql
    • 0058_template_mcp_chat.sql
    • 0059_api_key_tier.sql
    • 0062_llm_interop.sql
    • 0063_seed_llm_chat_skill.sql

    Go-live checklist

    1. Apply migrations 0056–0063
    2. Deploy control plane (this app) to production
    3. Publish template from dashboard (or repair-live)
    4. Upgrade worker if sitemap should list legal URLs
    5. Test /developers claim-key and /contact inquire form

    LLM Provider Interop

    AgentDAO agents can run LLM workloads through a single skill (llm.chat) with automatic routing across OpenAI, Claude (Anthropic), and Gemini (Google). Install surfaces let external clients connect without custom SDK work.

    Key resolution order

    1. Agent deployment keys (external_api_credentials in dashboard)
    2. Developer provider keys (Dashboard → APIs / provider settings)
    3. .env fallback: OPENAI_API_KEY, ANTHROPIC_API_KEY, GOOGLE_AI_API_KEY

    Execute LLM chat

    POST https://{agent-domain}/api/execute
    X-API-Key: YOUR_KEY
    
    {
      "intent": "llm.chat",
      "input": {
        "messages": [
          { "role": "user", "content": "Hello" }
        ],
        "providerPreference": "openai"
      }
    }

    Attach skill llm.chat to the agent. Configure default provider and fallbacks under My Agents → LLM Provider Interop.

    Install surfaces (per live agent)

    • GET https://{domain}/openapi.json — OpenAPI for GPT Actions / HTTP clients
    • GET https://{domain}/.well-known/mcp.json — MCP-style tool manifest (Claude, Cursor)
    • GET https://{domain}/.well-known/agent.json — A2A agent card

    Control plane mirrors: /api/agent/interop/openapi?domain=... and /api/agent/interop/mcp?domain=...

    Environment

    • LLM_INTEROP_ENABLED=true
    • LLM_ENV_FALLBACK_ENABLED=true (use .env when no agent/user key)
    • LLM_DEFAULT_MODEL_OPENAI, LLM_DEFAULT_MODEL_ANTHROPIC, LLM_DEFAULT_MODEL_GOOGLE

    See lib/llm/README.md in the repo for the full request/response contract.

    Getting Started

    Learn how to create your first agent, claim a URL, and deploy your solution in minutes.

    1. Sign up and log in to your AgentDAO developer account.
    2. Claim a URL or select an existing one.
    3. Use the No-Code Agent Builder or Advanced Mode to create your agent.
    4. Test and deploy your agent. Get a live URL instantly.
    5. Monitor, update, and manage your agents from your dashboard.

    Analytics Service

    AgentDAO includes a built-in analytics service that automatically tracks important events across all agents and skills. The analytics system is performance-optimized and privacy-friendly.

    Key Features

    • 🔄 Automatic Tracking: All agent activities, skill usage, and user actions are automatically tracked
    • 📦 Performance Optimized: Non-blocking, batch-processed analytics with rate limiting
    • 🛡️ Privacy Friendly: Only tracks important business events, not every interaction
    • 📊 Rich Insights: Detailed analytics dashboard for admins and users
    • 🔗 Platform Integration: Centralized analytics across all deployed agents

    Using Analytics in Your Code

    The analytics service is automatically available in all skills. You can also track custom events:

    import { trackEvent, trackSkillUsage, trackApiCall } from '@agentdao/core';
    
    // Track skill usage
    await trackSkillUsage('WebSearchSkill', 'my-agent-123', {
      query: 'AI trends 2024',
      provider: 'google'
    });
    
    // Track API calls
    await trackApiCall('web_search', true, 1500, {
      skill: 'WebSearchSkill',
      resultCount: 10
    });
    
    // Track custom events
    await trackEvent({
      event_type: 'user_action',
      event_name: 'button_click',
      metadata: { button: 'submit', page: 'dashboard' }
    });

    Analytics Dashboard

    Access your analytics data through the platform dashboard:

    • User Analytics: Track user signups, logins, and activity patterns
    • Agent Analytics: Monitor agent creation, deployment, and usage
    • Skill Analytics: Track skill usage, performance, and error rates
    • Challenge Analytics: Monitor challenge submissions and awards
    • Admin Analytics: Comprehensive admin dashboard with system health metrics

    Analytics API Endpoints

    Access analytics data programmatically:

    # Get analytics data
    GET /api/dashboard/analytics?timeRange=30d&realTime=true
    
    # Track an event
    POST /api/analytics/track
    {
      "event_type": "user_action",
      "event_name": "user_signup",
      "metadata": { "source": "github" }
    }
    
    # Batch analytics (for npm package)
    POST /api/analytics/batch
    {
      "events": [
        {
          "event_type": "skill_usage",
          "event_name": "skill_used",
          "skill_name": "WebSearchSkill",
          "metadata": { "query": "test" }
        }
      ]
    }

    Performance & Privacy

    The analytics system is designed to be lightweight and privacy-friendly:

    • Automatic Cleanup: Old data is automatically deleted after 90 days
    • Rate Limiting: Maximum 10 events per user per minute

    Web3Subscription (Enhanced)

    AgentDAO Web3Subscription supports multi-token and native ETH/BNB payments. Use FlawlessWeb3Subscription so users can pay with ADAO, USDC, DAI, ETH, BNB, or any ERC-20 token.

    Quick start

    1. Install:
      pnpm add @agentdao/core wagmi viem ethers
    2. Use the component:
      import { FlawlessWeb3Subscription } from '@agentdao/core/ui/FlawlessWeb3Subscription';
      
      <FlawlessWeb3Subscription
        agentId="my-agent"
        planId="premium"
        billingPeriod="monthly"
        amount="1"
        recipient="0xYourPlatformOrContractAddress"
        tokens={tokens}
        plans={plansObject}
        onSuccess={handleSuccess}
        onError={handleError}
      />

    Verify payment API

    After wallet payment, call POST /api/agent/verify-payment to verify on-chain and activate the subscription.

    For production, verify amount, recipient, sender, and token on-chain before activating access.

    API Overview

    AgentDAO provides a RESTful API for managing agents, keys, and integrations. All endpoints are prefixed with /api/dashboard/.

    • Base URL: https://developers.agentdao.com/api/dashboard
    • All endpoints require authentication via session cookie.
    • See the API Reference for full details.

    Authentication

    All API requests require an active session. The session is managed via cookies and is automatically handled when you're logged in through the dashboard.

    Session Management

    Your session is automatically created when you log in through the dashboard. The session cookie is required for all API requests.

    Note: Never expose your session cookie. Keep it secure and never share it.

    API Key Authentication

    For programmatic access to AgentDAO APIs, you can generate API keys from your API Management Dashboard. API keys are required for all protected endpoints and are scoped to specific domains.

    1. Go to Dashboard → APIs and click Create API Key.
    2. Select the domain you want to generate a key for.
    3. Copy your new API key and keep it secure.

    Using Your API Key

    Include your API key in the Authorization header of every request:

    Authorization: Bearer YOUR_API_KEY

    Example with curl:

    curl -H "Authorization: Bearer YOUR_API_KEY" https://developers.agentdao.com/api/agents

    Example with JavaScript:

    fetch('https://developers.agentdao.com/api/agents', {
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY'
      }
    })

    Security Best Practices

    • Never share your API key publicly or commit it to version control.
    • Rotate your API keys regularly.
    • Delete unused keys from the dashboard.

    Key API Endpoints

    • List Agent Projects: GET /api/dashboard/agent-projects
    • Create Agent Project: POST /api/dashboard/agent-projects
    • Update Agent Project: PUT /api/dashboard/agent-projects/:id
    • Delete Agent Project: DELETE /api/dashboard/agent-projects/:id
    • Test Agent: POST /api/dashboard/test-agent
    • Deploy Agent: POST /api/dashboard/deploy-agent
    • Run Agent: POST /api/dashboard/run-agent
    • Agent Logs: GET /api/agent-logs
    • Agent Metrics: GET /api/agent-metrics
    • Submit Agent: POST /api/dashboard/submit-agent
    • List Submitted Agents: GET /api/dashboard/submitted-agents

    Agent Execution

    AgentDAO now provides real agent execution capabilities. Your agents are executed in a sandboxed environment with full access to their code and configuration.

    Real Agent Execution

    Unlike mock implementations, AgentDAO now actually executes your agent code:

    • Code Execution: Your agent code runs in a secure sandboxed environment
    • Real Input/Output: Agents process actual user input and return real results
    • Execution Logging: All executions are logged with timing and metadata
    • Error Handling: Proper error capture and reporting
    • Performance Tracking: Execution time and success rate monitoring

    Test Agent Endpoint

    The test endpoint now actually executes your agent with test input:

    POST /api/dashboard/test-agent
    Content-Type: application/json
    
    {
      "projectId": "YOUR_PROJECT_ID",
      "testInput": "Hello, this is a test input"
    }

    Response:

    {
      "success": true,
      "message": "Agent test completed successfully",
      "output": { "message": "Hello, this is a test input" },
      "executionTime": 125,
      "testInput": "Hello, this is a test input"
    }

    Run Agent Endpoint

    The run endpoint executes your agent and streams real-time results:

    POST /api/dashboard/run-agent
    Content-Type: application/json
    
    {
      "projectId": "YOUR_PROJECT_ID",
      "input": "User input here"
    }

    Streaming Response:

    {"type": "log", "content": "Starting agent execution..."}
    {"type": "log", "content": "Executing agent code..."}
    {"type": "output", "content": "{\"result\": \"Agent response\"}"}
    {"type": "log", "content": "Execution completed successfully in 150ms."}

    Agent Code Requirements

    Your agent code should follow these patterns:

    // Option 1: Export a main function
    async function main(input, config) {
      // Your agent logic here
      return { message: "Hello from agent!", input };
    }
    
    // Option 2: Export a handler function
    async function handler(input, config) {
      // Your agent logic here
      return { message: "Hello from agent!", input };
    }
    
    // Option 3: Direct execution
    // Your agent logic here
    // The result will be automatically returned

    ServiceBot Integration

    Learn how to integrate AgentDAO with ServiceBot to create monetized AI agents for your domains.

    ServiceBot MVP Flow

    Create a complete monetization strategy using ServiceBot and AgentDAO:

    1. User Registration: Users register via ServiceBot agent with email and domain
    2. Domain Analysis: AgentDAO analyzes the domain using core skills
    3. Web3 Payment: Users pay via Web3 integration with AgentDAO API
    4. Email Confirmation: Payment confirmation sent via email
    5. Dashboard Access: Users get access to manage their domains
    6. Agent Configuration: Configure chat agents for each domain
    7. Integration Options: JavaScript embed or API integration

    Implementation Steps

    Here's how to implement the ServiceBot integration:

    // 1. Create ServiceBot Agent
    const servicebotAgent = {
      name: "AgentDAO Registration Agent",
      skills: ["domain_analysis", "payment_processing", "email_notifications"],
      webhook_endpoints: ["/register", "/analyze", "/payment"]
    };
    
    // 2. Domain Analysis Service
    const domainAnalysis = {
      endpoint: "/api/domain-analysis",
      skills: ["web_search", "content_analysis", "business_classification"]
    };
    
    // 3. Payment Integration
    const paymentIntegration = {
      provider: "AgentDAO API",
      endpoint: "/api/agents/{agentId}/pricing-config",
      web3_support: true
    };
    
    // 4. Email Service
    const emailService = {
      provider: "AgentDAO Email Service",
      templates: ["payment_confirmation", "welcome", "setup_guide"]
    };

    API Integration

    Use the AgentPricingSDK to integrate with AgentDAO:

    import { AgentPricingSDK } from '@agentdao/core';
    
    // Initialize SDK
    const pricingSDK = new AgentPricingSDK(agentId, {
      baseUrl: 'https://developers.agentdao.com',
      apiKey: 'your_api_key'
    });
    
    // Get pricing configuration
    const config = await pricingSDK.getPricingConfig();
    
    // Process payment
    const payment = await pricingSDK.processPayment({
      plan: 'premium',
      amount: 100,
      token: 'ADAO',
      userWallet: '0x...'
    });
    
    // Send confirmation email
    await pricingSDK.sendEmail({
      template: 'payment_confirmation',
      to: userEmail,
      data: { payment, domain }
    });

    Domain Management Dashboard

    Create a simple dashboard for users to manage their domains:

    // Dashboard API endpoints
    GET /api/user/domains          // List user domains
    POST /api/user/domains         // Add new domain
    PUT /api/user/domains/:id      // Update domain config
    DELETE /api/user/domains/:id   // Remove domain
    
    // Domain configuration
    {
      id: "domain_id",
      domain: "example.com",
      status: "active",
      payment_status: "paid",
      agent_config: {
        enabled: true,
        chat_widget: true,
        api_integration: false
      },
      analytics: {
        visitors: 1500,
        interactions: 250,
        revenue: 100
      }
    }

    Integration Options

    Users can integrate the chat agent in two ways:

    1. JavaScript Embed

    <script src="https://developers.agentdao.com/embed.js"></script>
    <script>
      AgentDAO.init({
        agentId: 'your_agent_id',
        domain: 'your_domain.com',
        position: 'bottom-right'
      });
    </script>

    2. API Integration

    const response = await fetch('/api/agents/chat', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        agentId: 'your_agent_id',
        message: userMessage,
        context: { domain: 'your_domain.com' }
      })
    });

    AgentPricingSDK

    The AgentPricingSDK provides a comprehensive interface for managing agent pricing, payments, and monetization features.

    Installation

    npm install @agentdao/core
    # or
    yarn add @agentdao/core

    Basic Usage

    import { AgentPricingSDK } from '@agentdao/core';
    
    // Initialize SDK
    const pricingSDK = new AgentPricingSDK(agentId, {
      baseUrl: 'https://developers.agentdao.com',
      apiKey: 'your_api_key'
    });
    
    // Get complete pricing configuration
    const config = await pricingSDK.getPricingConfig();
    console.log('Pricing Plans:', config.pricing.pricing_plans);
    console.log('Accepted Tokens:', config.pricing.accepted_tokens);

    Available Methods

    Pricing Methods

    • getPricingConfig() - Complete configuration
    • getPricingPlans() - Available pricing plans
    • getAcceptedTokens() - Supported tokens
    • getEshTokenAddresses() - ESH token addresses
    • getEshTokenMetadata() - ESH token metadata

    Agent Methods

    • getAgentInfo() - Agent details
    • isAvailableForHire() - Availability status
    • getUsageLimits() - Usage restrictions
    • getRateLimits() - Rate limiting info
    • getIntegrationInfo() - Integration details

    Feature Methods

    • getEnabledFeatures() - Enabled features
    • hasFeature(featureId) - Check feature
    • getTags() - Agent tags
    • getCategories() - Agent categories
    • getSupportedLanguages() - Supported languages

    Validation Methods

    • validateAccess(userId, token) - Access validation

    Advanced Usage

    // Check if agent has specific feature
    const hasWeb3 = await pricingSDK.hasFeature('web3-subscription');
    if (hasWeb3) {
      console.log('Agent supports Web3 subscriptions');
    }
    
    // Validate user access
    const access = await pricingSDK.validateAccess(userId, token);
    if (access.valid) {
      console.log('User has access to this agent');
    }
    
    // Get specific pricing plan
    const plans = await pricingSDK.getPricingPlans();
    const premiumPlan = plans.premium;
    console.log('Premium plan:', premiumPlan);
    
    // Check accepted tokens
    const tokens = await pricingSDK.getAcceptedTokens();
    if (tokens.ADAO) {
      console.log('Agent accepts ADAO tokens');
    }

    Error Handling

    try {
      const config = await pricingSDK.getPricingConfig();
      console.log('Config loaded:', config);
    } catch (error) {
      if (error.message.includes('Agent not found')) {
        console.error('Agent does not exist');
      } else if (error.message.includes('Access denied')) {
        console.error('API key does not have access to this agent');
      } else {
        console.error('Unexpected error:', error.message);
      }
    }

    Factory Function

    import { createAgentPricingSDK } from '@agentdao/core';
    
    // Create SDK using factory function
    const pricingSDK = createAgentPricingSDK(agentId, {
      baseUrl: 'https://developers.agentdao.com',
      apiKey: 'your_api_key'
    });
    
    // Use the same way as constructor
    const config = await pricingSDK.getPricingConfig();

    Agent Logs & Metrics

    AgentDAO provides comprehensive logging and metrics for monitoring your agent performance and debugging issues.

    Agent Logs

    Get real-time logs of your agent executions:

    GET /api/agent-logs

    Response:

    [
      {
        "time": "2:30:45 PM",
        "type": "success",
        "message": "Agent executed successfully",
        "agentName": "My Agent"
      },
      {
        "time": "2:30:40 PM", 
        "type": "error",
        "message": "Agent execution failed",
        "agentName": "My Agent"
      }
    ]

    Agent Metrics

    Get performance metrics for your agents:

    GET /api/agent-metrics

    Response:

    [
      {
        "label": "Total Agents",
        "value": "5",
        "change": "+5"
      },
      {
        "label": "Deployed Agents", 
        "value": "3",
        "change": "+3"
      },
      {
        "label": "Active Agents",
        "value": "2", 
        "change": "+2"
      },
      {
        "label": "Total Executions",
        "value": "150",
        "change": "+150"
      },
      {
        "label": "Avg Execution Time",
        "value": "125.50ms",
        "change": "+125.50ms"
      },
      {
        "label": "Success Rate",
        "value": "98.5%",
        "change": "N/A"
      }
    ]

    Creating Logs

    You can also create custom logs for your agents:

    POST /api/agent-logs
    Content-Type: application/json
    
    {
      "agentId": "YOUR_AGENT_ID",
      "logType": "info",
      "message": "Custom log message"
    }

    Log Types

    • info: General information messages
    • success: Successful operations
    • warning: Warning messages
    • error: Error messages

    Claiming a URL Asset

    When you claim a URL asset, the following happens:

    • You click the Claim URL button for an available URL in the dashboard.
    • The frontend sends a POST request to /api/marketplace/claim with the URL's ID.
    • The backend verifies your authentication and checks if the URL is still available.
    • If available, the URL's status is updated to claimed, you are set as the claimer, and the claim time is recorded.
    • You are awarded points based on the URL's estimated value (1 point per $10).
    • The claimed URL disappears from the available list and appears in your claimed URLs tab.
    • You see a success message with the number of points earned.
    Example: Claim a URL
    POST /api/marketplace/claim
    Content-Type: application/json
    
    {
      "urlId": 123
    }
    Success Response
    {
      "success": true,
      "url": {
        "id": 123,
        "url": "ai.agentdao.com",
        "status": "claimed",
        ...
      },
      "pointsAwarded": 15,
      "message": "Successfully claimed ai.agentdao.com and earned 15 points!"
    }
    Error Response
    {
      "error": "URL not available or already claimed"
    }

    Once claimed, you can build and submit agents on top of your URLs directly from the dashboard.

    Agent Lifecycle

    1. Create: Define your agent (no-code or advanced).
    2. Test: Validate your agent's logic and integration.
    3. Deploy: Launch your agent and get a live URL.
    4. Monitor: Track usage, logs, and performance in your dashboard.
    5. Update: Edit and redeploy your agent as needed.

    Code Examples

    Here are some quick examples for using the API:

    Create Agent Project (JavaScript)

    fetch("/api/dashboard/agent-projects", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: "My Agent",
          description: "A helpful agent",
          template: "basic",
          files: {
            "index.js": "// Your agent code here"
          },
          config: {
            ai_provider: "openai",
            model: "gpt-3.5-turbo",
            environment_vars: {},
            dependencies: []
          }
        })
      })
      .then(res => res.json())
      .then(data => console.log(data));

    Test Agent (Python)

    import requests
    
    resp = requests.post(
      "/api/dashboard/test-agent",
      json={
        "projectId": "YOUR_PROJECT_ID",
        "testInput": "Hello, this is a test input"
      }
    )
    print(resp.json())

    Run Agent (JavaScript)

    fetch("/api/dashboard/run-agent", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          projectId: "YOUR_PROJECT_ID",
          input: "User input here"
        })
      })
      .then(res => {
        const reader = res.body.getReader();
        const decoder = new TextDecoder();
        
        return new ReadableStream({
          start(controller) {
            function push() {
              reader.read().then(({done, value}) => {
                if (done) {
                  controller.close();
                  return;
                }
                
                const chunk = decoder.decode(value);
                const lines = chunk.split("\n").filter(line => line.trim());
                
                lines.forEach(line => {
                  try {
                    const data = JSON.parse(line);
                    console.log(data);
                  } catch (e) {
                    // Ignore invalid JSON
                  }
                });
                
                push();
              });
            }
            
            push();
          }
        });
      });

    Best Practices

    Agent Development

    • Test Thoroughly: Use the real test endpoint to validate your agent logic before deployment
    • Handle Errors: Implement proper error handling in your agent code
    • Optimize Performance: Monitor execution times and optimize slow operations
    • Use Environment Variables: Store sensitive data like API keys in environment variables
    • Follow Security Best Practices: Never expose sensitive data in your agent responses

    Monitoring & Logging

    • Monitor Logs: Regularly check agent logs for errors and performance issues
    • Track Metrics: Use the metrics endpoint to monitor agent performance over time
    • Set Up Alerts: Create alerts for high error rates or slow execution times
    • Log Important Events: Use custom logging for important agent events

    API Usage

    • Keep API Keys Secure: Never expose them in public code or client-side applications
    • Follow Rate Limits: Implement exponential backoff for rate-limited requests
    • Handle Errors Gracefully: Implement proper error handling for all API calls
    • Use Streaming: Use the streaming run-agent endpoint for real-time responses

    Frequently Asked Questions

    General Questions

    • How do I get an API key?
      Create and manage API keys in your dashboard under API Management.
    • Can I use the API without coding?
      Yes! Use the No-Code Agent Builder in your dashboard.
    • Where can I find more examples?
      See the API Reference for more code samples.
    • How do I get support?
      See below for support options.

    Agent Execution

    • Is agent execution real or simulated?
      AgentDAO now provides real agent execution. Your code actually runs in a sandboxed environment.
    • How do I test my agent?
      Use the /api/dashboard/test-agent endpoint with your project ID and test input.
    • How do I run my agent?
      Use the /api/dashboard/run-agent endpoint for real-time execution with streaming results.
    • What programming languages are supported?
      Currently JavaScript/Node.js is supported for agent execution.

    Monitoring & Logs

    • How do I view agent logs?
      Use the /api/agent-logs endpoint to get execution logs.
    • How do I get performance metrics?
      Use the /api/agent-metrics endpoint for detailed metrics.
    • Can I create custom logs?
      Yes, use POST /api/agent-logs to create custom log entries.
    • What log types are available?
      info, success, warning, and error log types are supported.

    Support & Community

    Error Handling

    Learn how to handle errors gracefully in your AgentDAO integrations.

    Common Error Types

    • AuthenticationError - Invalid or expired API key
    • RateLimitError - Too many requests
    • ValidationError - Invalid request parameters
    • TimeoutError - Request timed out

    Error Handling Example

    try {
      const response = await agent.execute({
        input: userInput,
        options: {
          timeout: 5000,
          retries: 3
        }
      });
    } catch (error) {
      if (error.code === 'TIMEOUT') {
        // Handle timeout
      } else if (error.code === 'RATE_LIMIT') {
        // Handle rate limit
      } else {
        // Handle other errors
      }
    }

    AgentBridge

    AgentBridge is a powerful tool that enables seamless integration between different AI agents and services. It provides a unified interface for managing agent interactions, data flow, and state management.

    Key Features

    • Multi-Agent Orchestration - Coordinate multiple agents to work together on complex tasks
    • State Management - Maintain and share state between agents
    • Event System - Handle asynchronous events and agent communication
    • Data Pipeline - Process and transform data between agents
    • Error Recovery - Automatic retry and fallback mechanisms

    Basic Setup

    import { AgentBridge } from '@agentdao/bridge';
    
    const bridge = new AgentBridge({
      agents: {
        assistant: new AssistantAgent(),
        researcher: new ResearchAgent(),
        writer: new WriterAgent()
      },
      config: {
        maxRetries: 3,
        timeout: 30000
      }
    });

    Agent Communication

    // Define a workflow
    bridge.defineWorkflow('research-and-write', async (context) => {
      // Research phase
      const research = await context.agents.researcher.execute({
        query: context.input.topic
      });
    
      // Writing phase
      const article = await context.agents.writer.execute({
        content: research.data,
        format: 'blog-post'
      });
    
      return article;
    });
    
    // Execute the workflow
    const result = await bridge.executeWorkflow('research-and-write', {
      topic: 'AI Ethics'
    });

    State Management

    // Set state
    bridge.setState('user-preferences', {
      language: 'en',
      tone: 'professional'
    });
    
    // Get state
    const preferences = bridge.getState('user-preferences');
    
    // Subscribe to state changes
    bridge.subscribe('user-preferences', (newState) => {
      console.log('Preferences updated:', newState);
    });

    Event Handling

    // Register event handlers
    bridge.on('agent:error', async (error) => {
      console.error('Agent error:', error);
      await notifyAdmin(error);
    });
    
    bridge.on('workflow:complete', (result) => {
      console.log('Workflow completed:', result);
    });
    
    // Emit events
    bridge.emit('custom:event', {
      type: 'notification',
      message: 'Task completed'
    });

    Data Pipeline

    // Define data transformations
    bridge.defineTransform('clean-text', (text) => {
      return text.trim().toLowerCase();
    });
    
    bridge.defineTransform('format-json', (data) => {
      return JSON.stringify(data, null, 2);
    });
    
    // Use in workflow
    bridge.defineWorkflow('process-data', async (context) => {
      const rawData = await context.agents.collector.getData();
      const cleaned = await context.transform('clean-text', rawData);
      const formatted = await context.transform('format-json', cleaned);
      return formatted;
    });

    Error Recovery

    // Configure retry strategy
    bridge.configureRetry({
      maxAttempts: 3,
      backoff: 'exponential',
      maxDelay: 5000
    });
    
    // Define fallback behavior
    bridge.defineFallback('research-agent', async (error) => {
      if (error.code === 'TIMEOUT') {
        return await context.agents.backupResearcher.execute(context.input);
      }
      throw error;
    });

    Pricing Integration

    AgentDAO provides a comprehensive pricing integration system that allows deployed agents to fetch and use pricing plans configured in the platform. This enables seamless monetization of your deployed agents with centralized pricing management.

    🚀 Quick Start

    Get started with pricing integration in your deployed agent:

    import { AgentPricingSDK } from '@agentdao/core';
    
    // Initialize with your agent ID
    const agentId = 123; // Replace with your actual agent ID
    const pricingSDK = new AgentPricingSDK(agentId);
    
    // Fetch pricing configuration
    const config = await pricingSDK.getPricingConfig();
    console.log('Pricing plans:', config.pricing.pricing_plans);

    🔑 Key Features

    • Centralized Pricing: Configure pricing plans in AgentDAO platform, use them in deployed agents
    • Real-time Updates: Pricing changes are immediately available to deployed agents
    • Access Control: Built-in validation for user plans and tokens
    • Usage Limits: Enforce monthly requests, rate limiting, and feature restrictions
    • Payment Integration: Calculate platform fees and developer revenue automatically
    • Multi-token Support: Accept ADAO, ETH, USDC, and other tokens

    📋 API Endpoints

    Access pricing configuration via REST API:

    GET /api/agents/{agentId}/pricing-config

    Returns complete pricing configuration including plans, tokens, limits, and features.

    Get agent info (claimed URL and API key):

    GET /api/dashboard/agent-info?agentId={agentId}

    Returns the claimed URL from agent submissions and the matching API key for the domain.

    💳 Access Control Example

    Implement access control in your deployed agent:

    // Check if user has access
    const accessResult = await pricingSDK.validateAccess('monthly', 'ADAO');
    
    if (accessResult.hasAccess) {
      console.log('User has access to the agent');
      // Proceed with agent functionality
    } else {
      console.log('Access denied:', accessResult.reason);
      // Redirect to pricing page or show upgrade message
    }

    📊 Usage Limits Example

    Enforce usage limits based on your configuration:

    // Check usage limits
    const usageLimits = await pricingSDK.getUsageLimits();
    const rateLimits = await pricingSDK.getRateLimits();
    
    // Check against your database
    const userUsage = await getUserUsageFromDatabase(userId);
    
    if (usageLimits.requests_per_month && userUsage.requests >= usageLimits.requests_per_month) {
      throw new Error('Monthly request limit exceeded');
    }
    
    if (rateLimits.requests_per_minute && userUsage.recentRequests >= rateLimits.requests_per_minute) {
      throw new Error('Rate limit exceeded');
    }

    🎯 Feature-Based Access

    Enable/disable features based on plan tiers:

    // Check if specific features are enabled
    const hasAnalytics = await pricingSDK.hasFeature('analytics');
    const hasPrioritySupport = await pricingSDK.hasFeature('priority_support');
    
    if (hasAnalytics) {
      enableAnalytics();
    }
    
    if (hasPrioritySupport) {
      enablePrioritySupport();
    }

    💰 Payment Processing

    Process payments using your configured pricing:

    // Process payment
    const config = await pricingSDK.getPricingConfig();
    const plans = await pricingSDK.getPricingPlans();
    const tokens = await pricingSDK.getAcceptedTokens();
    
    const plan = plans[userPlan];
    const token = tokens[userToken];
    
    const planPrice = plan.price;
    const platformFee = config.pricing.platform_commission_rate / 100;
    const platformAmount = planPrice * platformFee;
    const developerAmount = planPrice - platformAmount;
    
    // Process payment with your payment system
    const paymentResult = await yourPaymentSystem.process({
      amount: planPrice,
      token: userToken,
      tokenAddress: token.address,
      platformAmount,
      developerAmount,
      developerWallet: config.pricing.payment_wallet_address
    });

    🔧 Express.js Middleware

    Use middleware for automatic access control:

    function createAccessControlMiddleware(agentId) {
      return async (req, res, next) => {
        const userPlan = req.headers['x-user-plan'];
        const userToken = req.headers['x-user-token'];
        
        const pricingSDK = new AgentPricingSDK(agentId);
        const accessResult = await pricingSDK.validateAccess(userPlan, userToken);
        
        if (!accessResult.hasAccess) {
          return res.status(403).json({
            error: 'Access denied',
            reason: accessResult.reason,
            requiredPlan: accessResult.requiredPlan
          });
        }
        
        req.pricingConfig = await pricingSDK.getPricingConfig();
        next();
      };
    }
    
    // Use middleware
    app.use(createAccessControlMiddleware(123));

    🔑 Getting Your API Key

    To get the correct API key for your claimed domain:

    1. Submit your agent to a URL in the marketplace
    2. Once approved, your agent gets a claimed URL (e.g., "servicebot.com")
    3. Create an API key with the same domain as your claimed URL
    4. Use the agent-info endpoint to get the matching API key
    // Get your agent's claimed URL and API key
    const response = await fetch('/api/dashboard/agent-info?agentId=15');
    const data = await response.json();
    
    console.log('Claimed URL:', data.claimedUrl); // "servicebot.com"
    console.log('API Key:', data.apiKey.key); // "ak_9zrytvahq8w0ldud4cu4dv"
    
    // Use this API key for pricing configuration calls
    const pricingSDK = new AgentPricingSDK(15, data.apiKey.key);

    📖 Configuration in AgentDAO

    Before using pricing integration, configure your agent in the AgentDAO platform:

    1. Go to your agent in the Agent Builder
    2. Set your payment wallet address
    3. Enable "Available for Hire"
    4. Add pricing plans (monthly, quarterly, annually, one-time)
    5. Configure accepted tokens (ADAO, ETH, USDC, etc.)
    6. Set usage limits and rate limits
    7. Enable features for different plan tiers

    Rate Limits

    AgentDAO implements rate limiting to ensure fair usage and system stability. Rate limits are applied per API key and are reset periodically.

    Free Tier

    • 100 requests per minute
    • 1,000 requests per hour
    • 10,000 requests per day

    Pro Tier

    • 1,000 requests per minute
    • 10,000 requests per hour
    • 100,000 requests per day

    Rate Limit Headers

    Every API response includes rate limit information in the headers:

    X-RateLimit-Limit: 100
    X-RateLimit-Remaining: 95
    X-RateLimit-Reset: 1625097600

    Versioning

    Our API is versioned using the URL path. The current version is v1. We follow semantic versioning principles and maintain backward compatibility within major versions.

    Version Policy

    • Major versions (v1, v2) are released every 6 months
    • Minor updates are backward compatible
    • Deprecated versions are supported for 12 months
    • Breaking changes are only introduced in major versions

    Version Headers

    You can specify the API version in your requests:

    Accept: application/vnd.agentdao.v1+json

    Migration Guide

    When upgrading to a new major version:

    1. Review the changelog for breaking changes
    2. Update your API calls to use the new version
    3. Test your integration thoroughly
    4. Monitor for any deprecation warnings

    React Integration

    Use our official React package to easily integrate AgentDAO into your React applications.

    Installation

    npm install @agentdao/react
    # or
    yarn add @agentdao/react
    # or
    pnpm add @agentdao/react

    Usage

    import { useAgent } from '@agentdao/react';
    
    function MyComponent() {
      const { agent, loading, error } = useAgent('my-agent-id');
    
      if (loading) return <div>Loading...</div>;
      if (error) return <div>Error: {error.message}</div>;
      if (!agent) return <div>No agent found</div>;
    
      return <div>Agent: {agent.name}</div>;
    }

    Next.js Integration

    Use our official Next.js package to create API routes and server components with AgentDAO.

    Installation

    npm install @agentdao/next
    # or
    yarn add @agentdao/next
    # or
    pnpm add @agentdao/next

    API Routes

    // pages/api/agent.ts
    import { createAgent } from '@agentdao/next';
    
    export default createAgent({
      name: 'my-agent',
      handler: async (req, res) => {
        // Your agent logic here
        return { message: 'Hello from my agent!' };
      }
    });

    Client Components

    import { getAgent } from '@agentdao/next';
    
    // Fetch an agent
    const agent = await getAgent('my-agent-id');

    Node.js Integration

    Use our core package to integrate AgentDAO into your Node.js applications.

    Installation

    npm install @agentdao/core
    # or
    yarn add @agentdao/core
    # or
    pnpm add @agentdao/core

    Usage

    import { Agent } from '@agentdao/core';
    
    // Create a new agent
    const agent = new Agent({
      name: 'my-agent',
      description: 'A custom agent',
      version: '1.0.0',
      handler: async (input) => {
        // Process the input
        return { result: 'success' };
      },
    });
    
    // Execute the agent
    try {
      const result = await agent.execute({ query: 'test' });
      console.log(result);
    } catch (error) {
      console.error('Agent execution failed:', error);
    }

    Testing Strategies

    Best practices for testing your AgentDAO integrations with real agent execution.

    Real Agent Testing

    AgentDAO now provides real agent testing capabilities. Your agents are actually executed during testing:

    // Test your agent with real execution
    const response = await fetch('/api/dashboard/test-agent', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        projectId: 'YOUR_PROJECT_ID',
        testInput: 'Hello, world!'
      })
    });
    
    const result = await response.json();
    console.log(result);
    // {
    //   "success": true,
    //   "message": "Agent test completed successfully",
    //   "output": { "message": "Hello, world!" },
    //   "executionTime": 125,
    //   "testInput": "Hello, world!"
    // }

    Integration Testing

    // Test agent with different inputs
    const testCases = [
      { input: 'Hello', expected: /greeting/i },
      { input: 'Help', expected: /assist/i },
      { input: 'Error test', expected: /error/i }
    ];
    
    for (const testCase of testCases) {
      const response = await fetch('/api/dashboard/test-agent', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          projectId: 'YOUR_PROJECT_ID',
          testInput: testCase.input
        })
      });
      
      const result = await response.json();
      expect(result.success).toBe(true);
      expect(result.output).toMatch(testCase.expected);
    }

    Performance Testing

    // Test agent performance
    const startTime = Date.now();
    const response = await fetch('/api/dashboard/test-agent', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        projectId: 'YOUR_PROJECT_ID',
        testInput: 'Performance test input'
      })
    });
    
    const result = await response.json();
    const totalTime = Date.now() - startTime;
    
    console.log('Total time:', totalTime, 'ms');
    console.log('Execution time:', result.executionTime, 'ms');
    console.log('Success:', result.success);

    Error Testing

    // Test error handling
    try {
      const response = await fetch('/api/dashboard/test-agent', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          projectId: 'INVALID_PROJECT_ID',
          testInput: 'Test input'
        })
      });
      
      const result = await response.json();
      expect(result.success).toBe(false);
      expect(result.error).toBeDefined();
    } catch (error) {
      console.error('Test error:', error);
    }

    Troubleshooting

    Common issues and their solutions when working with AgentDAO.

    Common Issues

    • Authentication Failed - Check your API key and ensure it's properly set in your environment variables.
    • Rate Limit Exceeded - Implement exponential backoff and retry logic in your application.
    • Timeout Errors - Increase the timeout value or optimize your agent's response time.
    • Integration Issues - Verify your webhook URLs and ensure they're accessible.

    Basic Agent

    Create a simple agent using our core package.

    import { Agent } from '@agentdao/core';
    
    // Create a basic agent
    const agent = new Agent({
      name: 'greeting-agent',
      description: 'A simple greeting agent',
      version: '1.0.0',
      handler: async (input) => {
        const { name = 'World' } = input;
        return { message: `Hello, ${name}!` };
      }
    });
    
    // Execute the agent
    const result = await agent.execute({ name: 'Alice' });
    console.log(result.message); // "Hello, Alice!"

    Advanced Agent

    Create an advanced agent with input/output validation and error handling.

    import { Agent } from '@agentdao/core';
    
    // Create an advanced agent
    const agent = new Agent({
      name: 'calculator-agent',
      description: 'A calculator agent with validation',
      version: '1.0.0',
      validateInput: (input) => {
        const { operation, a, b } = input;
        return (
          typeof operation === 'string' &&
          ['add', 'subtract', 'multiply', 'divide'].includes(operation) &&
          typeof a === 'number' &&
          typeof b === 'number'
        );
      },
      validateOutput: (output) => {
        return typeof output.result === 'number';
      },
      handler: async (input) => {
        const { operation, a, b } = input;
        
        switch (operation) {
          case 'add': return { result: a + b };
          case 'subtract': return { result: a - b };
          case 'multiply': return { result: a * b };
          case 'divide':
            if (b === 0) throw new Error('Division by zero');
            return { result: a / b };
          default:
            throw new Error('Invalid operation');
        }
      }
    });
    
    // Execute the agent
    try {
      const result = await agent.execute({
        operation: 'add',
        a: 5,
        b: 3
      });
      console.log(result.result); // 8
    } catch (error) {
      console.error('Calculation failed:', error.message);
    }

    Custom Integration

    Create a custom integration using our Next.js package.

    // pages/api/agent.ts
    import { createAgent } from '@agentdao/next';
    
    export default createAgent({
      name: 'custom-agent',
      handler: async (req, res) => {
        // Access request data
        const { method, body } = req;
        
        // Handle different HTTP methods
        switch (method) {
          case 'GET':
            return { status: 'active', timestamp: new Date() };
            
          case 'POST':
            // Process the request body
            const { action, data } = body;
            return { 
              action,
              processed: true,
              data: `Processed: ${JSON.stringify(data)}`
            };
            
          default:
            res.status(405).json({ error: 'Method not allowed' });
            return;
        }
      }
    });

    Installation

    AgentDAO is a platform for building and deploying AI agents. To get started, you don't need to install any packages. Instead, follow these steps:

    Getting Started

    1. Sign up for an account at developers.agentdao.com
    2. Install the AgentDAO GitHub App for your account
    3. Create a new agent from the dashboard
    4. Choose a template or start from scratch
    5. Deploy your agent with one click

    Required Setup

    • GitHub Account - Required for agent deployment
    • API Keys - Depending on your agent's features:
      • OpenAI API Key for AI features
      • OpenWeather API Key for weather features
      • Other service-specific API keys as needed

    Available Templates

    • AI Chatbot
    • Web Scraper Agent
    • Data Analysis Agent
    • SEO Analyzer
    • Content Summarizer
    • Customer Support Bot
    • RSS News Summarizer
    • Weather Reporter

    Webhooks Overview

    AgentDAO webhooks allow you to receive real-time notifications when specific events occur in your agent ecosystem. This enables seamless integration with external services and automated workflows.

    How Webhooks Work

    1. You create a webhook in your AgentDAO dashboard
    2. AgentDAO sends HTTP POST requests to your webhook URL when events occur
    3. Your service processes the webhook data and takes action
    4. AgentDAO logs delivery attempts and handles retries

    Key Features

    • Real-time Notifications - Get instant updates when agents are approved
    • Secure Delivery - HMAC-SHA256 signature verification
    • Event Filtering - Subscribe only to events you care about
    • Delivery Logging - Track webhook delivery success/failure
    • Retry Logic - Automatic retry for failed deliveries

    Use Cases

    • Crypto Wallet Creation - Create wallets when agents are approved
    • Notification Systems - Send alerts to Slack, Discord, or email
    • Data Synchronization - Keep external systems in sync
    • Analytics Tracking - Log events to analytics platforms
    • Workflow Automation - Trigger automated processes

    Webhook Setup

    Setting up webhooks is straightforward. You'll need a publicly accessible endpoint to receive webhook notifications.

    Step 1: Create Your Webhook Endpoint

    Create a POST endpoint in your application:

    // app/api/webhooks/agentdao/route.ts
    import { NextRequest, NextResponse } from 'next/server';
    import crypto from 'crypto';
    
    const WEBHOOK_SECRET = process.env.AGENTDAO_WEBHOOK_SECRET!;
    
    function verifySignature(payload: string, signature: string): boolean {
      const expectedSignature = crypto
        .createHmac('sha256', WEBHOOK_SECRET)
        .update(payload, 'utf8')
        .digest('hex');
      
      return crypto.timingSafeEqual(
        Buffer.from(signature.replace('sha256=', ''), 'hex'),
        Buffer.from(expectedSignature, 'hex')
      );
    }
    
    export async function POST(req: NextRequest) {
      try {
        const body = await req.text();
        const signature = req.headers.get('x-webhook-signature');
        const event = req.headers.get('x-webhook-event');
    
        // Verify webhook signature
        if (!signature || !verifySignature(body, signature)) {
          return NextResponse.json({ error: 'Invalid signature' }, { status: 401 });
        }
    
        const payload = JSON.parse(body);
        
        // Handle agent.approved event
        if (event === 'agent.approved') {
          const { data } = payload;
          
          // Create crypto wallet or take other action
          await createCryptoWallet(data);
          
          return NextResponse.json({ success: true });
        }
    
        return NextResponse.json({ success: true });
        
      } catch (error) {
        console.error('Webhook error:', error);
        return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
      }
    }

    Step 2: Configure Environment Variables

    # .env
    AGENTDAO_WEBHOOK_SECRET=whsec_your_webhook_secret_here

    Step 3: Create Webhook in AgentDAO

    1. Go to your AgentDAO dashboard
    2. Navigate to Settings → Webhooks
    3. Click Create Webhook
    4. Enter your webhook URL: https://your-domain.com/api/webhooks/agentdao
    5. Select agent.approved event
    6. Save the webhook and copy the secret

    Step 4: Test Your Webhook

    Use the test endpoint to verify your webhook is working:

    curl -X POST https://your-domain.com/api/test-webhook \
      -H "Content-Type: application/json" \
      -d '{"event": "agent.approved", "data": {"test": true}}'

    Webhook Events

    AgentDAO sends webhooks for various events in the agent lifecycle. Each event includes relevant data about the action that occurred.

    Available Events

    agent.approved

    Triggered when an admin approves an agent submission

    Perfect for creating crypto wallets or external integrations

    agent.updated

    Triggered when an agent is modified

    agent.deleted

    Triggered when an agent is removed

    challenge.completed

    Triggered when a developer completes a challenge

    integration.approved

    Triggered when an integration is approved

    Webhook Payload Structure

    {
      "event": "agent.approved",
      "data": {
        "agent_id": 123,
        "agent_name": "My Agent",
        "agent_url": "myagent.com",
        "developer_id": 456,
        "developer_name": "developer123",
        "description": "Agent description",
        "functionality": "What the agent does",
        "tech_stack": "Technologies used",
        "demo_url": "https://demo.example.com",
        "github_url": "https://github.com/user/repo",
        "approved_at": "2024-01-01T12:00:00.000Z",
        "admin_notes": "Admin approval notes"
      },
      "timestamp": "2024-01-01T12:00:00.000Z",
      "webhook_id": "webhook_123"
    }

    Webhook Headers

    • Content-Type: application/json
    • User-Agent: AgentDAO-Webhooks/1.0
    • X-Webhook-Signature: sha256=abc123...
    • X-Webhook-Event: agent.approved
    • X-Webhook-ID: webhook_123

    Webhook Security

    Webhook security is crucial for protecting your integration. AgentDAO provides several security features to ensure safe webhook delivery.

    Signature Verification

    Every webhook includes an HMAC-SHA256 signature that you must verify:

    function verifySignature(payload: string, signature: string): boolean {
      const expectedSignature = crypto
        .createHmac('sha256', WEBHOOK_SECRET)
        .update(payload, 'utf8')
        .digest('hex');
      
      return crypto.timingSafeEqual(
        Buffer.from(signature.replace('sha256=', ''), 'hex'),
        Buffer.from(expectedSignature, 'hex')
      );
    }

    Important: Always verify signatures before processing webhooks. Never trust unverified requests.

    Security Best Practices

    • Verify Signatures - Always check the webhook signature before processing
    • Use HTTPS - Only accept webhooks over secure connections
    • Rate Limiting - Implement rate limiting on your webhook endpoint
    • Timeout Handling - Respond quickly to webhook requests (within 5 seconds)
    • Error Logging - Log failed webhook deliveries for debugging
    • Secret Management - Store webhook secrets securely in environment variables

    Error Handling

    export async function POST(req: NextRequest) {
      try {
        const body = await req.text();
        const signature = req.headers.get('x-webhook-signature');
    
        // Verify signature first
        if (!signature || !verifySignature(body, signature)) {
          console.error('Invalid webhook signature');
          return NextResponse.json({ error: 'Invalid signature' }, { status: 401 });
        }
    
        const payload = JSON.parse(body);
        
        // Process webhook
        await processWebhook(payload);
        
        // Always return 200 for successful receipt
        return NextResponse.json({ success: true });
        
      } catch (error) {
        console.error('Webhook processing error:', error);
        // Return 500 to trigger retry
        return NextResponse.json({ error: 'Processing failed' }, { status: 500 });
      }
    }

    Testing Security

    Test your webhook security with these scenarios:

    • Send webhook with invalid signature
    • Send webhook with missing signature
    • Send webhook with wrong HTTP method
    • Send webhook with malformed JSON
    • Test timeout scenarios

    Core Skills Overview

    AgentDAO Core Skills are powerful, composable modules that can be integrated into any application. Each skill provides specific AI-powered functionality while maintaining consistency and interoperability.

    🔄 Composable

    Mix and match skills as needed for your use case

    🤖 AI-Powered

    Leverage advanced AI capabilities for intelligent automation

    🔧 Configurable

    Customize behavior and settings for your specific needs

    📦 NPM Ready

    Easy installation and updates via npm package

    Available Skills

    Web3SubscriptionSkill - ADAO token-based subscription management on Base chain
    ContentGeneratorSkill - AI-powered content generation and optimization
    SocialMediaSkill - Multi-platform social media management and analytics
    HelpSupportSkill - AI customer support with knowledge base and ticket management
    LiveChatSkill - Real-time chat with moderation and file sharing

    Quick Installation

    npm install @agentdao/core
    
    import { 
      Web3SubscriptionSkill,
      ContentGeneratorSkill,
      SocialMediaSkill,
      HelpSupportSkill,
      LiveChatSkill,
      RssFetcherSkill,
      WebSearchSkill
    } from '@agentdao/core';

    Web3SubscriptionSkill

    Manage subscriptions using ADAO tokens on Base chain with flexible billing periods (monthly, quarterly, annually).

    Key Features

    • ✅ ADAO token payments on Base chain
    • ✅ Monthly, quarterly, and annual billing
    • ✅ Automatic subscription management
    • ✅ Revenue tracking and analytics
    • ✅ Plan upgrades and downgrades
    • ✅ Subscription cancellation
    • ✅ **Multi-chain support (Base, Polygon, Ethereum)**
    • ✅ **Multi-token payments (ADAO, USDC, ETH, MATIC)**
    • ✅ **Advanced analytics and insights**
    • ✅ **Real-time webhooks**
    • ✅ **Automated refund processing**
    • ✅ **10% platform fee (reduced from 15%)**

    Token Gating Feature

    Token Gating allows you to restrict access to your app or specific features based on a user's ADAO token balance. This is useful for premium features, early access, or community gating.

    • Set a minimum ADAO token balance required for access
    • Gate the entire app or individual features
    • Show custom banners and warnings for users who don't meet the requirement
    • Fully configurable via environment variables

    Example Token Gating Config

    const tokenGatingConfig = {
      minTokenForAccess: 10000, // Minimum ADAO tokens required
      tokenAddress: '0x1ef7Be0aBff7d1490e952eC1C7476443A66d6b72',
      tokenSymbol: 'ADAO',
      tokenDecimals: 18,
      features: {
        agent_builder: { requiredTokens: 10000 },
        analytics: { requiredTokens: 10000 },
        // ...other features
      }
    };

    Environment Variables: You can set the required token amount and contract address in your .env file:

    NEXT_PUBLIC_REQUIRED_ADAO_TOKENS=10000
    NEXT_PUBLIC_ADAO_TOKEN_CONTRACT=0x1ef7Be0aBff7d1490e952eC1C7476443A66d6b72

    The platform will automatically enforce token gating and display a status banner if the user does not meet the requirement.

    Configuration

    const subscriptionConfig = {
      agentId: 'my-agent-123',
      agentName: 'My Agent',
      domain: 'myagent.agentdao.com',
      
      // ADAO Token Configuration (Base chain)
      adaoToken: {
        address: '0x...', // ADAO contract address on Base
        decimals: 18,
        network: 'base',
        logo: 'https://example.com/adao-logo.png'
      },
      
      // Subscription Plans
      plans: {
        basic: {
          name: 'Basic Plan',
          description: 'Essential features',
          features: ['chat', 'basic_analytics'],
          pricing: {
            monthly: { adao: 100 },
            quarterly: { adao: 270 }, // 10% discount
            annually: { adao: 960 }   // 20% discount
          }
        },
        pro: {
          name: 'Pro Plan',
          description: 'Advanced features',
          features: ['chat', 'analytics', 'priority_support'],
          pricing: {
            monthly: { adao: 250 },
            quarterly: { adao: 675 },
            annually: { adao: 2400 }
          }
        }
      },
      
      // Provider Configuration
      provider: {
        rpcUrl: 'https://mainnet.base.org',
        chainId: 8453
      }
    };

    Usage Examples

    Create Subscription

    const subscriptionSkill = new Web3SubscriptionSkill(subscriptionConfig);
    
    // Create a subscription
    const subscription = await subscriptionSkill.createSubscription(
      '0x1234...', // user address
      'pro',       // plan ID
      'monthly'    // billing period
    );

    Check Subscription Status

    const status = await subscriptionSkill.getSubscriptionStatus(
      '0x1234...'  // user address
    );
    
    console.log(status); // { active: true, plan: 'pro', expiresAt: '2024-02-15' }

    Get Revenue Analytics

    const analytics = await subscriptionSkill.getRevenueAnalytics();
    
    console.log(analytics);
    // {
    //   totalRevenue: 15000,
    //   monthlyRevenue: 2500,
    //   activeSubscriptions: 45,
    //   conversionRate: 0.15
    // }

    💡 Pro Tip

    Use quarterly and annual billing periods to offer discounts and improve customer retention. The skill automatically handles the discount calculations.

    📊 Comprehensive Statistics

    We've created comprehensive database-driven statistics for both admins and agent owners:

    • Admin Statistics - Platform overview, revenue trends, top performing agents, system health
    • Agent Owner Statistics - Individual agent performance, revenue breakdown, customer insights
    • Real-time Analytics - Live revenue tracking and usage monitoring

    Access these through /api/admin/statistics and /api/dashboard/agent-statistics endpoints.

    Getting Your Receiving Wallet

    To receive subscription payments, you need to set up a receiving wallet for your agent. Here's how:

    1. Get Your Agent's Receiving Wallet

    // Get current receiving wallet
    const response = await fetch('/api/dashboard/agent-receiving-wallet?agentId=your-agent-id');
    const data = await response.json();
    
    if (data.needsSetup) {
      console.log('No receiving wallet configured');
      console.log('Instructions:', data.instructions);
    } else {
      console.log('Receiving wallet:', data.receivingWallet);
      console.log('Payment stats:', data.paymentStats);
    }

    2. Update Your Receiving Wallet

    // Update receiving wallet
    const response = await fetch('/api/dashboard/agent-receiving-wallet', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        agentId: 'your-agent-id',
        receivingWallet: '0x1234567890123456789012345678901234567890'
      })
    });
    
    const data = await response.json();
    console.log('Updated:', data.success);

    3. Create Safe Wallet (Recommended)

    // Create Safe wallet using FundAgent
    const response = await fetch('/api/agents/fund', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        wallet: 'your-wallet-address'
      })
    });
    
    // Send 100 ADAO to FundAgent to create Safe wallet
    // Then use the Safe address as your receiving wallet

    💰 Revenue Flow

    When users subscribe to your agent:

    • 10% goes to AgentDAO platform (reduced from 15%)
    • 90% goes to your receiving wallet
    • All payments are processed automatically
    • Revenue is tracked in real-time

    ContentGeneratorSkill

    Generate AI-powered content for blogs, social media, emails, and more with SEO optimization and brand voice customization.

    Key Features

    • ✅ AI-powered content generation
    • ✅ Multi-platform social media posts
    • ✅ SEO optimization and scoring
    • ✅ Content templates and variables
    • ✅ Brand voice customization
    • ✅ Meta tag generation

    Configuration

    const contentConfig = {
      brand: {
        name: 'My Company',
        voice: 'professional',
        tone: 'friendly',
        keywords: ['technology', 'innovation', 'solutions']
      },
      
      ai: {
        provider: 'openai',
        model: 'gpt-4',
        apiKey: process.env.OPENAI_API_KEY,
        maxTokens: 2000,
        temperature: 0.7
      },
      
      seo: {
        keywords: ['seo', 'marketing', 'digital'],
        targetLength: 1500
      },
      
      integration: {
        autoSave: true,
        storage: 'database' // or 'file'
      },
      
      templates: {
        blog_post: {
          prompt: 'Write a blog post about {topic}',
          variables: ['topic'],
          maxLength: 2000
        },
        social_post: {
          prompt: 'Create a {platform} post about {topic}',
          variables: ['platform', 'topic'],
          maxLength: 280
        }
      }
    };

    Usage Examples

    Generate Blog Post

    const contentSkill = new ContentGeneratorSkill(contentConfig);
    
    const blogPost = await contentSkill.generateBlogPost(
      'AI in Healthcare',
      ['artificial intelligence', 'healthcare', 'innovation']
    );
    
    console.log(blogPost);
    // {
    //   title: 'The Future of AI in Healthcare: Transforming Patient Care',
    //   content: '...',
    //   summary: '...',
    //   keywords: [...],
    //   seoOptimized: true,
    //   wordCount: 1250
    // }

    Generate Social Media Post

    const socialPost = await contentSkill.generateSocialPost(
      'twitter',
      'New product launch'
    );
    
    console.log(socialPost);
    // {
    //   content: '🚀 Exciting news! We just launched our new AI-powered solution...',
    //   platform: 'twitter',
    //   hashtags: ['#AI', '#Innovation'],
    //   characterCount: 245
    // }

    Optimize Content for SEO

    const optimized = await contentSkill.optimizeForSEO(
      'Your content here...',
      ['keyword1', 'keyword2']
    );
    
    console.log(optimized);
    // {
    //   original: '...',
    //   optimized: '...',
    //   seoScore: 85,
    //   suggestions: ['Add more keywords', 'Increase content length']
    // }

    💡 Pro Tip

    Use the brand voice and tone settings to maintain consistency across all generated content. The AI will automatically adapt the writing style to match your brand personality.

    SocialMediaSkill

    Manage social media presence across multiple platforms with scheduling, analytics, and engagement tracking.

    Supported Platforms

    Twitter
    280 chars
    LinkedIn
    1300 chars
    Facebook
    63K chars
    Instagram
    2200 chars

    Key Features

    • ✅ Multi-platform posting (Twitter, LinkedIn, Facebook, Instagram)
    • ✅ Post scheduling and drafts
    • ✅ Analytics and engagement tracking
    • ✅ Comment management
    • ✅ Mention monitoring
    • ✅ File/media uploads

    Configuration

    ⚠️ Important Note

    Use provider: 'openai' for DALL-E models. The provider should be 'openai', not 'dalle'. Supported providers: 'openai', 'midjourney', 'stable-diffusion'.

    const socialConfig = {
      platforms: {
        twitter: {
          enabled: true,
          accessToken: process.env.TWITTER_ACCESS_TOKEN,
          username: '@mycompany'
        },
        linkedin: {
          enabled: true,
          accessToken: process.env.LINKEDIN_ACCESS_TOKEN,
          companyId: '123456'
        },
        facebook: {
          enabled: true,
          accessToken: process.env.FACEBOOK_ACCESS_TOKEN,
          pageId: '987654321'
        },
        instagram: {
          enabled: true,
          accessToken: process.env.INSTAGRAM_ACCESS_TOKEN,
          accountId: 'insta123'
        }
      },
      
      scheduling: {
        enabled: true,
        timezone: 'UTC',
        defaultTime: '09:00'
      },
      
      analytics: {
        enabled: true,
        trackEngagement: true,
        trackReach: true
      }
    };

    Usage Examples

    Post to All Platforms

    const socialSkill = new SocialMediaSkill(socialConfig);
    
    const results = await socialSkill.postToAll(
      'Exciting news! We just launched our new feature.',
      [{ type: 'image', url: 'https://example.com/image.jpg' }]
    );
    
    console.log(results);
    // [
    //   { platform: 'twitter', success: true, postId: '123', url: '...' },
    //   { platform: 'linkedin', success: true, postId: '456', url: '...' },
    //   ...
    // ]

    Schedule a Post

    const scheduled = await socialSkill.schedulePost(
      'twitter',
      'Scheduled post content',
      new Date('2024-01-15T10:00:00Z')
    );
    
    console.log(scheduled);
    // {
    //   id: 'post_123',
    //   platform: 'twitter',
    //   content: '...',
    //   scheduledTime: '2024-01-15T10:00:00Z',
    //   status: 'scheduled'
    // }

    Get Analytics

    const analytics = await socialSkill.getPostAnalytics('post_id_123');
    
    console.log(analytics);
    // {
    //   postId: 'post_id_123',
    //   platform: 'twitter',
    //   impressions: 1500,
    //   engagement: 45,
    //   clicks: 23,
    //   shares: 12,
    //   comments: 8,
    //   likes: 67
    // }

    💡 Pro Tip

    Use the scheduling feature to post at optimal times for each platform. The skill automatically handles timezone conversions and platform-specific posting times.

    HelpSupportSkill

    Provide AI-powered customer support with knowledge base integration, ticket management, and automatic escalation to human agents.

    Key Features

    • ✅ AI-powered responses with confidence scoring
    • ✅ Automatic escalation to human support
    • ✅ Knowledge base integration
    • ✅ Support ticket management
    • ✅ Conversation history tracking
    • ✅ Analytics and common issue detection

    Configuration

    ⚠️ Important Note

    Use provider: 'openai' for DALL-E models. The provider should be 'openai', not 'dalle'. Supported providers: 'openai', 'midjourney', 'stable-diffusion'.

    const supportConfig = {
      agentName: 'Customer Support Bot',
      
      ai: {
        provider: 'openai',
        model: 'gpt-4',
        apiKey: process.env.OPENAI_API_KEY,
        maxTokens: 1000,
        temperature: 0.7
      },
      
      escalationThreshold: 5, // messages before human escalation
      
      humanSupport: {
        enabled: true,
        email: 'support@company.com',
        phone: '+1-555-0123',
        responseTime: '2 hours'
      },
      
      knowledgeBase: {
        sources: [
          'https://docs.company.com',
          'https://help.company.com'
        ],
        autoUpdate: true
      }
    };

    Usage Examples

    Handle Customer Message

    const supportSkill = new HelpSupportSkill(supportConfig);
    
    const response = await supportSkill.handleMessage(
      'How do I reset my password?',
      {
        userId: 'user123',
        subscription: 'pro',
        previousTickets: 2
      }
    );
    
    console.log(response);
    // {
    //   response: 'To reset your password, go to the login page...',
    //   confidence: 0.95,
    //   escalateToHuman: false,
    //   conversationId: 'conv_123',
    //   sources: ['https://docs.company.com/password-reset'],
    //   suggestedActions: ['Click "Forgot Password"', 'Check your email']
    // }

    Search Knowledge Base

    const results = await supportSkill.searchKnowledgeBase('password reset');
    
    console.log(results);
    // [
    //   {
    //     id: 'kb_1',
    //     title: 'How to reset your password',
    //     content: 'To reset your password, go to the login page...',
    //     relevance: 0.95,
    //     source: 'https://docs.company.com/password-reset',
    //     lastUpdated: '2024-01-10'
    //   }
    // ]

    Create Support Ticket

    const ticket = await supportSkill.createTicket(
      'user123',
      'Payment processing error',
      'high'
    );
    
    console.log(ticket);
    // {
    //   id: 'ticket_456',
    //   userId: 'user123',
    //   issue: 'Payment processing error',
    //   priority: 'high',
    //   status: 'open',
    //   createdAt: '2024-01-15T10:30:00Z'
    // }

    💡 Pro Tip

    Set up your knowledge base sources to improve AI response accuracy. The skill will automatically search and reference relevant documentation when answering customer questions.

    LiveChatSkill

    Real-time chat functionality with moderation, file sharing, user management, and analytics.

    Key Features

    • ✅ Real-time messaging
    • ✅ File upload and sharing
    • ✅ Message moderation and filtering
    • ✅ User presence tracking
    • ✅ Chat analytics
    • ✅ Multi-user conversations

    Configuration

    ⚠️ Important Note

    Use provider: 'openai' for DALL-E models. The provider should be 'openai', not 'dalle'. Supported providers: 'openai', 'midjourney', 'stable-diffusion'.

    const chatConfig = {
      maxParticipants: 50,
      messageHistoryLimit: 100,
      
      moderation: {
        enabled: true,
        profanityFilter: true,
        spamDetection: true,
        autoBlock: false,
        filters: ['spam', 'inappropriate']
      },
      
      fileSharing: {
        enabled: true,
        maxFileSize: 10 * 1024 * 1024, // 10MB
        allowedTypes: ['image/*', 'application/pdf']
      },
      
      notifications: {
        enabled: true,
        sound: true,
        desktop: true
      }
    };

    Usage Examples

    Start a Chat

    const chatSkill = new LiveChatSkill(chatConfig);
    
    const chatId = await chatSkill.startChat('user123', {
      userAgent: 'Mozilla/5.0...',
      referrer: 'https://example.com'
    });
    
    console.log(chatId); // 'chat_1234567890_abc123'

    Send a Message

    const message = await chatSkill.sendMessage(
      chatId,
      'Hello everyone!',
      'user123'
    );
    
    console.log(message);
    // {
    //   id: 'msg_123',
    //   chatId: 'chat_1234567890_abc123',
    //   sender: 'user123',
    //   content: 'Hello everyone!',
    //   messageType: 'text',
    //   timestamp: '2024-01-15T10:30:00Z',
    //   read: false
    // }

    Upload File

    const fileMessage = await chatSkill.uploadFile(
      chatId,
      fileObject, // File object from input
      'user123'
    );
    
    console.log(fileMessage);
    // {
    //   id: 'msg_456',
    //   chatId: 'chat_1234567890_abc123',
    //   fileName: 'document.pdf',
    //   fileUrl: 'https://storage.example.com/files/document.pdf',
    //   fileSize: 2048576,
    //   fileType: 'application/pdf',
    //   uploadedBy: 'user123',
    //   timestamp: '2024-01-15T10:35:00Z'
    // }

    Get Online Users

    const onlineUsers = await chatSkill.getOnlineUsers(chatId);
    
    console.log(onlineUsers);
    // [
    //   {
    //     id: 'user123',
    //     username: 'user123',
    //     online: true,
    //     lastSeen: '2024-01-15T10:30:00Z'
    //   },
    //   {
    //     id: 'user456',
    //     username: 'user456',
    //     online: true,
    //     lastSeen: '2024-01-15T10:25:00Z'
    //   }
    // ]

    💡 Pro Tip

    Enable message moderation to automatically filter inappropriate content and spam. The skill uses AI-powered detection to keep your chat environment safe and professional.

    RssFetcherSkill

    Fetch and filter RSS feeds with keyword filtering, date filtering, and multi-feed aggregation. Perfect for content monitoring and news aggregation.

    Key Features

    • ✅ Single and multi-feed fetching
    • ✅ Keyword-based filtering
    • ✅ Date-based filtering
    • ✅ Custom field selection
    • ✅ Feed aggregation
    • ✅ Error handling and retries

    Configuration

    ⚠️ Important Note

    Use provider: 'openai' for DALL-E models. The provider should be 'openai', not 'dalle'. Supported providers: 'openai', 'midjourney', 'stable-diffusion'.

    const rssConfig = {
      maxResults: 10,
      timeout: 30000, // 30 seconds
      retryAttempts: 3
    };

    Usage Examples

    Fetch Single RSS Feed

    const rssSkill = new RssFetcherSkill(rssConfig);
    
    const items = await rssSkill.fetchFeed('https://hnrss.org/frontpage', {
      keyword: 'AI',
      limit: 5,
      after: '2024-01-01T00:00:00Z'
    });
    
    console.log(items);
    // [
    //   {
    //     title: 'New AI breakthrough in healthcare',
    //     link: 'https://example.com/ai-healthcare',
    //     pubDate: '2024-01-15T10:30:00Z',
    //     contentSnippet: 'Researchers discover...'
    //   }
    // ]

    Multi-Feed Aggregation

    const multiFeedItems = await rssSkill.fetchFeed('', {
      urls: [
        'https://hnrss.org/frontpage',
        'https://rss.cnn.com/rss/edition.rss',
        'https://feeds.bbci.co.uk/news/rss.xml'
      ],
      keyword: 'technology',
      limit: 10
    });
    
    console.log(multiFeedItems);
    // [
    //   {
    //     title: 'Tech news from multiple sources',
    //     link: 'https://example.com/tech-news',
    //     pubDate: '2024-01-15T10:30:00Z',
    //     _feedUrl: 'https://hnrss.org/frontpage'
    //   }
    // ]

    Filter by Custom Fields

    const filteredItems = await rssSkill.fetchFeed('https://example.com/feed', {
      fields: ['title', 'link', 'pubDate', 'contentSnippet'],
      limit: 5
    });
    
    console.log(filteredItems);
    // [
    //   {
    //     title: 'Article Title',
    //     link: 'https://example.com/article',
    //     pubDate: '2024-01-15T10:30:00Z',
    //     contentSnippet: 'Article summary...'
    //   }
    // ]

    💡 Pro Tip

    Use multi-feed aggregation to create comprehensive news monitoring systems. Combine feeds from different sources to get a complete view of topics you're interested in.

    Skills API

    AgentDAO Skills can be used both as an npm package and via REST API endpoints. The API endpoints provide the same functionality as the npm package, allowing you to integrate skills into any application without installing dependencies.

    🔐 Authentication & API Keys

    All skill endpoints now automatically fetch and use your API keys:

    • ✅ Session authentication required (automatic when logged in)
    • ✅ External API keys automatically fetched from your settings
    • ✅ Clear error messages if required keys are missing
    • ✅ Your keys are never exposed in code or logs

    Example error when key is missing:

    {
      "error": "No OpenAI API key found in your settings. Please add your OpenAI API key in Settings → API Keys."
    }

    Base URL

    All skills API endpoints are prefixed with: /api/skills/

    Web3SubscriptionSkill Endpoints

    Create Subscription

    POST /api/skills/web3-subscription/create-subscription
    Content-Type: application/json
    
    {
      "userAddress": "0x1234...",
      "planId": "pro",
      "billingPeriod": "monthly",
      "config": {
        "agentId": "my-agent-123",
        "plans": { ... },
        "provider": { ... }
      }
    }

    Check Subscription

    GET /api/skills/web3-subscription/check-subscription?userAddress=0x1234...&config={...}

    Get Available Plans

    GET /api/skills/web3-subscription/plans?config={...}

    ContentGeneratorSkill Endpoints

    Generate Blog Post

    POST /api/skills/content-generator/generate-blog-post
    Content-Type: application/json
    
    {
      "topic": "AI in Healthcare",
      "keywords": ["artificial intelligence", "healthcare"],
      "config": {
        "brand": { ... },
        "ai": { ... },
        "seo": { ... }
      }
    }

    Generate Social Post

    POST /api/skills/content-generator/generate-social-post
    Content-Type: application/json
    
    {
      "platform": "twitter",
      "topic": "New product launch",
      "config": { ... }
    }

    SocialMediaSkill Endpoints

    Post to Platform

    POST /api/skills/social-media/post-to-platform
    Content-Type: application/json
    
    {
      "platform": "twitter",
      "content": "Exciting news! We just launched our new feature.",
      "media": [{ "type": "image", "url": "https://example.com/image.jpg" }],
      "config": {
        "platforms": { ... },
        "scheduling": { ... }
      }
    }

    Get Analytics

    GET /api/skills/social-media/analytics?platform=twitter&postId=123&config={...}

    HelpSupportSkill Endpoints

    Handle Message

    POST /api/skills/help-support/handle-message
    Content-Type: application/json
    
    {
      "message": "How do I reset my password?",
      "userContext": {
        "userId": "user123",
        "subscription": "pro",
        "previousTickets": 2
      },
      "config": {
        "agentName": "Customer Support Bot",
        "ai": { ... },
        "escalationThreshold": 5
      }
    }

    LiveChatSkill Endpoints

    Start Chat

    POST /api/skills/live-chat/start-chat
    Content-Type: application/json
    
    {
      "userId": "user123",
      "metadata": {
        "userAgent": "Mozilla/5.0...",
        "referrer": "https://example.com"
      },
      "config": {
        "maxParticipants": 50,
        "moderation": { ... }
      }
    }

    Send Message

    POST /api/skills/live-chat/send-message
    Content-Type: application/json
    
    {
      "chatId": "chat_123",
      "message": "Hello everyone!",
      "userId": "user123",
      "config": { ... }
    }

    RssFetcherSkill Endpoints

    Fetch RSS Feed

    POST /api/skills/rss-fetcher
    Content-Type: application/json
    
    {
      "url": "https://hnrss.org/frontpage",
      "options": {
        "keyword": "AI",
        "limit": 10,
        "after": "2024-01-01T00:00:00Z",
        "fields": ["title", "link", "pubDate"]
      },
      "config": {
        "maxResults": 10,
        "timeout": 30000
      }
    }

    Multi-Feed Aggregation

    POST /api/skills/rss-fetcher/multi-feed
    Content-Type: application/json
    
    {
      "urls": [
        "https://hnrss.org/frontpage",
        "https://rss.cnn.com/rss/edition.rss"
      ],
      "options": {
        "keyword": "technology",
        "limit": 15
      }
    }

    WebSearchSkill Endpoints

    🔍 Search Providers

    The API automatically uses your configured search providers with fallback:

    • Primary: Google Search (if GOOGLE_SEARCH_API_KEY configured)
    • Secondary: Bing Search (if BING_SEARCH_API_KEY configured)
    • Fallback: OpenAI Web Search (if OPENAI_API_KEY configured)

    Web Search

    POST /api/skills/web3-search
    Content-Type: application/json
    
    {
      "query": "blockchain technology trends 2024",
      "options": {
        "maxResults": 10,
        "includeImages": false,
        "includeNews": true,
        "type": "web"
      },
      "config": {
        "agentId": "web-search-agent",
        "ai": { ... },
        "search": { ... }
      }
    }

    News Search

    POST /api/skills/web3-search/news
    Content-Type: application/json
    
    {
      "query": "cryptocurrency regulations",
      "options": {
        "maxResults": 5,
        "timeRange": "week"
      }
    }

    Image Search

    POST /api/skills/web3-search/images
    Content-Type: application/json
    
    {
      "query": "blockchain network diagram",
      "options": {
        "maxResults": 10,
        "size": "medium"
      }
    }

    AI-Powered Search

    POST /api/skills/web3-search/ai-search
    Content-Type: application/json
    
    {
      "query": "Web3 development best practices",
      "context": "I need guidance for building a DeFi application"
    }

    Search Analytics

    GET /api/skills/web3-search/analytics

    💡 Pro Tip

    You can use the same configuration object for both npm package and API endpoints. This makes it easy to switch between local and remote usage without changing your configuration.

    ImageGenerationSkill Endpoints

    Generate Images

    POST /api/skills/image-generation
    Content-Type: application/json
    
    {
      "prompt": "A futuristic blockchain city with flying cars and digital displays",
      "options": {
        "size": "1024x1024",
        "style": "vivid",
        "quality": "standard",
        "numImages": 1
      },
      "config": {
        "agentId": "image-gen-agent",
        "ai": { ... },
        "image": { ... }
      }
    }

    Generate Variations

    POST /api/skills/image-generation
    Content-Type: application/json
    
    {
      "prompt": "variation",
      "options": {
        "type": "variation",
        "imageUrl": "https://example.com/original-image.jpg",
        "size": "1024x1024",
        "numVariations": 4
      }
    }

    Edit Images

    POST /api/skills/image-generation
    Content-Type: application/json
    
    {
      "prompt": "Add a blockchain logo to the top right corner",
      "options": {
        "type": "edit",
        "imageUrl": "https://example.com/original-image.jpg",
        "maskUrl": "https://example.com/mask.png"
      }
    }

    PhotoSkill Endpoints

    Search Photos

    POST /api/skills/photo
    Content-Type: application/json
    
    {
      "query": "blockchain technology",
      "options": {
        "provider": "all",
        "size": "medium",
        "orientation": "landscape",
        "maxResults": 20,
        "page": 1
      },
      "config": {
        "agentId": "photo-agent",
        "providers": { ... },
        "search": { ... }
      }
    }

    Get Trending Photos

    POST /api/skills/photo
    Content-Type: application/json
    
    {
      "query": "trending",
      "options": {
        "type": "trending",
        "provider": "unsplash",
        "category": "technology",
        "maxResults": 10
      }
    }

    Get Categories

    POST /api/skills/photo
    Content-Type: application/json
    
    {
      "query": "categories",
      "options": {
        "type": "categories"
      }
    }

    Download Photo

    POST /api/skills/photo
    Content-Type: application/json
    
    {
      "query": "download",
      "options": {
        "type": "download",
        "photoId": "photo_123",
        "provider": "unsplash"
      }
    }

    📋 Complete Skills API Endpoints

    All endpoints require authentication and automatically fetch your API keys. Here's the complete list:

    🤖 AI & Language Models

    • POST /api/skills/ai-chat - AI chat with OpenAI
    • POST /api/skills/image-generation - Generate images with DALL-E
    • POST /api/skills/help-support/handle-message - AI-powered support

    🔍 Web Search & Content

    • POST /api/skills/web3-search - Web search with AI analysis
    • POST /api/skills/web3-search/ai-search - AI-powered search
    • POST /api/skills/web3-search/news - News search
    • POST /api/skills/web3-search/images - Image search
    • GET /api/skills/web3-search/analytics - Search analytics
    • POST /api/skills/photo - Stock photo search
    • POST /api/skills/rss-fetcher - RSS feed fetching
    • POST /api/skills/rss-fetcher/multi-feed - Multiple RSS feeds

    📱 Social Media

    • POST /api/skills/social-media/post-to-platform - Post to social platforms
    • GET /api/skills/social-media/analytics - Social media analytics

    ⛓️ Web3 & Blockchain

    • GET /api/skills/web3-subscription/check-subscription - Check subscription status
    • GET /api/skills/web3-subscription/plans - Get available plans
    • POST /api/skills/web3-subscription/create-subscription - Create subscription

    💬 Live Chat

    • POST /api/skills/live-chat/start-chat - Start a chat session
    • POST /api/skills/live-chat/send-message - Send chat message

    ⚠️ Important Notes

    • • All endpoints require session authentication (automatic when logged in)
    • • External API keys are automatically fetched from your settings
    • • Missing API keys return clear error messages with instructions
    • • Your API keys are never exposed in responses or logs
    • • Rate limits apply per user and endpoint

    ImageGenerationSkill

    Generate AI-powered images using OpenAI DALL-E. Create custom visuals, variations, and edits for marketing, content creation, and design projects.

    Key Features

    • ✅ AI image generation with DALL-E 3
    • ✅ Image variations and editing
    • ✅ Multiple sizes and styles
    • ✅ Batch generation
    • ✅ Style customization
    • ✅ High-quality outputs

    Configuration

    ⚠️ Important Note

    Use provider: 'openai' for DALL-E models. The provider should be 'openai', not 'dalle'. Supported providers: 'openai', 'midjourney', 'stable-diffusion'.

    const imageConfig = {
      agentId: 'image-gen-agent',
      agentName: 'Image Generation Agent',
      domain: 'images.agentdao.com',
      
      ai: {
        provider: 'openai',
        model: 'dall-e-3',
        apiKey: process.env.OPENAI_API_KEY,
        maxTokens: 1000,
        temperature: 0.7
      },
      
      image: {
        defaultSize: '1024x1024',
        defaultStyle: 'vivid',
        maxImages: 4,
        quality: 'standard'
      },
      
      integration: {
        webhooks: {
          enabled: true,
          url: 'https://example.com/webhook'
        }
      },
      
      analytics: {
        enabled: true,
        tracking: ['generations', 'downloads', 'styles']
      }
    };

    Usage Examples

    Generate Images

    const imageSkill = new ImageGenerationSkill(imageConfig);
    
    const images = await imageSkill.generateImages({
      prompt: 'A futuristic blockchain city with flying cars and digital displays',
      size: '1024x1024',
      style: 'vivid',
      quality: 'standard',
      numImages: 1
    });
    
    console.log(images);
    // [
    //   {
    //     id: 'img_1705312345678_0',
    //     url: 'https://oaidalleapiprodscus.blob.core.windows.net/private/...',
    //     prompt: 'A futuristic blockchain city with flying cars and digital displays',
    //     size: '1024x1024',
    //     style: 'vivid',
    //     quality: 'standard',
    //     createdAt: '2024-01-15T10:30:00Z',
    //     metadata: {
    //       model: 'dall-e-3',
    //       provider: 'openai'
    //     }
    //   }
    // ]

    Generate Variations

    const variations = await imageSkill.generateVariations(
      'https://example.com/original-image.jpg',
      {
        size: '1024x1024',
        numVariations: 4
      }
    );
    
    console.log(variations);
    // [
    //   {
    //     id: 'var_1705312345678_0',
    //     url: 'https://oaidalleapiprodscus.blob.core.windows.net/private/...',
    //     prompt: 'Variation of: https://example.com/original-image.jpg',
    //     size: '1024x1024',
    //     style: 'vivid',
    //     quality: 'standard',
    //     createdAt: '2024-01-15T10:30:00Z',
    //     metadata: {
    //       model: 'dall-e-2',
    //       provider: 'openai'
    //     }
    //   }
    // ]

    Edit Images

    const editedImage = await imageSkill.editImage(
      'https://example.com/original-image.jpg',
      'Add a blockchain logo to the top right corner',
      {
        size: '1024x1024',
        mask: 'base64-encoded-mask-data'
      }
    );
    
    console.log(editedImage);
    // {
    //   id: 'edit_1705312345678',
    //   url: 'https://oaidalleapiprodscus.blob.core.windows.net/private/...',
    //   prompt: 'Edit: Add a blockchain logo to the top right corner',
    //   size: '1024x1024',
    //   style: 'vivid',
    //   quality: 'standard',
    //   createdAt: '2024-01-15T10:30:00Z',
    //   metadata: {
    //     model: 'dall-e-2',
    //     provider: 'openai'
    //   }
    // }

    💡 Pro Tip

    Use detailed, descriptive prompts for better results. Include style keywords like "photorealistic", "artistic", or "minimalist" to get the exact look you want.

    PhotoSkill

    Search and manage stock photos across multiple providers including Unsplash, Pexels, and Pixabay. Perfect for content creation, marketing, and design projects.

    Key Features

    • ✅ Multi-provider search (Unsplash, Pexels, Pixabay)
    • ✅ Advanced filtering and sorting
    • ✅ High-resolution downloads
    • ✅ Photographer attribution
    • ✅ Category browsing
    • ✅ Trending photos

    Configuration

    const photoConfig = {
      agentId: 'photo-agent',
      agentName: 'Photo Search Agent',
      domain: 'photos.agentdao.com',
      
      providers: {
        unsplash: {
          enabled: true,
          accessKey: process.env.UNSPLASH_ACCESS_KEY
        },
        pexels: {
          enabled: true,
          apiKey: process.env.PEXELS_API_KEY
        },
        pixabay: {
          enabled: true,
          apiKey: process.env.PIXABAY_API_KEY
        }
      },
      
      search: {
        defaultProvider: 'all',
        maxResults: 20,
        defaultSize: 'medium',
        includeOrientation: true
      },
      
      integration: {
        webhooks: {
          enabled: true,
          url: 'https://example.com/webhook'
        }
      },
      
      analytics: {
        enabled: true,
        tracking: ['searches', 'downloads', 'providers']
      }
    };

    Usage Examples

    Search Photos

    const photoSkill = new PhotoSkill(photoConfig);
    
    const photos = await photoSkill.searchPhotos({
      query: 'blockchain technology',
      provider: 'all',
      size: 'medium',
      orientation: 'landscape',
      maxResults: 20,
      page: 1
    });
    
    console.log(photos);
    // [
    //   {
    //     id: 'photo_123',
    //     url: 'https://images.unsplash.com/photo-1234567890',
    //     thumbnailUrl: 'https://images.unsplash.com/photo-1234567890?w=400',
    //     previewUrl: 'https://images.unsplash.com/photo-1234567890?w=800',
    //     downloadUrl: 'https://unsplash.com/photos/1234567890/download',
    //     title: 'Blockchain Technology Visualization',
    //     description: 'Digital representation of blockchain technology',
    //     photographer: {
    //       name: 'John Doe',
    //       username: 'johndoe',
    //       profileUrl: 'https://unsplash.com/@johndoe'
    //     },
    //     dimensions: {
    //       width: 1920,
    //       height: 1080
    //     },
    //     size: 0,
    //     format: 'jpeg',
    //     tags: ['blockchain', 'technology', 'digital'],
    //     category: 'technology',
    //     license: 'free',
    //     provider: 'unsplash',
    //     createdAt: '2024-01-15T10:30:00Z',
    //     metadata: {
    //       likes: 150,
    //       downloads: 500,
    //       views: 2000,
    //       color: '#1a1a1a'
    //     }
    //   }
    // ]

    Get Trending Photos

    const trendingPhotos = await photoSkill.getTrendingPhotos({
      provider: 'unsplash',
      category: 'technology',
      maxResults: 10
    });
    
    console.log(trendingPhotos);
    // [
    //   {
    //     id: 'trending_123',
    //     url: 'https://images.unsplash.com/photo-trending-123',
    //     title: 'Trending Technology Photo',
    //     photographer: {
    //       name: 'Jane Smith',
    //       username: 'janesmith'
    //     },
    //     provider: 'unsplash',
    //     category: 'technology'
    //   }
    // ]

    Get Categories

    const categories = await photoSkill.getCategories();
    
    console.log(categories);
    // [
    //   {
    //     id: 'nature',
    //     name: 'Nature',
    //     description: 'Landscapes, wildlife, and natural scenes',
    //     photoCount: 50000
    //   },
    //   {
    //     id: 'business',
    //     name: 'Business',
    //     description: 'Professional business and office scenes',
    //     photoCount: 25000
    //   },
    //   {
    //     id: 'technology',
    //     name: 'Technology',
    //     description: 'Computers, gadgets, and tech scenes',
    //     photoCount: 15000
    //   }
    // ]

    💡 Pro Tip

    Use specific keywords and combine them with orientation and size filters to find the perfect photo for your project. The multi-provider search gives you access to millions of high-quality images.

    Bring Your Own API Key (BYOAK)

    AgentDAO uses a Bring Your Own API Key (BYOAK) model for all external providers (OpenAI, AWS, Google, etc.).

    You must add your own API keys in the Settings → API Keys page. These keys are securely stored and automatically used by any of your agents that require them.

    1. Go to Dashboard → Settings → API Keys.
    2. Search for the provider you want (e.g., OpenAI, AWS, etc.).
    3. Enter your API key(s) and save.

    API Flow & Security

    All skill endpoints now automatically fetch and use your API keys:

    1. When you call a skill endpoint (e.g., AI chat, image generation), the system checks if you have the required API key
    2. If the key exists, it's automatically used for the external API call
    3. If the key is missing, you get a clear error message directing you to add it
    4. Your keys are never exposed in agent code or logs

    Example error when key is missing:

    {
      "error": "No OpenAI API key found in your settings. Please add your OpenAI API key in Settings → API Keys."
    }

    Why BYOAK?

    • You control your own usage, billing, and security.
    • No keys are ever shared or hardcoded in agent code.
    • You can update, rotate, or delete keys at any time.
    • All agents you build can use your saved keys automatically.
    • Centralized, secure management of all your external API keys.
    • Clear error messages guide you to add missing keys.

    Supported Providers

    AI & Language Models

    • OpenAI (GPT-4, GPT-3.5, DALL-E)
    • Anthropic (Claude)
    • Google (PaLM, Gemini)
    • Azure OpenAI

    Web3 & Blockchain

    • Alchemy
    • Infura
    • QuickNode
    • Etherscan

    Social Media

    • Twitter/X API
    • Facebook Graph API
    • LinkedIn API
    • Instagram API

    Content & Media

    • Unsplash
    • Pexels
    • Pixabay
    • Resend (Email)

    Security Best Practices

    • Never share your API keys publicly or commit them to version control.
    • Rotate your API keys regularly.
    • Delete unused keys from the dashboard.
    • Monitor your API usage through your provider's dashboard.
    • Use environment-specific keys (development vs production).