# AI Coder Master Prompt: IRC Agent Hub (AgentBridge)
## 1. PROJECT OVERVIEW
**Project Name:** IRC Agent Hub (AgentBridge)
**Core Functionality:** AgentBridge is a SaaS platform that empowers users to deploy, manage, and interact with AI agents through versatile transport layers, including traditional IRC and modern web interfaces. It simplifies the process of setting up and running AI agents, offering cost-effective tiered inference and flexible infrastructure options (user-provided VPS or platform-hosted).
**Problem Solved:** The complexity and cost associated with deploying and accessing AI agents. Many users struggle with server management, API key handling, and optimizing inference costs. AgentBridge abstracts these complexities, making AI agents accessible via familiar interfaces like IRC and a user-friendly web chat.
**Value Proposition:** Deploy and interact with your AI agents effortlessly. AgentBridge provides a cost-efficient, flexible, and accessible platform for managing AI agents, bridging the gap between powerful AI capabilities and everyday communication tools.
**Target Audience:** Tech enthusiasts, AI developers, chatbot hobbyists, users needing low-bandwidth communication, and individuals/teams seeking an easier way to deploy and manage AI agents.
## 2. TECH STACK
- **Framework:** Next.js (App Router)
- **Language:** TypeScript
- **Styling:** Tailwind CSS
- **ORM:** Drizzle ORM
- **Database:** PostgreSQL (or SQLite for local development/simplicity)
- **Authentication:** NextAuth.js (or Clerk for quicker setup)
- **UI Components:** shadcn/ui
- **State Management:** React Context API / Zustand (for global state)
- **API Layer:** Server Actions / Route Handlers
- **Real-time (IRC):** `irc-framework` or similar Node.js IRC client library
- **Real-time (Web Chat):** WebSocket (using `socket.io` or native WebSockets)
- **Deployment:** Vercel / Docker
## 3. DATABASE SCHEMA (Drizzle ORM - PostgreSQL Syntax)
```sql
-- Users Table (for authentication)
CREATE TABLE users (
id TEXT PRIMARY KEY,
name TEXT,
email TEXT UNIQUE NOT NULL,
emailVerified TIMESTAMP WITH TIME ZONE,
image TEXT,
createdAt TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updatedAt TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
-- Accounts Table (for NextAuth.js)
CREATE TABLE accounts (
id TEXT PRIMARY KEY,
userId TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
type TEXT NOT NULL,
provider TEXT NOT NULL,
providerAccountId TEXT NOT NULL,
refresh_token TEXT,
access_token TEXT,
expires_at BIGINT,
token_type TEXT,
scope TEXT,
id_token TEXT,
session_state TEXT,
UNIQUE (provider, providerAccountId)
);
-- Sessions Table (for NextAuth.js)
CREATE TABLE sessions (
id TEXT PRIMARY KEY,
sessionToken TEXT UNIQUE NOT NULL,
userId TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
expires TIMESTAMP WITH TIME ZONE NOT NULL
);
-- Verification Tokens Table (for NextAuth.js)
CREATE TABLE verification_tokens (
identifier TEXT NOT NULL,
token TEXT NOT NULL,
expires TIMESTAMP WITH TIME ZONE NOT NULL,
PRIMARY KEY (identifier, token)
);
-- AI Agents Table
CREATE TABLE agents (
id TEXT PRIMARY KEY,
userId TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
name TEXT NOT NULL,
description TEXT,
model_provider TEXT NOT NULL, -- e.g., 'openai', 'anthropic'
model_name TEXT NOT NULL, -- e.g., 'gpt-4o-mini', 'claude-3-haiku'
inference_cost_cap_per_day REAL DEFAULT 2.00,
transport_layer TEXT NOT NULL, -- e.g., 'irc', 'web'
irc_server TEXT, -- e.g., 'irc.georgelarson.me'
irc_port INTEGER,
irc_channel TEXT,
irc_tls BOOLEAN DEFAULT FALSE,
is_public BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
-- Agent Conversations Table
CREATE TABLE conversations (
id TEXT PRIMARY KEY,
agentId TEXT NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
userId TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
transport_type TEXT NOT NULL, -- 'irc' or 'web'
irc_nick TEXT, -- For IRC
session_id TEXT, -- For Web Chat persistence
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
-- Messages Table
CREATE TABLE messages (
id TEXT PRIMARY KEY,
conversationId TEXT NOT NULL REFERENCES conversations(id) ON DELETE CASCADE,
sender_type TEXT NOT NULL, -- 'user' or 'agent'
content TEXT NOT NULL,
timestamp TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
-- API Keys Table (for users to input their own, e.g., OpenAI keys)
CREATE TABLE api_keys (
id TEXT PRIMARY KEY,
userId TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
provider TEXT NOT NULL, -- e.g., 'openai', 'anthropic'
key TEXT NOT NULL UNIQUE, -- Consider encryption here!
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
-- Infrastructure Settings Table (Optional: for user-managed VPS)
CREATE TABLE infrastructure_settings (
id TEXT PRIMARY KEY,
userId TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
vps_type TEXT, -- 'self_hosted', 'platform_hosted'
vps_details JSONB -- e.g., { ip: '...', ssh_user: '...', private_key: '...' } for self-hosted
);
-- Add indexes for performance
CREATE INDEX idx_agents_userId ON agents(userId);
CREATE INDEX idx_conversations_agentId ON conversations(agentId);
CREATE INDEX idx_conversations_userId ON conversations(userId);
CREATE INDEX idx_messages_conversationId ON messages(conversationId);
CREATE INDEX idx_api_keys_userId ON api_keys(userId);
```
## 4. CORE FEATURES & USER FLOWS
**4.1 User Authentication & Onboarding
- **Flow:**
1. User visits the landing page.
2. Clicks "Sign Up" or "Sign In".
3. Redirected to authentication provider (e.g., Google, GitHub via NextAuth.js).
4. Upon successful login, user is redirected to their Dashboard.
5. First-time users see a brief onboarding tour highlighting key features.
- **Edge Cases:** Auth errors, session expiry, email verification (if using email/password).
**4.2 Agent Creation & Configuration
- **Flow:**
1. User navigates to "Create Agent" page from Dashboard.
2. **Form Fields:**
- Agent Name (e.g., "Support Bot", "Code Helper")
- Description (Optional)
- **Model Provider:** Dropdown (OpenAI, Anthropic, etc.)
- **Model Name:** Dropdown (dynamically populated based on provider, e.g., `gpt-4o-mini`, `claude-3-haiku`, `claude-3-sonnet`)
- **Tiered Inference:** Checkbox to enable/disable.
- If enabled: Set Daily Cost Cap (e.g., $2.00). System will auto-switch to cheaper models (like Haiku) for general chat and more powerful ones (like Sonnet) only when needed for tool use/complex tasks.
- **Transport Layer:** Radio Buttons/Dropdown (`IRC`, `Web`, `Both`).
- If `IRC`: Fields for Server Address, Port, Channel Name, TLS (toggle).
- If `Web`: Automatically handled by the platform (generates a unique chat URL).
- **API Key:** Option to select a pre-saved API key from their account or input a new one (which gets saved).
3. User clicks "Create Agent".
4. Agent is saved to the `agents` table. User is redirected to their Dashboard showing the new agent.
- **Edge Cases:** Invalid model names, missing API keys, cost cap exceeded (handled by monitoring, not creation).
**4.3 Agent Interaction (Web Chat)
- **Flow:**
1. User clicks on an agent in their Dashboard or a direct chat link.
2. A dedicated chat interface (e.g., `app/agents/[agentId]/chat` or `app/chat/[sessionId]`) loads.
3. **UI:** A chat window with message history, an input field, and a send button.
4. User types a message and hits Enter/Send.
5. **Frontend:** Message is added optimistically to the UI and sent via WebSocket to the backend.
6. **Backend (WebSocket Handler):**
- Receives message.
- Retrieves relevant `agent` and `conversation` data.
- Determines the appropriate AI model based on the request and cost settings (using tiered inference logic if enabled).
- Constructs the prompt for the AI model, including conversation history.
- **Crucially:** Calls the AI provider API (OpenAI, Anthropic) using the user's or platform's API key.
- Receives the AI response.
- Saves both the user message and AI response to the `messages` table.
- Sends the AI response back to the specific user's WebSocket connection.
7. **Frontend:** Receives AI response via WebSocket and displays it in the chat interface.
- **Edge Cases:** WebSocket disconnects, API errors (rate limits, invalid key, model unavailable), long responses, empty messages.
**4.4 Agent Interaction (IRC)
- **Flow:**
1. User connects to the specified IRC server (`irc_server`, `irc_port`) using an IRC client.
2. Joins the specified channel (`irc_channel`).
3. **Platform Backend (IRC Client):**
- The backend runs an IRC client instance for each configured IRC agent.
- It connects to the server and joins the channel.
- It listens for messages in the channel.
- **Message Handling:** If a message is directed at the bot (e.g., starts with the bot's nickname or a command prefix), the backend processes it.
4. **Processing:** Similar to web chat – retrieves agent config, determines model, calls AI API.
5. **Response:** The backend sends the AI's response back into the IRC channel using the agent's IRC nickname.
6. **User Experience:** Users interact as they would with any other IRC bot.
- **Edge Cases:** IRC server disconnects, NickServ/ChanServ registration, flood protection, messages not directed at the bot, handling private messages (if implemented).
**4.5 API Key Management
- **Flow:**
1. User navigates to "API Keys" section in Settings.
2. Clicks "Add API Key".
3. Selects Provider (OpenAI, Anthropic).
4. Pastes their API Key.
5. Clicks "Save".
6. **Security:** The key is encrypted at rest in the `api_keys` table.
7. When creating/editing an agent, the user can select a saved key.
- **Edge Cases:** Invalid key format, duplicate keys, security breaches.
**4.6 Cost Monitoring & Control
- **Flow:**
1. Backend periodically checks the total cost incurred by each agent against its `inference_cost_cap_per_day`.
2. Uses AI provider's usage APIs or estimates based on token counts.
3. If an agent is approaching its cap, it might issue a warning or temporarily disable further expensive inferences.
4. Users can view their current spending and daily costs on their Dashboard.
- **Edge Cases:** Inaccurate cost tracking, delayed reporting from API providers.
## 5. API & DATA FETCHING
- **Authentication:** NextAuth.js handles session management. All API routes and Server Actions are protected by default, requiring a valid session.
- **Key API Routes / Server Actions (App Router Structure):
- **`POST /api/auth/signup` / `POST /api/auth/login`:** (Handled by NextAuth.js provider callbacks)
- **`GET /api/agents` (Server Action):** Fetches all agents for the logged-in user.
- **Response:** `Array<Agent>`
- **`POST /api/agents` (Server Action):** Creates a new agent.
- **Request Body:** `CreateAgentInput` (from form)
- **Response:** `Agent` or success status.
- **`GET /api/agents/[agentId]` (Server Action):** Fetches details for a specific agent.
- **Response:** `Agent`
- **`PUT /api/agents/[agentId]` (Server Action):** Updates an existing agent.
- **Request Body:** `UpdateAgentInput`
- **Response:** Updated `Agent` or success status.
- **`DELETE /api/agents/[agentId]` (Server Action):** Deletes an agent.
- **Response:** Success status.
- **`POST /api/agents/[agentId]/sendMessage` (WebSocket/Route Handler):** Handles incoming messages from web clients.
- **Request Body:** `{ message: string, conversationId?: string }`
- **Response:** AI's reply `{ reply: string, conversationId: string }` (via WebSocket or direct response)
- **`GET /api/keys` (Server Action):** Fetches user's saved API keys.
- **Response:** `Array<ApiKey>`
- **`POST /api/keys` (Server Action):** Saves a new API key.
- **Request Body:** `{ provider: string, key: string }`
- **Response:** Saved `ApiKey` or success status.
- **Data Fetching in Components:** Primarily using Server Actions for data fetching on the server (React Server Components) and Client Components fetching data via API routes or Server Actions marked with `'use server'`. For real-time chat, WebSockets are used.
- **WebSocket Server:** A separate service or integrated into Next.js API routes/Server Actions, managing connections, message broadcasting, and AI interaction orchestration.
## 6. COMPONENT BREAKDOWN (Next.js App Router)
- **`app/layout.tsx`:** Root layout (HTML, Head, global styles, Context providers).
- **`app/page.tsx`:** Landing Page (marketing content, Sign Up/In CTA).
- **`app/(authenticated)/layout.tsx`:** Authenticated layout (Sidebar Navigation, Header).
- **`app/(authenticated)/dashboard/page.tsx`:** Dashboard
- **Components:** AgentList (displays agents), StatsOverview (usage, cost), CreateAgentButton.
- **State:** Fetches and displays agent data. Manages loading/error states.
- **`app/(authenticated)/agents/new/page.tsx`:** Create New Agent Page
- **Components:** AgentForm (all fields for agent creation/editing).
- **State:** Manages form state, handles API calls for creation.
- **`app/(authenticated)/agents/[agentId]/edit/page.tsx`:** Edit Agent Page
- **Components:** AgentForm (pre-filled with agent data).
- **State:** Fetches agent data, manages form state, handles API calls for updates.
- **`app/(authenticated)/settings/page.tsx`:** Settings Page
- **Components:** ProfileForm, ApiKeyManager (list, add, delete keys), InfrastructureSettings.
- **State:** Manages user profile, API keys, infrastructure config.
- **`app/chat/[sessionId]/page.tsx` (or `app/agents/[agentId]/chat/page.tsx`):** Web Chat Interface
- **Components:** ChatWindow (displays messages, input field, send button), MessageItem (individual message bubble).
- **State:** Manages message history, user input, WebSocket connection status. Uses Zustand or Context for state.
- **`components/ui/`:** Re-usable shadcn/ui components (Button, Input, Card, Select, Dialog, etc.).
- **`components/layout/`:** Sidebar, Header, Footer components.
- **`components/agent/`:** AgentListItem, AgentForm.
- **`components/chat/`:** ChatWindow, MessageItem.
## 7. UI/UX DESIGN & VISUAL IDENTITY
- **Design Style:** Minimalist Clean with subtle futuristic accents.
- **Color Palette:**
- Primary: `#6366F1` (Indigo-500)
- Secondary: `#8B5CF6` (Violet-500)
- Accent: `#34D399` (Emerald-400)
- Background: `#1F2937` (Slate-800 - Dark Mode First)
- Surface: `#374151` (Slate-700)
- Text (Primary): `#E5E7EB` (Slate-200)
- Text (Secondary): `#9CA3AF` (Slate-400)
-destructive: `#F87171` (Red-400)
- **Typography:**
- Headings: Inter (Variable Font)
- Body Text: Inter (Variable Font)
- **Layout:**
- Use a sidebar for navigation in authenticated sections.
- Dashboard: Card-based layout for agents and stats.
- Chat: Classic chat layout, full-width or contained.
- Forms: Clear labels, ample spacing, intuitive grouping.
- **Visual Elements:** Subtle gradients in buttons or backgrounds, clean icons, smooth transitions.
- **Responsiveness:** Mobile-first approach. Sidebar collapses into a hamburger menu on smaller screens. Chat interfaces adapt to screen width. All components should be fully responsive.
## 8. SAMPLE/MOCK DATA
**Agents:**
1. `{ id: 'agent-123', userId: 'user-abc', name: 'Help Desk Bot', description: 'Answers common support questions.', model_provider: 'openai', model_name: 'gpt-4o-mini', inference_cost_cap_per_day: 1.50, transport_layer: 'web', irc_server: null, irc_port: null, irc_channel: null, irc_tls: false, is_public: false }`
2. `{ id: 'agent-456', userId: 'user-abc', name: 'IRC Greeter', description: 'Greets users in the lobby channel.', model_provider: 'anthropic', model_name: 'claude-3-haiku', inference_cost_cap_per_day: 0.50, transport_layer: 'irc', irc_server: 'irc.example.com', irc_port: 6697, irc_channel: '#lobby', irc_tls: true, is_public: false }`
3. `{ id: 'agent-789', userId: 'user-def', name: 'Code Assistant', description: 'Helps with Python code snippets.', model_provider: 'openai', model_name: 'gpt-4o', inference_cost_cap_per_day: 5.00, transport_layer: 'both', irc_server: 'irc.code.net', irc_port: 6667, irc_channel: '#dev', irc_tls: false, is_public: true }`
**Conversations:**
1. `{ id: 'conv-001', agentId: 'agent-123', userId: 'user-abc', transport_type: 'web', irc_nick: null, session_id: 'sess-web-xyz', created_at: '2024-07-26T10:00:00Z' }`
2. `{ id: 'conv-002', agentId: 'agent-456', userId: 'user-abc', transport_type: 'irc', irc_nick: 'greeter-bot', session_id: null, created_at: '2024-07-26T11:00:00Z' }`
**Messages:**
1. `{ id: 'msg-001', conversationId: 'conv-001', sender_type: 'user', content: 'How do I reset my password?', timestamp: '2024-07-26T10:01:00Z' }`
2. `{ id: 'msg-002', conversationId: 'conv-001', sender_type: 'agent', content: 'You can reset your password by clicking the