Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(agent): db schema + plan flag for the in-product AI agent (#120)
Gökhan Geyikf3cb097fcc56
diff --git a/supabase/migrations/00009_agent_chat_schema.sql b/supabase/migrations/00009_agent_chat_schema.sqlnew file mode 100644index 000000000..d74bc1aed--- /dev/null+++ b/supabase/migrations/00009_agent_chat_schema.sql@@ -0,0 +1,141 @@+-- In-product AI agent: schema for conversations, messages, and per-user+-- monthly token usage (#94 Phase 2).+--+-- Three tables, each scoped to a user inside an organization:+--+-- agent_conversations one chat thread; "+ new chat" creates a row+-- agent_messages ordered messages within a thread; tool calls+-- stored alongside text content as jsonb+-- agent_token_usage monthly bucket per user so the cost-guard can+-- enforce plan-level quotas without scanning the+-- messages table on every request+--+-- RLS scopes everything to auth.uid() — users can only see their own+-- conversations / messages / usage. The chat API runs server-side with+-- supabaseAdmin so it can write tool results that the user didn't author;+-- service_role bypasses RLS naturally.++-- ── agent_conversations ──────────────────────────────────────────────────+CREATE TABLE IF NOT EXISTS public.agent_conversations (+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),+ user_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,+ organization_id uuid NOT NULL REFERENCES public.organizations(id) ON DELETE CASCADE,+ -- Optional default brand context: a new chat opened from a brand-specific+ -- page can pin the conversation to that brand so subsequent tool calls+ -- don't need to re-resolve the brand id every turn. Null = no pin.+ brand_id uuid REFERENCES public.brands(id) ON DELETE SET NULL,+ title text NOT NULL DEFAULT 'New conversation',+ created_at timestamptz NOT NULL DEFAULT now(),+ updated_at timestamptz NOT NULL DEFAULT now()+);++-- Recency-sorted lookup per user is the hot path (sidebar list).+CREATE INDEX IF NOT EXISTS idx_agent_conversations_user_updated+ ON public.agent_conversations (user_id, updated_at DESC);+++-- ── agent_messages ──────────────────────────────────────────────────────+-- Roles match the Vercel AI SDK / OpenAI shape so we can hydrate the chat+-- panel and feed the SDK's tool-calling loop without re-mapping:+--+-- user regular user message; `content` holds the text+-- assistant model output; `content` may be empty if the model only+-- emitted tool calls; `tool_calls` holds the array+-- tool result of a tool call; `tool_call_id` joins back to the+-- assistant message's tool_calls entry; `tool_result` holds+-- the JSON payload returned by the tool+CREATE TABLE IF NOT EXISTS public.agent_messages (+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),+ conversation_id uuid NOT NULL REFERENCES public.agent_conversations(id) ON DELETE CASCADE,+ role text NOT NULL CHECK (role IN ('user', 'assistant', 'tool')),+ content text NOT NULL DEFAULT '',+ tool_calls jsonb,+ tool_call_id text,+ tool_name text,+ tool_result jsonb,+ -- Token usage attributed to this message for analytics + the monthly+ -- bucket below. Null on user/tool rows; filled on the assistant+ -- response once the SDK stream finishes.+ prompt_tokens int,+ completion_tokens int,+ created_at timestamptz NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS idx_agent_messages_conv_created+ ON public.agent_messages (conversation_id, created_at);+++-- ── agent_token_usage ───────────────────────────────────────────────────+-- One row per (user, organization, year_month). The chat API upserts on+-- this row at the end of every streamed response, so quota enforcement is+-- one SELECT instead of an aggregate scan over agent_messages.+CREATE TABLE IF NOT EXISTS public.agent_token_usage (+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),+ user_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,+ organization_id uuid NOT NULL REFERENCES public.organizations(id) ON DELETE CASCADE,+ -- 'YYYY-MM' (UTC). Stored as text so it's portable + lex-sortable.+ year_month text NOT NULL,+ prompt_tokens bigint NOT NULL DEFAULT 0,+ completion_tokens bigint NOT NULL DEFAULT 0,+ created_at timestamptz NOT NULL DEFAULT now(),+ updated_at timestamptz NOT NULL DEFAULT now(),+ UNIQUE (user_id, organization_id, year_month)+);++CREATE INDEX IF NOT EXISTS idx_agent_token_usage_user_month+ ON public.agent_token_usage (user_id, year_month);+++-- ── RLS ────────────────────────────────────────────────────────────────+ALTER TABLE public.agent_conversations ENABLE ROW LEVEL SECURITY;+ALTER TABLE public.agent_messages ENABLE ROW LEVEL SECURITY;+ALTER TABLE public.agent_token_usage ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Users read own conversations" ON public.agent_conversations+ FOR SELECT USING (user_id = auth.uid());+CREATE POLICY "Users write own conversations" ON public.agent_conversations+ FOR ALL USING (user_id = auth.uid()) WITH CHECK (user_id = auth.uid());++CREATE POLICY "Users read own messages" ON public.agent_messages+ FOR SELECT USING (conversation_id IN (+ SELECT id FROM public.agent_conversations WHERE user_id = auth.uid()+ ));+CREATE POLICY "Users write own messages" ON public.agent_messages+ FOR ALL USING (conversation_id IN (+ SELECT id FROM public.agent_conversations WHERE user_id = auth.uid()+ )) WITH CHECK (conversation_id IN (+ SELECT id FROM public.agent_conversations WHERE user_id = auth.uid()+ ));++-- Read-only via RLS so the dashboard can display the user's own usage.+-- The chat API writes via supabaseAdmin (service_role bypasses RLS).+CREATE POLICY "Users read own usage" ON public.agent_token_usage+ FOR SELECT USING (user_id = auth.uid());+++-- ── updated_at trigger ──────────────────────────────────────────────────+-- Conversations: touch updated_at when title or brand_id changes (sidebar+-- sort key) and when a new message is inserted (handled at the API layer).+CREATE OR REPLACE FUNCTION public.touch_agent_conversation_updated_at()+RETURNS trigger LANGUAGE plpgsql AS $$+BEGIN+ NEW.updated_at = now();+ RETURN NEW;+END;+$$;++CREATE TRIGGER trg_agent_conversations_touch_updated_at+ BEFORE UPDATE ON public.agent_conversations+ FOR EACH ROW EXECUTE FUNCTION public.touch_agent_conversation_updated_at();++CREATE OR REPLACE FUNCTION public.touch_agent_token_usage_updated_at()+RETURNS trigger LANGUAGE plpgsql AS $$+BEGIN+ NEW.updated_at = now();+ RETURN NEW;+END;+$$;++CREATE TRIGGER trg_agent_token_usage_touch_updated_at+ BEFORE UPDATE ON public.agent_token_usage+ FOR EACH ROW EXECUTE FUNCTION public.touch_agent_token_usage_updated_at();diff --git a/web/src/config/plans.ts b/web/src/config/plans.tsindex 1d18c0bee..d418a5e7e 100644--- a/web/src/config/plans.ts+++ b/web/src/config/plans.ts@@ -10,6 +10,11 @@ export const FEATURES = ['api_access','white_label','sso_saml',+ // In-product AI agent — chat panel that calls the MCP read tools to+ // answer questions about the brand's AI search performance. Gated on+ // cloud by plan; self-host gets it unconditionally because the+ // underlying tool calls run against the user's own infrastructure.+ 'ai_agent',] as const;export type Feature = (typeof FEATURES)[number];@@ -30,6 +35,12 @@ export interface PlanLimits {allowedScrapers?: readonly string[];/** If set, only these model IDs are available. Undefined = all, [] = none. */allowedModels?: readonly string[];+ /**+ * Cap on combined prompt + completion tokens for the in-product AI agent+ * per user, per calendar month. `undefined` = unlimited (self-host,+ * enterprise). Has no effect when `ai_agent` is not in `features`.+ */+ aiAgentTokenQuota?: number;}export interface PlanPricing {@@ -70,7 +81,10 @@ export const PLANS: Record<PlanId, Plan> = {'content_optimization','custom_reports','api_access',+ 'ai_agent',],+ // Self-host runs against the operator's own infrastructure / API+ // keys — no platform quota to enforce.},},starter: {@@ -127,7 +141,13 @@ export const PLANS: Record<PlanId, Plan> = {'content_optimization','custom_reports','api_access',+ 'ai_agent',],+ // ~50k combined prompt + completion tokens per user per month.+ // Claude Sonnet 4.6 averages ~750 tokens/turn for typical+ // dashboard questions including tool I/O, so this is ~65 turns+ // per user before they hit the quota wall.+ aiAgentTokenQuota: 50000,},},enterprise: {@@ -156,7 +176,9 @@ export const PLANS: Record<PlanId, Plan> = {'api_access','white_label','sso_saml',+ 'ai_agent',],+ // Enterprise — no platform quota; usage governed by contract.},},} as const;@@ -184,7 +206,10 @@ export function hasFeature(plan: Plan, feature: Feature): boolean {export function isWithinLimit(plan: Plan,- key: keyof Omit<PlanLimits, 'features' | 'allowedScrapers' | 'allowedModels'>,+ key: keyof Omit<+ PlanLimits,+ 'features' | 'allowedScrapers' | 'allowedModels' | 'aiAgentTokenQuota'+ >,currentCount: number,): boolean {const limit = plan.limits[key];diff --git a/web/src/hooks/use-feature-gate.ts b/web/src/hooks/use-feature-gate.tsindex bb4451ab5..924c0a2ac 100644--- a/web/src/hooks/use-feature-gate.ts+++ b/web/src/hooks/use-feature-gate.ts@@ -24,14 +24,20 @@ export function useFeatureGate() {},withinLimit(- key: keyof Omit<PlanLimits, 'features' | 'allowedScrapers' | 'allowedModels'>,+ key: keyof Omit<+ PlanLimits,+ 'features' | 'allowedScrapers' | 'allowedModels' | 'aiAgentTokenQuota'+ >,currentCount: number,): boolean {return isWithinLimit(plan, key, currentCount);},getLimit(- key: keyof Omit<PlanLimits, 'features' | 'allowedScrapers' | 'allowedModels'>,+ key: keyof Omit<+ PlanLimits,+ 'features' | 'allowedScrapers' | 'allowedModels' | 'aiAgentTokenQuota'+ >,): number {return plan.limits[key];},diff --git a/web/src/lib/guards/plan-guard.ts b/web/src/lib/guards/plan-guard.tsindex 34cf66a24..724197b1d 100644--- a/web/src/lib/guards/plan-guard.ts+++ b/web/src/lib/guards/plan-guard.ts@@ -56,7 +56,10 @@ export async function enforceFeature(organizationId: string, feature: Feature):export async function enforceLimit(organizationId: string,- key: keyof Omit<PlanLimits, 'features' | 'allowedScrapers' | 'allowedModels'>,+ key: keyof Omit<+ PlanLimits,+ 'features' | 'allowedScrapers' | 'allowedModels' | 'aiAgentTokenQuota'+ >,currentCount: number,): Promise<void> {const plan = await getOrgPlan(organizationId);diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex a57aabc74..dc68da4f4 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -14,6 +14,111 @@ export type Database = {};public: {Tables: {+ agent_conversations: {+ Row: {+ id: string;+ user_id: string;+ organization_id: string;+ brand_id: string | null;+ title: string;+ created_at: string;+ updated_at: string;+ };+ Insert: {+ id?: string;+ user_id: string;+ organization_id: string;+ brand_id?: string | null;+ title?: string;+ created_at?: string;+ updated_at?: string;+ };+ Update: {+ id?: string;+ user_id?: string;+ organization_id?: string;+ brand_id?: string | null;+ title?: string;+ created_at?: string;+ updated_at?: string;+ };+ Relationships: [];+ };+ agent_messages: {+ Row: {+ id: string;+ conversation_id: string;+ role: 'user' | 'assistant' | 'tool';+ content: string;+ tool_calls: Json | null;+ tool_call_id: string | null;+ tool_name: string | null;+ tool_result: Json | null;+ prompt_tokens: number | null;+ completion_tokens: number | null;+ created_at: string;+ };+ Insert: {+ id?: string;+ conversation_id: string;+ role: 'user' | 'assistant' | 'tool';+ content?: string;+ tool_calls?: Json | null;+ tool_call_id?: string | null;+ tool_name?: string | null;+ tool_result?: Json | null;+ prompt_tokens?: number | null;+ completion_tokens?: number | null;+ created_at?: string;+ };+ Update: {+ id?: string;+ conversation_id?: string;+ role?: 'user' | 'assistant' | 'tool';+ content?: string;+ tool_calls?: Json | null;+ tool_call_id?: string | null;+ tool_name?: string | null;+ tool_result?: Json | null;+ prompt_tokens?: number | null;+ completion_tokens?: number | null;+ created_at?: string;+ };+ Relationships: [];+ };+ agent_token_usage: {+ Row: {+ id: string;+ user_id: string;+ organization_id: string;+ year_month: string;+ prompt_tokens: number;+ completion_tokens: number;+ created_at: string;+ updated_at: string;+ };+ Insert: {+ id?: string;+ user_id: string;+ organization_id: string;+ year_month: string;+ prompt_tokens?: number;+ completion_tokens?: number;+ created_at?: string;+ updated_at?: string;+ };+ Update: {+ id?: string;+ user_id?: string;+ organization_id?: string;+ year_month?: string;+ prompt_tokens?: number;+ completion_tokens?: number;+ created_at?: string;+ updated_at?: string;+ };+ Relationships: [];+ };api_keys: {Row: {id: string;