AgentHR Developer Guide

v1.0.0

Platform Overview

AgentHR is an AI-powered HR hiring SaaS platform built by Diploy (Bisht Technologies Private Limited). It enables organizations to create AI agents for automated phone interviews, manage hiring pipelines, bulk-screen CVs, and conduct AI voice interviews at scale.

Core Capabilities

Architecture Diagram


                    +-------------------+
                    |   React Frontend  |
                    |  (Vite + shadcn)  |
                    +--------+----------+
                             |
                    +--------v----------+
                    |  Express Backend  |
                    |   (TypeScript)    |
                    +--------+----------+
                             |
          +------------------+------------------+
          |                  |                  |
  +-------v------+  +-------v------+  +-------v------+
  |   Drizzle    |  |   Engines    |  |   Plugins    |
  |  PostgreSQL  |  | (Voice, Pay) |  | (REST, SIP,  |
  |              |  |              |  |  Team Mgmt)  |
  +--------------+  +------+-------+  +--------------+
                           |
            +--------------+--------------+
            |              |              |
     +------v---+  +------v---+  +------v---+
     | ElevenLabs|  |  Twilio  |  |  Plivo   |
     |  OpenAI   |  |          |  |          |
     +-----------+  +----------+  +----------+

Project Structure

AgentHR/
├── client/                  # React frontend (Vite)
│   ├── src/
│   │   ├── pages/           # Route-based page components
│   │   ├── components/      # Reusable UI components
│   │   │   ├── ui/          # shadcn/ui base components
│   │   │   ├── landing/     # Public landing page components
│   │   │   └── admin/       # Admin panel components
│   │   ├── contexts/        # React contexts (auth, plugins)
│   │   ├── hooks/           # Custom React hooks
│   │   ├── lib/             # Utilities (API client, formatters)
│   │   └── i18n/            # Internationalization config
│   └── public/              # Static assets
├── server/                  # Express backend
│   ├── routes/              # API route handlers
│   ├── services/            # Business logic layer
│   ├── engines/             # Specialized subsystems
│   │   ├── payment/         # Multi-gateway payment engine
│   │   ├── plivo/           # Plivo telephony engine
│   │   ├── twilio-openai/   # Twilio + OpenAI engine
│   │   ├── plivo-elevenlabs/# Plivo + ElevenLabs SIP engine
│   │   └── kyc/             # KYC verification engine
│   ├── infrastructure/      # DB pools, WebSocket, BullMQ
│   ├── middleware/          # Auth, rate limiting, logging
│   ├── storage/             # Data access layer (Drizzle)
│   ├── plugins/             # Plugin loader system
│   ├── demo-mode/           # Demo mode seeding & middleware
│   └── modules/             # Feature modules (widget, etc.)
├── shared/                  # Shared between client & server
│   └── schema.ts            # Drizzle ORM schema (source of truth)
├── plugins/                 # Installable plugins
│   ├── rest-api/            # REST API plugin
│   ├── sip-engine/          # SIP Engine plugin
│   └── team-management/     # Team Management plugin
├── packages/                # Internal libraries
│   └── diploy-core/         # Shared errors, logging, response utils
├── scripts/                 # Build, setup, deployment scripts
├── public/                  # Server-served static files
├── .env.example             # Environment variable template
├── drizzle.config.ts        # Drizzle ORM configuration
├── vite.config.ts           # Vite build configuration
├── tailwind.config.ts       # Tailwind CSS configuration
└── package.json             # Dependencies and scripts

Tech Stack

LayerTechnologyPurpose
Frontend FrameworkReact 18 + TypeScriptUI rendering
Build ToolViteFast HMR, bundling
RoutingWouterLightweight client routing
Data FetchingTanStack Query v5Server state management
UI Componentsshadcn/ui (Radix UI)Accessible component library
StylingTailwind CSSUtility-first CSS
IconsLucide ReactIcon library
i18ni18next + react-i18nextInternationalization
BackendNode.js + ExpressHTTP server
LanguageTypeScriptType safety
ORMDrizzle ORMType-safe SQL
DatabasePostgreSQL 14+Primary data store
Queue (Optional)BullMQ + RedisBackground job processing
AuthJWT + bcryptAuthentication & hashing
Voice AIElevenLabs, OpenAI RealtimeConversational AI
TelephonyTwilio, PlivoPhone calls & SMS
PaymentsStripe, Razorpay, PayPal, Paystack, MercadoPagoBilling & subscriptions

Database Schema

All tables are defined in shared/schema.ts using Drizzle ORM. The schema serves as the single source of truth for both backend queries and frontend types.

Core Tables

users

Central user accounts table. Every resource is owned by a user.

ColumnTypeNotes
idvarchar (PK, UUID)Auto-generated
emailvarchar (unique)Login identifier
passwordtextbcrypt hashed
nametextDisplay name
roletext"user", "admin", "super_admin"
planTypetext"free", "pro"
planExpiresAttimestampSubscription expiry
creditsintegerAvailable credits balance
isActivebooleanAccount enabled
isDeletedbooleanSoft delete flag
stripeCustomerIdtextStripe customer link
kycStatustextKYC verification status
timezonetextUser timezone
createdAt, updatedAttimestampAudit timestamps
agents

AI agent configurations. Each agent belongs to a user and can be of type "incoming" or "flow".

ColumnTypeNotes
idvarchar (PK)UUID
userIdvarchar (FK → users)Owner
nametextAgent display name
typetext"incoming" or "flow"
telephonyProvidertext"twilio", "plivo", "elevenlabs"
systemPrompttextAI system instructions
firstMessagetextOpening greeting
llmModeltexte.g. "gpt-4o-mini"
temperaturerealLLM temperature 0-1
languagetextAgent language code
elevenLabsAgentIdtextRemote ElevenLabs agent
elevenLabsVoiceIdtextVoice selection
transferEnabledbooleanAllow human transfer
transferPhoneNumbertextTransfer destination
flowIdvarchar (FK → flows)Linked flow for flow agents
knowledgeBaseIdstext[]Attached KB document IDs
configjsonbExtended configuration
isActivebooleanEnabled/disabled
campaigns

Bulk outbound calling campaigns linked to an agent and phone number.

ColumnTypeNotes
idvarchar (PK)UUID
userIdvarchar (FK → users)Owner
agentIdvarchar (FK → agents)AI agent to use
phoneNumberIdvarchar (FK → phone_numbers)Caller ID
name, goal, scripttextCampaign metadata
statustext"pending", "active", "completed", "failed"
totalContactsintegerTotal leads
completedCalls, successfulCalls, failedCallsintegerProgress counters
scheduledFortimestampDelayed start time
scheduleTimezonetextIANA timezone
retryEnabledbooleanAuto-retry failed calls
contacts

Leads within a campaign. Created by CSV upload.

ColumnTypeNotes
idvarchar (PK)UUID
campaignIdvarchar (FK → campaigns, CASCADE)Parent campaign
firstName, lastNametextContact name
phonetext (NOT NULL)Phone number
emailtextOptional email
customFieldsjsonbExtra CSV columns
statustext"pending", "completed", "failed", "in_progress"
calls

Record of every call made through the platform (Twilio/ElevenLabs).

ColumnTypeNotes
idvarchar (PK)UUID
userIdvarchar (FK → users)Owner
campaignIdvarchar (FK → campaigns)Source campaign
contactIdvarchar (FK → contacts)Called contact
statustext"initiated", "ringing", "in-progress", "completed", "failed"
callDirectiontext"outbound" or "inbound"
durationintegerSeconds
transcripttextFull conversation text
aiSummarytextAI-generated summary
sentimenttextCall sentiment analysis
recordingUrltextAudio recording link
wasTransferredbooleanTransferred to human
flows

Visual conversation flows built with React Flow editor.

ColumnTypeNotes
idvarchar (PK)UUID
userIdvarcharOwner
name, descriptiontextMetadata
nodesjsonbReact Flow node array
edgesjsonbReact Flow edge array
compiledSystemPrompttextCompiled LLM prompt
compiledStatesjsonbState machine representation
compiledToolsjsonbFunction calling tools
isTemplatebooleanSystem template flag
HR Tables: jobs, candidates, interview_sessions, candidate_pipeline_history
TableKey ColumnsNotes
jobsid, userId (FK), agentId (FK), flowId (FK), title, department, location, type, salaryRange, statusJob postings with optional AI agent assignment
candidatesid, jobId (FK), userId (FK), firstName, lastName, email, phone, cvFilePath, cvText, status, aiScreeningScore, aiScreeningEvaluationApplicants with AI-scored CVs
interview_sessionsid, userId, jobId (FK), candidateId (FK), callId (FK), status, overallScore, questionScores (jsonb), aiEvaluation, aiRecommendationAI interview records with scoring
candidate_pipeline_historyid, candidateId (FK), jobId (FK), stage, notes, movedAt, movedByKanban pipeline stage tracking
Other Tables
TablePurpose
phone_numbersTwilio phone numbers owned by users
incoming_connectionsPhone number → agent mapping for inbound
incoming_agentsDedicated inbound agent config
knowledge_baseRAG documents for agent context
credit_transactionsCredit purchase/deduction ledger
plansSubscription tier definitions
website_widgetsEmbeddable voice interview widgets
webhook_subscriptionsUser-configured webhook endpoints
webhook_deliveriesDelivery log for webhook events
prompt_templatesReusable AI prompt library
email_templatesTransactional email templates
global_settingsPlatform-wide configuration KV store
seo_settingsSEO meta tags configuration
llm_modelsAvailable LLM model definitions
eleven_labs_credentialsAPI key pool for ElevenLabs
openai_credentialsAPI key pool for OpenAI
plivo_credentialsPlivo telephony credentials
refresh_tokensJWT refresh token store
otp_verificationsEmail OTP tracking
notificationsIn-app notification system
api_keysREST API authentication keys
invoicesGenerated PDF invoices
flow_executionsRuntime state for active flows
plivo_callsPlivo-specific call records
twilio_openai_callsTwilio+OpenAI call records
hr_callsHR module call tracking

Key Relationships

Authentication & Authorization

Token Flow

Login Request (email + password)
       │
       ▼
   Validate credentials (bcrypt.compare)
       │
       ▼
   Generate Access Token (JWT, 15min expiry)
   Generate Refresh Token (random 64-char, 30-day expiry)
       │
       ├──► Access Token → Response body
       └──► Refresh Token → HttpOnly Secure Cookie (SHA-256 hashed in DB)
       
   On API Request:
       Authorization: Bearer <access_token>
       │
       ▼
   authenticateToken middleware → verify JWT → attach userId + userRole
       
   On Token Expiry:
       POST /api/auth/refresh (cookie-based)
       │
       ▼
   Validate refresh token hash → Issue new access token

Role Hierarchy

RoleAccess LevelDescription
userUser dashboard (/app/*)Standard user with own agents, campaigns, billing
adminAdmin panel (/admin/*) + User dashboardFull platform control: settings, user management, analytics. Primary admin role enforced by server middleware.
team_memberPermission-based (/app/*)Organization member with granular RBAC permissions. Uses session tokens (not JWT).
admin_team_memberPermission-based (/admin/*)Admin staff with section-level permissions (e.g., billing, users). Checked via requireAdminPermission middleware.
The role field in the users table supports "user" and "admin". Admin-level access is enforced server-side via requireRole('admin') and checkAdminOrTeamMember middleware. Team members use separate 64-character hex session tokens with permission-based access control.

Middleware Chain

Request → Rate Limiter → authenticateToken → checkUserActive → requireRole / requireAdminPermission → Route Handler
MiddlewareFilePurpose
authenticateTokenserver/middleware/auth.tsValidates JWT, attaches userId to request
authenticateAnyTokenserver/middleware/auth.tsAccepts user JWT OR admin team session token
checkUserActiveserver/middleware/auth.tsEnsures account is not suspended/deleted
requireRole(role)server/middleware/auth.tsChecks user has specific role
checkAdminOrTeamMemberserver/middleware/admin-auth.tsValidates admin or team member access
requireAdminPermission(section, sub, action)server/middleware/admin-auth.tsGranular RBAC for admin team members
checkActiveMembershipserver/middleware/auth.tsRequires active Pro subscription

API Reference

Authentication

MethodPathAuthDescription
POST/api/auth/send-otpNoneSend email verification OTP for registration
POST/api/auth/verify-otpNoneVerify registration OTP
POST/api/auth/registerNoneRegister new user account
POST/api/auth/loginNoneLogin with email/password, returns JWT
POST/api/auth/refreshCookieRefresh access token using cookie
POST/api/auth/logoutCookieInvalidate refresh token, clear cookie
POST/api/auth/forgot-password/send-otpNoneSend password reset OTP
POST/api/auth/forgot-password/resetNoneReset password after OTP verification

Agents

MethodPathAuthDescription
GET/api/agentsJWTList all user's agents
POST/api/agentsJWTCreate new AI agent
GET/api/agents/:idJWTGet agent details
PATCH/api/agents/:idJWTUpdate agent configuration
DELETE/api/agents/:idJWTDelete agent and remote resources

Campaigns & Contacts

MethodPathAuthDescription
GET/api/campaignsJWTList user's campaigns
POST/api/campaignsJWTCreate new campaign
GET/api/campaigns/:idJWTGet campaign details
DELETE/api/campaigns/:idJWTDelete campaign
POST/api/campaigns/:id/contacts/uploadJWTUpload CSV contacts
GET/api/campaigns/:id/callsJWTList campaign calls
GET/api/campaigns/:id/exportJWTExport results as CSV
POST/api/campaigns/:id/batch/cancelJWTCancel running batch job

Phone Numbers

MethodPathAuthDescription
GET/api/phone-numbersJWTList owned + system pool numbers
GET/api/phone-numbers/searchJWTSearch available Twilio numbers
POST/api/phone-numbers/buyJWTPurchase number with credits
DELETE/api/phone-numbers/:idJWTRelease phone number

Calls & Analytics

MethodPathAuthDescription
GET/api/callsJWTList calls with pagination
GET/api/calls/:idJWTCall details + transcript
GET/api/calls/:id/recordingJWTDownload call recording
GET/api/dashboardJWTDashboard metrics
GET/api/analyticsJWTTime-series analytics
POST/api/analytics/export-pdfJWTGenerate PDF analytics report

Billing & Subscriptions

MethodPathAuthDescription
GET/api/plansNoneList subscription plans
GET/api/subscriptions/my-subscriptionJWTCurrent subscription details
GET/api/credits/transactionsJWTCredit history
GET/api/billing-profileJWTGet billing info
PUT/api/billing-profileJWTUpdate billing info

Admin Endpoints

MethodPathAuthDescription
GET/api/admin/analyticsAdminPlatform-wide analytics
GET/api/admin/settingsAdminGet platform settings
POST/api/admin/users/:id/creditsAdminAdd/deduct user credits
PATCH/api/admin/users/:id/limitsAdminSet user limits
GET/api/admin/pluginsAdminList installed plugins

AI Agent System

Agents are the core unit of the platform. Each agent is an AI persona configured with voice, personality, and instructions.

Agent Types

TypeDescriptionUse Case
Natural (Incoming)LLM-powered free-form conversationInbound call handling, customer support
FlowVisual flow editor with branching logicStructured interviews, surveys, screenings

Voice Engines

EngineProvider StackKey Feature
ElevenLabs NativeElevenLabs Conversational AI + TwilioUltra-realistic voices, Batch API
OpenAI Realtime + TwilioOpenAI Realtime API + TwilioGPT-powered real-time conversation
OpenAI Realtime + PlivoOpenAI Realtime API + PlivoAlternative telephony provider
ElevenLabs SIP + PlivoElevenLabs + Plivo SIP TrunkSIP-based integration

Configuration Options

Campaign Execution Engine

Execution Flow

Create Campaign → Upload CSV Contacts → Start Campaign
       │
       ▼
   CampaignExecutor validates:
   - Agent exists and is configured
   - Phone number assigned
   - Contacts have valid phone numbers
   - User has sufficient credits
       │
       ▼
   Route to engine based on telephonyProvider:
   ├── ElevenLabs → BatchCallingService (ElevenLabs Batch API)
   ├── Plivo → PlivoBatchCallingService (local concurrency)
   └── Twilio → TwilioOpenAIBatchCallingService (local concurrency)
       │
       ▼
   Pre-create call records in DB (batch insert)
       │
       ▼
   Execute calls with concurrency control
       │
       ▼
   Webhooks update call status, transcript, duration
       │
       ▼
   Campaign marked "completed" when all contacts processed

Key Features

Key Files

FilePurpose
server/services/campaign-executor.tsMain orchestration and engine routing
server/services/campaign-scheduler.tsTimezone-aware scheduling and status polling
server/services/batch-calling.tsElevenLabs Batch API wrapper
server/infrastructure/bullmq/Redis-based distributed queue (optional)

Flow Builder System

A visual conversation designer built on React Flow. Users create branching conversational logic using drag-and-drop nodes.

Node Types

Flow Compilation

When saved, flows are compiled into executable state machines stored in compiledStates, compiledSystemPrompt, and compiledTools fields. The flow compilation is handled by server/services/elevenlabs-flow-compiler.ts (for ElevenLabs agents) and the flow agent service (server/services/flow-agent.ts), which convert visual nodes into LLM-compatible instructions.

Payment Infrastructure

Supported Gateways

GatewayRegionCurrenciesFeatures
StripeGlobalUSD, EUR, GBP, +135Checkout Sessions, Subscriptions, Webhooks
RazorpayIndiaINROrders, Subscriptions, UPI
PayPalGlobalUSD, EUR, GBP, +20REST Orders, Billing Subscriptions
PaystackAfricaNGN, GHS, ZAR, KES, USDTransactions, Plans, Subscriptions
MercadoPagoLatin AmericaBRL, ARS, MXN, CLP, COPPreferences, PreApproval Plans

Credit System

Invoice Generation

Uses pdfkit to generate branded PDF invoices after completed transactions. Stored in ./data/invoices/ and linked in the invoices table.

HR / Hiring Module

Workflow

Create Job Posting → Upload CVs / Receive Widget Applications
       │
       ▼
   AI CV Screening (score + evaluation)
       │
       ▼
   Candidates enter Pipeline (stages: Applied → Screening → Interview → Offer → Hired)
       │
       ▼
   Schedule AI Phone Interview (via campaign executor or widget callback)
       │
       ▼
   Interview Session recorded with scoring, evaluation, recommendation
       │
       ▼
   Move through pipeline stages → Hire or Reject

Key Features

Webhook System

Users can subscribe to platform events and receive real-time HTTP notifications.

Knowledge Base (RAG)

Users upload documents that get processed into chunks, embedded, and injected as context into AI agent conversations.

Client-Side Architecture

Component Structure

client/src/
├── App.tsx                  # Root component with routing and guards
├── pages/                   # Route-based page components
│   ├── LandingPage.tsx      # Public landing page
│   ├── LoginPage.tsx        # Auth (login + register)
│   ├── Dashboard.tsx        # User dashboard
│   ├── Agents.tsx           # Agent management
│   ├── JobsPage.tsx         # HR job listings
│   ├── CandidatesPage.tsx   # Candidate management
│   ├── PipelinePage.tsx     # Hiring pipeline
│   ├── FlowBuilderPage.tsx  # Visual flow editor
│   ├── FlowsPage.tsx        # Flow listing
│   ├── Billing.tsx          # Subscription & credits
│   ├── Settings.tsx         # User profile
│   ├── AdminDashboard.tsx   # Admin panel
│   ├── AdminCampaignDetail.tsx
│   ├── InstallWizard.tsx    # First-time setup
│   └── policies/            # Privacy, Terms, Cookies
├── components/
│   ├── ui/                  # shadcn/ui primitives
│   ├── landing/             # Landing page sections
│   └── admin/               # Admin-specific components
├── contexts/
│   ├── plugin-registry.tsx  # Runtime plugin UI injection
│   └── dynamic-languages.tsx # i18n dynamic loading
├── hooks/                   # useToast, useAuth, etc.
├── lib/
│   ├── queryClient.ts       # TanStack Query config
│   ├── auth-storage.ts      # Token persistence
│   └── formatters.ts        # Date, currency formatters
└── i18n/                    # Translation files (11 languages)

Routing & Guards

Route Groups

PrefixGuardSidebarAccess
/ (public)NoneNone (public layout)Everyone
/app/*UserGuardAppSidebarAuthenticated users
/app/* (team)UserGuardTeamMemberSidebarTeam members (permission-filtered)
/admin/*AdminGuardAdminSidebarAdmin role users
/admin/* (team)AdminTeamGuardAdminTeamMemberSidebarAdmin team members

Guard Logic

Pages Reference

Public Pages

RouteComponentDescription
/LandingPageMain marketing page
/loginLoginPageUser authentication
/registerLoginPageUser registration
/featuresFeaturesPageProduct features
/pricingPricingPagePlans and pricing
/use-casesUseCasesPageUse case examples
/contactContactContact form
/blogBlogBlog index
/privacyPrivacyPolicyPrivacy policy
/termsTermsOfServiceTerms of service
/team/loginTeamMemberLoginTeam member auth
/installInstallWizardFirst-time setup wizard

User Dashboard Pages (/app/*)

RouteComponentDescription
/appDashboardMain dashboard with metrics
/app/jobsJobsPageJob listings management
/app/candidatesCandidatesPageCandidate management
/app/pipelinePipelinePageHiring pipeline view
/app/cv-uploadCVUploadPageBulk CV upload
/app/interviewsInterviewsPageInterview management
/app/analyticsHRAnalyticsPageHR analytics
/app/agentsAgentsAI Agent management
/app/knowledge-baseKnowledgeBaseRAG document management
/app/flowsFlowsPageAutomation flows list
/app/flows/newFlowBuilderPageCreate new flow
/app/flows/:idFlowBuilderPageEdit existing flow
/app/phone-numbersPhoneNumbersPhone number management
/app/tools/widgetsWidgetsPageHiring widget configuration
/app/billingBillingSubscription & credits
/app/upgradeUpgradePlan upgrade
/app/settingsSettingsUser profile settings

Plugin System

Architecture

Plugins are self-contained extensions with their own backend routes, frontend UI, and database migrations.

plugins/
├── my-plugin/
│   ├── plugin.json          # Manifest: metadata, entry points, DB requirements
│   ├── index.ts              # Backend: Express route registration
│   ├── frontend/
│   │   └── index.tsx         # Frontend: UI component registration
│   ├── dist/
│   │   └── bundle.js         # Built frontend bundle
│   └── migrations/
│       └── 001_create_tables.sql

Lifecycle

  1. Discovery: server/plugins/loader.ts scans /plugins for directories with plugin.json
  2. Enable Check: Reads global_settings table for plugin_[name]_enabled = true
  3. Backend Registration: Imports and calls the registerFunction from the manifest
  4. Frontend Loading: PluginBootstrapper fetches /api/plugins/capabilities, downloads bundles
  5. UI Injection: Bundles call window.__AGENTHR_PLUGIN_REGISTRY__ to register tabs and menu items

Plugin Management API

MethodPathDescription
GET/api/plugins/capabilitiesList enabled plugins and bundle URLs
GET/api/plugins/:name/bundleServe plugin frontend JS bundle
GET/api/plugins/healthPlugin health diagnostics
GET/api/admin/pluginsAdmin: list all plugins with status

REST API Plugin

Exposes platform data via authenticated REST endpoints with API key management and professional documentation.

Endpoint GroupPathAuth
Calls/api/v1/callsAPI Key
Campaigns/api/v1/campaignsAPI Key
Agents/api/v1/agentsAPI Key
Contacts/api/v1/contactsAPI Key
Credits/api/v1/creditsAPI Key
Analytics/api/v1/analyticsAPI Key
Webhooks/api/v1/webhooksAPI Key
API Keys/api/user/api-keysJWT
Documentation/api/docsPublic

SIP Engine Plugin

Enables custom SIP trunk integration for voice calls, allowing users to bring their own telephony infrastructure.

EndpointAuthPurpose
/api/sip/trunksJWTManage SIP credentials
/api/sip/phone-numbersJWTImport SIP phone numbers
/api/admin/sipAdminGlobal SIP configuration
/api/openai-sip/webhookNoneOpenAI SIP webhook handler

Team Management Plugin

Adds RBAC (Role-Based Access Control) and multi-user sub-accounts for organizations.

EndpointAuthPurpose
/api/team/authPublicTeam member login
/api/team/membersJWTCRUD team members
/api/team/rolesJWTCustom role management
/api/team/permissionsJWTPermission configuration
/api/admin/teamsAdminGlobal team oversight
/api/admin/teamAdminAdmin sub-admin management

Development Setup

Prerequisites

Installation Steps

# 1. Extract the package
unzip AgentHR-v1.0.0-complete.zip
cd AgentHR-v1.0.0

# 2. Copy environment template
cp .env.example .env

# 3. Run setup (auto-generates SESSION_SECRET and JWT_SECRET)
npm run setup

# 4. Edit .env with your configuration
#    - Database credentials
#    - Twilio / ElevenLabs API keys
#    - SMTP settings
#    - Payment gateway keys (optional)

# 5. Install dependencies
npm install

# 6. Push database schema
npm run db:push

# 7. Seed system data (plans, models, templates, etc.)
npm run db:seed

# 8. Build plugins (if modifying plugin source)
npm run build:plugins

# 9. Build for production
npm run build

# 10. Start the application
bash scripts/production.sh start

Development Mode

# Start dev server with hot reload
npm run dev
# Server runs on http://localhost:5000

npm Scripts

ScriptCommandDescription
npm run devtsx server/index.tsDevelopment server with HMR
npm run buildvite build && esbuild ...Production build
npm run db:pushdrizzle-kit pushSync schema to database
npm run db:generatedrizzle-kit generateGenerate migrations
npm run db:seedtsx server/seed-all.tsSeed system data
npm run build:pluginsnode scripts/build-plugins.jsBuild plugin frontend bundles

Environment Variables

Required

VariableDescriptionExample
DATABASE_URLPostgreSQL connection stringpostgresql://user:pass@host:5432/db
SESSION_SECRETSession encryption key (64 chars)Auto-generated by setup
JWT_SECRETJWT signing key (64 chars)Auto-generated by setup
APP_URLPublic application URLhttps://agenthr.example.com
APP_DOMAINDomain without protocolagenthr.example.com
PORTServer port5000

Integrations

VariableServiceRequired
TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKENTwilioFor calling
ELEVENLABS_API_KEYElevenLabsFor voice AI
OPENAI_API_KEYOpenAIFor OpenAI Realtime
STRIPE_SECRET_KEY, VITE_STRIPE_PUBLIC_KEYStripeFor payments
SMTP_HOST, SMTP_USER, SMTP_PASSEmailFor OTP/notifications
RAZORPAY_KEY_ID, RAZORPAY_KEY_SECRETRazorpayOptional
PAYPAL_CLIENT_ID, PAYPAL_CLIENT_SECRETPayPalOptional
PAYSTACK_SECRET_KEYPaystackOptional
MERCADOPAGO_ACCESS_TOKENMercadoPagoOptional

Optional

VariableDefaultDescription
NODE_ENVdevelopmentEnvironment mode
LOG_LEVELinfoLogging verbosity (debug/info/warn/error)
DEMO_MODEfalseEnable demo account with sample data
ENABLE_BULLMQfalseEnable Redis-based job queue
REDIS_URLRedis connection for BullMQ

Demo Mode

Demo mode creates a pre-populated demo account for showcasing the platform to visitors.

Activation

# In .env file
DEMO_MODE=true

What Gets Created

ResourceCount
Demo Account1 (demo@diploy.in / Demo@123, admin role, pro plan, 1000 credits)
AI Agents3 (HR Screening, Technical Interview, Candidate Follow-up)
Knowledge Base Items4
Campaigns3 (completed, active, pending)
Contacts18
Call Records11 (with transcripts and summaries)
Credit Transactions5
Webhook Subscriptions2
Website Widget1
Jobs4
Candidates12
Interview Sessions4

Behavior

Key Files

FilePurpose
server/demo-mode/index.tsMiddleware, account seeding, data masking
server/demo-mode/seed-demo-data.tsSample data creation for all modules
server/seed-hr-data.tsShared HR data seeder (jobs, candidates)

Production Deployment

Using Production Script

# Start
bash scripts/production.sh start

# Stop
bash scripts/production.sh stop

# Restart
bash scripts/production.sh restart

# View status
bash scripts/production.sh status

# View logs
bash scripts/production.sh logs

Using deploy.sh

# Full deployment (install, build, restart)
bash deploy.sh

Production Checklist


AgentHR Developer Guide v1.0.0

© 2025 Diploy — Bisht Technologies Private Limited

Website: diploy.in | Contact: cs@diploy.in