Skip to content

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.

feat(agent): end-to-end in-product AI agent chat (#121)

Gökhan Geyik558197d1b2b9
diff --git a/supabase/migrations/00010_org_anthropic_keys.sql b/supabase/migrations/00010_org_anthropic_keys.sql
new file mode 100644
index 000000000..56f61d5df
--- /dev/null
+++ b/supabase/migrations/00010_org_anthropic_keys.sql
@@ -0,0 +1,31 @@
+-- Bring-your-own-key for the in-product AI agent on cloud.
+--
+-- Cloud customers paste their own Anthropic API key in Settings → Agent;
+-- the agent's chat endpoint reads it back at request time, decrypts it,
+-- and uses it to drive `streamText`. Without a key the feature stays
+-- locked regardless of plan.
+--
+-- The key itself lives in `anthropic_api_key_encrypted` as the JSON
+-- envelope returned by the app-level AES-256-GCM helper
+-- (web/src/lib/agent/key-encryption.ts). The app's master key
+-- (ANSVISOR_ENCRYPTION_KEY) is the only thing that can decrypt it —
+-- Postgres + Supabase admins see ciphertext only.
+--
+-- `last4` is mirrored in plaintext so the Settings UI can show
+-- "sk-…abcd" without round-tripping decrypt. `set_at` / `set_by` give us
+-- an audit trail for support cases ("when did the key change?").
+
+alter table public.organizations
+ add column if not exists anthropic_api_key_encrypted text,
+ add column if not exists anthropic_api_key_last4 text,
+ add column if not exists anthropic_api_key_set_at timestamptz,
+ add column if not exists anthropic_api_key_set_by uuid references public.profiles(id) on delete set null;
+
+comment on column public.organizations.anthropic_api_key_encrypted is
+ 'AES-256-GCM ciphertext (JSON envelope) of the org-level Anthropic API key. Null = no key configured.';
+comment on column public.organizations.anthropic_api_key_last4 is
+ 'Last 4 chars of the plaintext key. Display-only; safe to expose to org members.';
+comment on column public.organizations.anthropic_api_key_set_at is
+ 'When the current key was last saved.';
+comment on column public.organizations.anthropic_api_key_set_by is
+ 'Profile of the org member who saved the current key. Set null on profile delete to preserve audit trail.';
diff --git a/web/.env.example b/web/.env.example
index b2437cc71..35de04e3e 100644
--- a/web/.env.example
+++ b/web/.env.example
@@ -16,6 +16,16 @@ NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
OPENAI_API_KEY=sk-...
GOOGLE_GEMINI_API_KEY=AIza...
ANTHROPIC_API_KEY=sk-ant-...
+
+# -----------------------------------------------------------------------------
+# Agent (in-product BYOK)
+# -----------------------------------------------------------------------------
+# Cloud customers paste their own Anthropic key in Settings → Agent. We
+# encrypt it at rest with AES-256-GCM; this is the master key. Must be a
+# 32-byte (256-bit) value, base64-encoded.
+# Generate one: `openssl rand -base64 32`
+# Self-host instances can skip this — they use ANTHROPIC_API_KEY directly.
+ANSVISOR_ENCRYPTION_KEY=base64-32-bytes-here
PERPLEXITY_API_KEY=pplx-...
GROK_API_KEY=xai-...
diff --git a/web/messages/en.json b/web/messages/en.json
index 907903fe9..14592a82a 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -17,6 +17,7 @@
},
"nav": {
"overview": "Overview",
+ "agent": "Agent",
"insights": "Answer Engine Insights",
"traffic": "AI Traffic Analytics",
"prompts": "Prompts",
diff --git a/web/package.json b/web/package.json
index 28b5c26ec..1fd49fb75 100644
--- a/web/package.json
+++ b/web/package.json
@@ -19,6 +19,8 @@
"format:check": "prettier --check \"src/**/*.{ts,tsx}\""
},
"dependencies": {
+ "@ai-sdk/anthropic": "^3.0.58",
+ "@ai-sdk/react": "^3.0.81",
"@base-ui/react": "^1.2.0",
"@modelcontextprotocol/sdk": "^1.29.0",
"@radix-ui/react-checkbox": "^1.3.3",
@@ -26,6 +28,7 @@
"@supabase/ssr": "^0.9.0",
"@supabase/supabase-js": "^2.99.0",
"@vercel/analytics": "^2.0.1",
+ "ai": "^6.0.116",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"framer-motion": "^12.35.2",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/agent/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/agent/page.tsx
new file mode 100644
index 000000000..5ead12ac8
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/agent/page.tsx
@@ -0,0 +1,626 @@
+'use client';
+
+import { useEffect, useRef, useState } from 'react';
+import { useChat } from '@ai-sdk/react';
+import { DefaultChatTransport, type UIMessage } from 'ai';
+import { useFeatureGate } from '@/hooks/use-feature-gate';
+import { Link } from '@/i18n/navigation';
+import { Button, buttonVariants } from '@/components/ui/button';
+import { Markdown } from '@/components/ui/markdown';
+import { cn } from '@/lib/utils';
+import {
+ Plus,
+ Send,
+ Sparkles,
+ Trash2,
+ Loader2,
+ Crown,
+ Wrench,
+ ChevronDown,
+ KeyRound,
+} from 'lucide-react';
+
+interface ConversationRow {
+ id: string;
+ title: string;
+ brand_id: string | null;
+ created_at: string;
+ updated_at: string;
+}
+
+interface AgentMessageRow {
+ id: string;
+ role: 'user' | 'assistant' | 'tool';
+ content: string;
+ tool_calls: UIMessage['parts'] | null;
+ created_at: string;
+}
+
+export default function AgentPage() {
+ const { canUse, requiredPlanFor, isCloud } = useFeatureGate();
+ const allowed = canUse('ai_agent');
+
+ const [conversations, setConversations] = useState<ConversationRow[]>([]);
+ const [activeId, setActiveId] = useState<string | null>(null);
+ const [initialMessages, setInitialMessages] = useState<UIMessage[]>([]);
+ const [hydrating, setHydrating] = useState(true);
+ const [input, setInput] = useState('');
+ const messagesEndRef = useRef<HTMLDivElement | null>(null);
+
+ // Plan gate — `ai_agent` is in every cloud plan post-BYOK, so this only
+ // bites if the org's plan was somehow stripped of the feature. Kept as
+ // a defensive check.
+ if (!allowed) {
+ return <PlanGate requiredPlan={requiredPlanFor('ai_agent')} />;
+ }
+
+ // BYOK gate — on cloud the real gate is "has the org saved an Anthropic
+ // key?". We probe the same endpoint Settings → Agent uses; if it's not
+ // configured, send the user to Settings instead of letting them type a
+ // message that would 403 on submit. Self-host bypasses (key is in env).
+ if (isCloud) {
+ return (
+ <KeyGatedAgentChat
+ conversations={conversations}
+ setConversations={setConversations}
+ activeId={activeId}
+ setActiveId={setActiveId}
+ initialMessages={initialMessages}
+ setInitialMessages={setInitialMessages}
+ hydrating={hydrating}
+ setHydrating={setHydrating}
+ input={input}
+ setInput={setInput}
+ messagesEndRef={messagesEndRef}
+ />
+ );
+ }
+
+ return (
+ <AgentChat
+ conversations={conversations}
+ setConversations={setConversations}
+ activeId={activeId}
+ setActiveId={setActiveId}
+ initialMessages={initialMessages}
+ setInitialMessages={setInitialMessages}
+ hydrating={hydrating}
+ setHydrating={setHydrating}
+ input={input}
+ setInput={setInput}
+ messagesEndRef={messagesEndRef}
+ />
+ );
+}
+
+function AgentChat(props: {
+ conversations: ConversationRow[];
+ setConversations: React.Dispatch<React.SetStateAction<ConversationRow[]>>;
+ activeId: string | null;
+ setActiveId: React.Dispatch<React.SetStateAction<string | null>>;
+ initialMessages: UIMessage[];
+ setInitialMessages: React.Dispatch<React.SetStateAction<UIMessage[]>>;
+ hydrating: boolean;
+ setHydrating: React.Dispatch<React.SetStateAction<boolean>>;
+ input: string;
+ setInput: React.Dispatch<React.SetStateAction<string>>;
+ messagesEndRef: React.MutableRefObject<HTMLDivElement | null>;
+}) {
+ const {
+ conversations,
+ setConversations,
+ activeId,
+ setActiveId,
+ initialMessages,
+ setInitialMessages,
+ hydrating,
+ setHydrating,
+ input,
+ setInput,
+ messagesEndRef,
+ } = props;
+
+ // Ref mirrors activeId for prepareSendMessagesRequest. Reading the
+ // state directly from the transport closure gives us a stale snapshot —
+ // setActiveId is async, so a "+ new chat then immediately send" flow
+ // would post conversationId: null and the server replies 400. The ref
+ // updates synchronously when we change the active conversation.
+ const activeIdRef = useRef<string | null>(activeId);
+ useEffect(() => {
+ activeIdRef.current = activeId;
+ }, [activeId]);
+
+ const { messages, sendMessage, status, setMessages, stop } = useChat({
+ transport: new DefaultChatTransport({
+ api: '/api/agent/chat',
+ // Always forward the active conversation id alongside the messages
+ // array — the server saves messages keyed off it. Caller can also
+ // pass body via sendMessage(message, { body }) to override the id
+ // synchronously (first-message-of-new-chat path uses this).
+ prepareSendMessagesRequest: ({ messages, body }) => ({
+ body: {
+ conversationId: activeIdRef.current,
+ ...(body ?? {}),
+ messages,
+ },
+ }),
+ }),
+ });
+
+ // Sync hydrated messages into the chat hook whenever we switch conversation.
+ useEffect(() => {
+ setMessages(initialMessages);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [initialMessages]);
+
+ // Auto-scroll on new messages / streaming chunks.
+ useEffect(() => {
+ messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
+ }, [messages, messagesEndRef]);
+
+ // Initial load of the conversation list + the most-recent conversation.
+ useEffect(() => {
+ let cancelled = false;
+ (async () => {
+ try {
+ const res = await fetch('/api/agent/conversations');
+ if (!res.ok) {
+ setHydrating(false);
+ return;
+ }
+ const { conversations: list } = (await res.json()) as {
+ conversations: ConversationRow[];
+ };
+ if (cancelled) return;
+ setConversations(list);
+ if (list.length > 0) {
+ await loadConversation(list[0]!.id);
+ } else {
+ setHydrating(false);
+ }
+ } catch {
+ setHydrating(false);
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ async function loadConversation(id: string) {
+ setHydrating(true);
+ setActiveId(id);
+ try {
+ const res = await fetch(`/api/agent/conversations/${id}`);
+ if (!res.ok) {
+ setInitialMessages([]);
+ return;
+ }
+ const { messages: rows } = (await res.json()) as {
+ messages: AgentMessageRow[];
+ };
+ // Rehydrate UIMessages. We saved `tool_calls` as the full parts
+ // array, so prefer it; fall back to a single text part from the
+ // `content` column.
+ const hydrated: UIMessage[] = rows.map((r) => ({
+ id: r.id,
+ role: r.role === 'tool' ? 'assistant' : r.role,
+ parts:
+ Array.isArray(r.tool_calls) && r.tool_calls.length > 0
+ ? (r.tool_calls as UIMessage['parts'])
+ : [{ type: 'text', text: r.content }],
+ })) as UIMessage[];
+ setInitialMessages(hydrated);
+ } finally {
+ setHydrating(false);
+ }
+ }
+
+ async function newChat() {
+ const res = await fetch('/api/agent/conversations', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({}),
+ });
+ if (!res.ok) return;
+ const { conversation } = (await res.json()) as { conversation: ConversationRow };
+ setConversations((prev) => [conversation, ...prev]);
+ setActiveId(conversation.id);
+ setInitialMessages([]);
+ setInput('');
+ }
+
+ async function deleteConversation(id: string) {
+ if (!confirm('Delete this conversation?')) return;
+ const res = await fetch(`/api/agent/conversations/${id}`, { method: 'DELETE' });
+ if (!res.ok) return;
+ setConversations((prev) => prev.filter((c) => c.id !== id));
+ if (activeId === id) {
+ setActiveId(null);
+ setInitialMessages([]);
+ setMessages([]);
+ }
+ }
+
+ async function onSubmit(e: React.FormEvent) {
+ e.preventDefault();
+ const text = input.trim();
+ if (!text || status !== 'ready') return;
+
+ // Resolve the conversation id we'll send with this message. If no chat
+ // is selected, spin one up. Captured into a local so the sendMessage
+ // call below uses today's value (the ref + state update happen, but
+ // sendMessage's body argument is what the server actually reads).
+ let convId = activeId;
+ if (!convId) {
+ const res = await fetch('/api/agent/conversations', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({}),
+ });
+ if (!res.ok) return;
+ const { conversation } = (await res.json()) as { conversation: ConversationRow };
+ setConversations((prev) => [conversation, ...prev]);
+ setActiveId(conversation.id);
+ activeIdRef.current = conversation.id;
+ convId = conversation.id;
+ }
+ sendMessage({ text }, { body: { conversationId: convId } });
+ setInput('');
+ }
+
+ return (
+ <div className="flex h-[calc(100vh-4rem)] md:h-screen -m-6">
+ <aside className="w-72 border-r bg-card flex flex-col">
+ <div className="p-3 border-b">
+ <Button onClick={newChat} variant="outline" className="w-full justify-start gap-2">
+ <Plus className="h-4 w-4" />
+ New chat
+ </Button>
+ </div>
+ <div className="flex-1 overflow-y-auto p-2 space-y-1">
+ {conversations.length === 0 && (
+ <p className="text-xs text-muted-foreground text-center py-8">No conversations yet.</p>
+ )}
+ {conversations.map((c) => (
+ // Outer wrapper is a div with role="button" rather than a real
+ // <button> because we render the delete control as a nested
+ // <button> inside it — HTML doesn't allow button-in-button
+ // (hydration error in Next.js). Keyboard support via tabIndex +
+ // onKeyDown preserves the same affordance.
+ <div
+ key={c.id}
+ role="button"
+ tabIndex={0}
+ onClick={() => loadConversation(c.id)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ loadConversation(c.id);
+ }
+ }}
+ className={cn(
+ 'w-full text-left text-sm rounded-md px-3 py-2 flex items-start gap-2 group hover:bg-accent transition-colors cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-ring',
+ activeId === c.id && 'bg-accent',
+ )}
+ >
+ <span className="flex-1 truncate">{c.title}</span>
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ void deleteConversation(c.id);
+ }}
+ className="opacity-0 group-hover:opacity-100 text-muted-foreground hover:text-destructive transition-opacity"
+ aria-label="Delete conversation"
+ >
+ <Trash2 className="h-3.5 w-3.5" />
+ </button>
+ </div>
+ ))}
+ </div>
+ </aside>
+
+ <main className="flex-1 flex flex-col overflow-hidden">
+ <div className="flex-1 overflow-y-auto px-6 py-6">
+ {hydrating ? (
+ <div className="flex items-center justify-center h-full text-muted-foreground gap-2 text-sm">
+ <Loader2 className="h-4 w-4 animate-spin" /> Loading conversation…
+ </div>
+ ) : messages.length === 0 ? (
+ <EmptyState />
+ ) : (
+ <div className="max-w-3xl mx-auto space-y-6">
+ {messages.map((m) => (
+ <MessageBubble key={m.id} message={m} />
+ ))}
+ {(status === 'submitted' || status === 'streaming') && (
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ Thinking…
+ </div>
+ )}
+ <div ref={messagesEndRef} />
+ </div>
+ )}
+ </div>
+
+ <form onSubmit={onSubmit} className="border-t bg-background px-6 py-4">
+ <div className="max-w-3xl mx-auto flex gap-2 items-end">
+ <textarea
+ value={input}
+ onChange={(e) => setInput(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' && !e.shiftKey) {
+ e.preventDefault();
+ void onSubmit(e as unknown as React.FormEvent);
+ }
+ }}
+ placeholder="Ask about visibility, competitors, citations…"
+ rows={1}
+ disabled={status !== 'ready'}
+ className="flex-1 resize-none rounded-md border bg-background px-3 py-2 text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent disabled:opacity-50"
+ />
+ {status === 'streaming' || status === 'submitted' ? (
+ <Button type="button" variant="outline" onClick={() => stop()}>
+ Stop
+ </Button>
+ ) : (
+ <Button type="submit" disabled={!input.trim()}>
+ <Send className="h-4 w-4" />
+ </Button>
+ )}
+ </div>
+ </form>
+ </main>
+ </div>
+ );
+}
+
+function MessageBubble({ message }: { message: UIMessage }) {
+ const isUser = message.role === 'user';
+ return (
+ <div className={cn('flex gap-3', isUser ? 'justify-end' : 'justify-start')}>
+ {!isUser && (
+ <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary/10 text-primary">
+ <Sparkles className="h-4 w-4" />
+ </div>
+ )}
+ <div
+ className={cn(
+ 'max-w-[80%] rounded-2xl px-4 py-3 text-sm',
+ isUser ? 'bg-primary text-primary-foreground' : 'bg-card border',
+ )}
+ >
+ {(message.parts ?? []).map((part, i) => {
+ if (part.type === 'text') {
+ // User messages stay plain — they're typed text, not authored
+ // markdown, and the chat bubble background contrasts more
+ // cleanly without prose styling. Assistant output is intended
+ // to be markdown (lists, **bold**, headings, links), so render
+ // it through the same component the rest of the dashboard uses.
+ if (isUser) {
+ return (
+ <p key={i} className="whitespace-pre-wrap leading-relaxed">
+ {part.text}
+ </p>
+ );
+ }
+ return (
+ <Markdown
+ key={i}
+ className="prose prose-sm dark:prose-invert max-w-none [&>*:first-child]:mt-0 [&>*:last-child]:mb-0"
+ >
+ {part.text}
+ </Markdown>
+ );
+ }
+ if (part.type.startsWith('tool-')) {
+ return <ToolCallDisclosure key={i} part={part} />;
+ }
+ return null;
+ })}
+ </div>
+ </div>
+ );
+}
+
+/**
+ * Disclosure-style renderer for a `tool-<name>` UIMessage part.
+ *
+ * AI SDK v6 tool parts carry an internal `state` machine
+ * (`input-streaming` → `input-available` → `output-available` | `output-error`).
+ * Surfacing the raw state string ("output-available") to end users is noise —
+ * what they actually want is "what did the agent ask and what came back?".
+ *
+ * So the collapsed view is a clean chip: tool name + chevron, with a spinner
+ * while the call is still resolving. Clicking expands an inline console-style
+ * panel that shows the input args and output payload as pretty-printed JSON,
+ * the same affordance most agent UIs (Claude, ChatGPT, Cursor) ship.
+ */
+function ToolCallDisclosure({ part }: { part: UIMessage['parts'][number] }) {
+ const [open, setOpen] = useState(false);
+ // Tool parts in AI SDK v6 carry these fields at the part level; we narrow
+ // here rather than importing the union type because each tool gets a
+ // distinct generated discriminant.
+ const toolPart = part as unknown as {
+ type: string;
+ toolName?: string;
+ state?: 'input-streaming' | 'input-available' | 'output-available' | 'output-error';
+ input?: unknown;
+ output?: unknown;
+ errorText?: string;
+ };
+ const name = toolPart.toolName ?? part.type.replace('tool-', '');
+ const isRunning = toolPart.state === 'input-streaming' || toolPart.state === 'input-available';
+ const hasError = toolPart.state === 'output-error';
+ const hasInput = toolPart.input !== undefined && toolPart.input !== null;
+ const hasOutput = toolPart.output !== undefined && toolPart.output !== null;
+ const hasDetails = hasInput || hasOutput || !!toolPart.errorText;
+
+ return (
+ <div className="my-2">
+ <button
+ type="button"
+ onClick={() => hasDetails && setOpen((o) => !o)}
+ disabled={!hasDetails}
+ className={cn(
+ 'inline-flex items-center gap-1.5 text-xs rounded-md px-2 py-1 transition-colors',
+ hasError
+ ? 'bg-destructive/10 text-destructive hover:bg-destructive/15'
+ : 'bg-muted text-muted-foreground hover:bg-muted/70',
+ !hasDetails && 'cursor-default opacity-80',
+ )}
+ aria-expanded={open}
+ >
+ {isRunning ? <Loader2 className="h-3 w-3 animate-spin" /> : <Wrench className="h-3 w-3" />}
+ <span className="font-mono">{name}</span>
+ {hasDetails && (
+ <ChevronDown className={cn('h-3 w-3 transition-transform', open && 'rotate-180')} />
+ )}
+ </button>
+ {open && hasDetails && (
+ <div className="mt-2 rounded-md border bg-muted/40 p-3 text-xs space-y-3 max-w-full">
+ {hasInput && (
+ <div>
+ <p className="text-muted-foreground font-medium mb-1 uppercase tracking-wider text-[10px]">
+ Input
+ </p>
+ <pre className="font-mono text-[11px] whitespace-pre-wrap break-words leading-relaxed text-foreground/90">
+ {safeStringify(toolPart.input)}
+ </pre>
+ </div>
+ )}
+ {hasOutput && (
+ <div>
+ <p className="text-muted-foreground font-medium mb-1 uppercase tracking-wider text-[10px]">
+ Output
+ </p>
+ <pre className="font-mono text-[11px] whitespace-pre-wrap break-words leading-relaxed text-foreground/90 max-h-80 overflow-y-auto">
+ {safeStringify(toolPart.output)}
+ </pre>
+ </div>
+ )}
+ {toolPart.errorText && (
+ <div>
+ <p className="text-destructive font-medium mb-1 uppercase tracking-wider text-[10px]">
+ Error
+ </p>
+ <pre className="font-mono text-[11px] whitespace-pre-wrap break-words leading-relaxed text-destructive">
+ {toolPart.errorText}
+ </pre>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function safeStringify(value: unknown): string {
+ try {
+ return JSON.stringify(value, null, 2);
+ } catch {
+ return String(value);
+ }
+}
+
+function EmptyState() {
+ return (
+ <div className="flex h-full items-center justify-center">
+ <div className="text-center max-w-md">
+ <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-primary/10 text-primary mb-4">
+ <Sparkles className="h-6 w-6" />
+ </div>
+ <h2 className="text-lg font-semibold">Ask the agent</h2>
+ <p className="text-sm text-muted-foreground mt-2">
+ Grounded in your tracked data. Try <em>&ldquo;how is my brand doing?&rdquo;</em> or{' '}
+ <em>&ldquo;who&apos;s gaining share of voice this month?&rdquo;</em>
+ </p>
+ </div>
+ </div>
+ );
+}
+
+/**
+ * Cloud wrapper: probes /api/settings/anthropic-key once on mount and
+ * either renders the chat (key configured) or a Settings CTA (no key).
+ * Self-host renders AgentChat directly — its key check is environmental.
+ */
+function KeyGatedAgentChat(props: React.ComponentProps<typeof AgentChat>) {
+ const [status, setStatus] = useState<'loading' | 'configured' | 'missing'>('loading');
+
+ useEffect(() => {
+ let cancelled = false;
+ (async () => {
+ try {
+ const res = await fetch('/api/settings/anthropic-key');
+ if (!res.ok) {
+ if (!cancelled) setStatus('missing');
+ return;
+ }
+ const body = (await res.json()) as { configured?: boolean };
+ if (!cancelled) setStatus(body.configured ? 'configured' : 'missing');
+ } catch {
+ if (!cancelled) setStatus('missing');
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ if (status === 'loading') {
+ return (
+ <div className="flex h-[calc(100vh-4rem)] md:h-screen items-center justify-center -m-6 p-6">
+ <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
+ </div>
+ );
+ }
+ if (status === 'missing') {
+ return <KeyMissingState />;
+ }
+ return <AgentChat {...props} />;
+}
+
+function KeyMissingState() {
+ return (
+ <div className="flex h-[calc(100vh-4rem)] md:h-screen items-center justify-center -m-6 p-6">
+ <div className="text-center max-w-md">
+ <div className="mx-auto flex h-14 w-14 items-center justify-center rounded-full bg-primary/10 text-primary mb-4">
+ <KeyRound className="h-7 w-7" />
+ </div>
+ <h2 className="text-lg font-semibold">Add your Anthropic API key</h2>
+ <p className="text-sm text-muted-foreground mt-2">
+ The agent uses your own Anthropic key to call Claude directly — usage is billed to your
+ Anthropic account, not to Ansvisor. Paste a key in Settings to unlock the chat.
+ </p>
+ <Link
+ href="/dashboard/settings?tab=agent"
+ className={cn(buttonVariants({ variant: 'default' }), 'mt-5 gap-2')}
+ >
+ <KeyRound className="h-4 w-4" />
+ Go to Settings
+ </Link>
+ </div>
+ </div>
+ );
+}
+
+function PlanGate({ requiredPlan }: { requiredPlan: string }) {
+ return (
+ <div className="flex h-[calc(100vh-4rem)] md:h-screen items-center justify-center -m-6 p-6">
+ <div className="text-center max-w-md">
+ <div className="mx-auto flex h-14 w-14 items-center justify-center rounded-full bg-amber-100 dark:bg-amber-900/30 mb-4">
+ <Crown className="h-7 w-7 text-amber-600 dark:text-amber-400" />
+ </div>
+ <h2 className="text-lg font-semibold">Agent is a {requiredPlan} feature</h2>
+ <p className="text-sm text-muted-foreground mt-2">
+ Upgrade your plan to chat with your dashboard about visibility, competitors, citations,
+ and content gaps.
+ </p>
+ </div>
+ </div>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/settings/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/settings/page.tsx
index 9602fd68d..6ecd0e140 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/settings/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/settings/page.tsx
@@ -16,8 +16,9 @@ import { usePlanContext } from '@/components/providers/plan-provider';
import { BillingSection } from '@/components/settings/billing-section';
import { TeamSection } from '@/components/settings/team-section';
import { ApiKeysSection } from '@/components/settings/api-keys-section';
+import { AgentSection } from '@/components/settings/agent-section';
-type Section = 'account' | 'theme' | 'project' | 'team' | 'api-keys' | 'billing';
+type Section = 'account' | 'theme' | 'project' | 'team' | 'api-keys' | 'agent' | 'billing';
export default function SettingsPage() {
const t = useTranslations('settings');
@@ -26,9 +27,11 @@ export default function SettingsPage() {
const { isCloud } = usePlanContext();
const searchParams = useSearchParams();
const tabParam = searchParams.get('tab');
- const [active, setActive] = useState<Section>(
- tabParam === 'billing' && isCloud ? 'billing' : 'account',
- );
+ const [active, setActive] = useState<Section>(() => {
+ if (tabParam === 'billing' && isCloud) return 'billing';
+ if (tabParam === 'agent' && isCloud) return 'agent';
+ return 'account';
+ });
const [displayName, setDisplayName] = useState('');
const [email, setEmail] = useState('');
@@ -53,6 +56,9 @@ export default function SettingsPage() {
{ id: 'project', label: t('project') },
{ id: 'team', label: t('team') },
{ id: 'api-keys', label: 'API Keys' },
+ // Agent BYOK is a cloud-only concern — self-host operators configure
+ // ANTHROPIC_API_KEY in their own env, no UI needed.
+ ...(isCloud ? [{ id: 'agent' as Section, label: 'Agent' }] : []),
...(isCloud ? [{ id: 'billing' as Section, label: t('billing') }] : []),
];
@@ -169,6 +175,9 @@ export default function SettingsPage() {
{/* API Keys */}
{active === 'api-keys' && <ApiKeysSection />}
+ {/* Agent (cloud BYOK) */}
+ {active === 'agent' && isCloud && <AgentSection />}
+
{/* Billing */}
{active === 'billing' && isCloud && <BillingSection />}
</div>
diff --git a/web/src/app/api/agent/chat/route.ts b/web/src/app/api/agent/chat/route.ts
new file mode 100644
index 000000000..4eeebf86d
--- /dev/null
+++ b/web/src/app/api/agent/chat/route.ts
@@ -0,0 +1,184 @@
+import { NextResponse } from 'next/server';
+import { convertToModelMessages, stepCountIs, streamText, type UIMessage } from 'ai';
+import { supabaseAdmin } from '@/lib/supabase/admin';
+import { resolveAgentAuth } from '@/lib/agent/auth';
+import { buildAgentTools } from '@/lib/agent/tools';
+import { AGENT_SYSTEM_PROMPT } from '@/lib/agent/system-prompt';
+import { buildAgentModel } from '@/lib/agent/model';
+import { resolveAnthropicKey } from '@/lib/agent/key';
+import { recordAgentTokenUsage } from '@/lib/agent/token-quota';
+import { getPlan, hasFeature, type PlanId } from '@/config/plans';
+
+// Streaming responses up to 5 min — agent loops can run multiple tool
+// calls plus a final generation, comfortably under this.
+export const maxDuration = 300;
+
+interface ChatBody {
+ conversationId: string;
+ messages: UIMessage[];
+}
+
+/**
+ * POST /api/agent/chat
+ *
+ * Streaming chat endpoint for the in-product agent. Verifies the user is
+ * signed in, the conversation belongs to them, the org's plan unlocks the
+ * `ai_agent` feature, and the user hasn't blown through the monthly token
+ * quota — then runs `streamText` with the MCP-data-backed tool surface and
+ * streams the response back via `toUIMessageStreamResponse()`. Tokens are
+ * billed at the end of the turn via the `onFinish` hook.
+ *
+ * The conversation row + user message must already exist before this is
+ * called — the page creates the row, persists the user message, and only
+ * then calls this endpoint with the full thread.
+ */
+export async function POST(req: Request) {
+ const auth = await resolveAgentAuth();
+ if (!auth || !auth.organizationId) {
+ return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
+ }
+ const organizationId: string = auth.organizationId;
+
+ let body: ChatBody;
+ try {
+ body = (await req.json()) as ChatBody;
+ } catch {
+ return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
+ }
+
+ const { conversationId, messages } = body;
+ if (!conversationId || !Array.isArray(messages) || messages.length === 0) {
+ return NextResponse.json(
+ { error: 'conversationId and a non-empty messages array are required' },
+ { status: 400 },
+ );
+ }
+
+ // Ownership: the conversation must belong to the calling user.
+ const { data: conv } = await supabaseAdmin
+ .from('agent_conversations')
+ .select('id, user_id, organization_id')
+ .eq('id', conversationId)
+ .maybeSingle();
+ if (!conv || conv.user_id !== auth.userId || conv.organization_id !== organizationId) {
+ return NextResponse.json({ error: 'Conversation not found' }, { status: 404 });
+ }
+
+ // Plan gate. On cloud the gate is intentionally loose — `ai_agent` is in
+ // every paid plan's feature list; the *real* gate is whether the org has
+ // pasted an Anthropic key in Settings → Agent (BYOK). Self-host bypasses
+ // both checks because the operator's env supplies everything.
+ const { data: org } = await supabaseAdmin
+ .from('organizations')
+ .select('plan')
+ .eq('id', organizationId)
+ .maybeSingle();
+ const plan = getPlan((org?.plan ?? 'starter') as PlanId);
+ if (!hasFeature(plan, 'ai_agent')) {
+ return NextResponse.json({ error: 'ai_agent is not enabled for this plan' }, { status: 403 });
+ }
+
+ // BYOK gate. Cloud customers paste their Anthropic key in
+ // Settings → Agent and the agent uses *that* key — Ansvisor never pays
+ // for the customer's tokens. Missing key = 403 with a code the UI can
+ // intercept to render the "add your key" CTA instead of a generic error.
+ const anthropicKey = await resolveAnthropicKey(organizationId);
+ if (!anthropicKey) {
+ return NextResponse.json(
+ {
+ error: 'Anthropic API key required',
+ code: 'missing_anthropic_key',
+ },
+ { status: 403 },
+ );
+ }
+
+ const result = streamText({
+ model: buildAgentModel(anthropicKey),
+ system: AGENT_SYSTEM_PROMPT,
+ messages: await convertToModelMessages(messages),
+ tools: buildAgentTools(auth),
+ // streamText is single-step by default in v6 — without an explicit
+ // stop condition the model fires a tool call and ends the turn before
+ // ever seeing the result. stepCountIs(N) re-runs the generation after
+ // each tool call so the agent can interpret what came back and either
+ // answer or call another tool. 20 is the same default ToolLoopAgent
+ // ships with — plenty of headroom for the typical "list_brands →
+ // get_visibility_summary → answer" chain without burning tokens
+ // forever on a pathological loop.
+ stopWhen: stepCountIs(20),
+ onFinish: async ({ usage }) => {
+ // Bill the turn. inputTokens / outputTokens are the counts from the
+ // provider; default to 0 if a step finished without billable usage.
+ const promptTokens = usage?.inputTokens ?? 0;
+ const completionTokens = usage?.outputTokens ?? 0;
+ try {
+ await recordAgentTokenUsage(auth.userId, organizationId, promptTokens, completionTokens);
+ } catch (err) {
+ console.error('[agent/chat] token recording failed:', err);
+ }
+ },
+ });
+
+ return result.toUIMessageStreamResponse({
+ originalMessages: messages,
+ onFinish: async ({ messages: finalMessages }) => {
+ // Replace-in-place: drop the conversation's messages and write the
+ // current full array back. The originalMessages option above lets
+ // toUIMessageStreamResponse merge incoming + new — so finalMessages
+ // contains the entire thread including the new user message and
+ // every assistant / tool step from this turn. Single batched write
+ // per turn; the trigger on agent_conversations bumps updated_at on
+ // the conversation row (sidebar re-sort).
+ try {
+ await supabaseAdmin.from('agent_messages').delete().eq('conversation_id', conversationId);
+
+ if (finalMessages.length > 0) {
+ await supabaseAdmin.from('agent_messages').insert(
+ finalMessages.map((m) => {
+ const textParts = (m.parts ?? []).filter(
+ (p): p is { type: 'text'; text: string } => p.type === 'text',
+ );
+ const text = textParts.map((p) => p.text).join('');
+ return {
+ conversation_id: conversationId,
+ role: m.role as 'user' | 'assistant' | 'tool',
+ content: text,
+ // Persist the full UIMessage parts array so on hydrate we
+ // can replay tool calls / results without re-deriving them.
+ tool_calls: (m.parts ?? []) as unknown as Record<string, unknown>[],
+ };
+ }),
+ );
+ }
+
+ // Auto-title from the first user message if the conversation is
+ // still on its default placeholder. ~40 chars is enough for a
+ // sidebar entry without forcing CSS truncation.
+ const firstUser = finalMessages.find((m) => m.role === 'user');
+ if (firstUser) {
+ const textPart = (firstUser.parts ?? []).find(
+ (p): p is { type: 'text'; text: string } => p.type === 'text',
+ );
+ const firstText = textPart?.text?.trim();
+ if (firstText) {
+ const candidate = firstText.length > 40 ? firstText.slice(0, 40) + '…' : firstText;
+ await supabaseAdmin
+ .from('agent_conversations')
+ .update({ title: candidate })
+ .eq('id', conversationId)
+ .eq('title', 'New conversation');
+ }
+ }
+
+ // Bump updated_at so the sidebar re-sorts this thread to the top.
+ await supabaseAdmin
+ .from('agent_conversations')
+ .update({ updated_at: new Date().toISOString() })
+ .eq('id', conversationId);
+ } catch (err) {
+ console.error('[agent/chat] message persistence failed:', err);
+ }
+ },
+ });
+}
diff --git a/web/src/app/api/agent/conversations/[id]/route.ts b/web/src/app/api/agent/conversations/[id]/route.ts
new file mode 100644
index 000000000..477900c75
--- /dev/null
+++ b/web/src/app/api/agent/conversations/[id]/route.ts
@@ -0,0 +1,74 @@
+import { NextResponse } from 'next/server';
+import { supabaseAdmin } from '@/lib/supabase/admin';
+import { resolveAgentAuth } from '@/lib/agent/auth';
+
+/**
+ * GET /api/agent/conversations/[id]
+ *
+ * Return one conversation plus its ordered messages so the chat panel can
+ * hydrate when the user opens a thread from the sidebar (or refreshes).
+ * Ownership-check before the messages select — wrong-org or someone
+ * else's conversation returns 404 to avoid id-probing.
+ */
+export async function GET(_req: Request, { params }: { params: Promise<{ id: string }> }) {
+ const auth = await resolveAgentAuth();
+ if (!auth) {
+ return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
+ }
+
+ const { id } = await params;
+
+ const { data: conversation } = await supabaseAdmin
+ .from('agent_conversations')
+ .select('id, title, brand_id, created_at, updated_at')
+ .eq('id', id)
+ .eq('user_id', auth.userId)
+ .eq('organization_id', auth.organizationId)
+ .maybeSingle();
+
+ if (!conversation) {
+ return NextResponse.json({ error: 'Conversation not found' }, { status: 404 });
+ }
+
+ const { data: messages } = await supabaseAdmin
+ .from('agent_messages')
+ .select(
+ 'id, role, content, tool_calls, tool_call_id, tool_name, tool_result, prompt_tokens, completion_tokens, created_at',
+ )
+ .eq('conversation_id', id)
+ .order('created_at', { ascending: true });
+
+ return NextResponse.json({ conversation, messages: messages ?? [] });
+}
+
+/**
+ * DELETE /api/agent/conversations/[id]
+ *
+ * Drop a conversation (cascades to its messages). Ownership-check first.
+ */
+export async function DELETE(_req: Request, { params }: { params: Promise<{ id: string }> }) {
+ const auth = await resolveAgentAuth();
+ if (!auth) {
+ return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
+ }
+
+ const { id } = await params;
+
+ // Match on user_id + organization_id so an attacker can't burn someone
+ // else's conversation by guessing an id.
+ const { error, count } = await supabaseAdmin
+ .from('agent_conversations')
+ .delete({ count: 'exact' })
+ .eq('id', id)
+ .eq('user_id', auth.userId)
+ .eq('organization_id', auth.organizationId);
+
+ if (error) {
+ return NextResponse.json({ error: error.message }, { status: 500 });
+ }
+ if (!count) {
+ return NextResponse.json({ error: 'Conversation not found' }, { status: 404 });
+ }
+
+ return NextResponse.json({ ok: true });
+}
diff --git a/web/src/app/api/agent/conversations/route.ts b/web/src/app/api/agent/conversations/route.ts
new file mode 100644
index 000000000..ac8092781
--- /dev/null
+++ b/web/src/app/api/agent/conversations/route.ts
@@ -0,0 +1,98 @@
+import { NextResponse } from 'next/server';
+import { supabaseAdmin } from '@/lib/supabase/admin';
+import { resolveAgentAuth } from '@/lib/agent/auth';
+import { getPlan, hasFeature, type PlanId } from '@/config/plans';
+import { isAnthropicKeyConfigured } from '@/lib/agent/key';
+
+/**
+ * GET /api/agent/conversations
+ *
+ * List the calling user's conversations, newest first. Powers the agent
+ * page's sidebar.
+ */
+export async function GET() {
+ const auth = await resolveAgentAuth();
+ if (!auth) {
+ return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
+ }
+
+ const { data, error } = await supabaseAdmin
+ .from('agent_conversations')
+ .select('id, title, brand_id, created_at, updated_at')
+ .eq('user_id', auth.userId)
+ .eq('organization_id', auth.organizationId)
+ .order('updated_at', { ascending: false })
+ .limit(100);
+
+ if (error) {
+ return NextResponse.json({ error: error.message }, { status: 500 });
+ }
+
+ return NextResponse.json({ conversations: data ?? [] });
+}
+
+/**
+ * POST /api/agent/conversations
+ *
+ * Create a new conversation row. Optional `brand_id` pins the chat to a
+ * brand so the agent's tool calls have an implicit scope. Returns the row.
+ *
+ * Plan-gated: the chat endpoint already gates on `ai_agent`, but we gate
+ * here too so a non-Growth user clicking "+ New chat" gets the 403
+ * immediately rather than after typing a message.
+ */
+export async function POST(req: Request) {
+ const auth = await resolveAgentAuth();
+ if (!auth || !auth.organizationId) {
+ return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
+ }
+ const organizationId: string = auth.organizationId;
+
+ const { data: org } = await supabaseAdmin
+ .from('organizations')
+ .select('plan')
+ .eq('id', organizationId)
+ .maybeSingle();
+ const plan = getPlan((org?.plan ?? 'starter') as PlanId);
+ if (!hasFeature(plan, 'ai_agent')) {
+ return NextResponse.json({ error: 'ai_agent is not enabled for this plan' }, { status: 403 });
+ }
+
+ // BYOK gate — match the chat endpoint so "+ new chat" can't create a row
+ // the user can never send a message to. UI uses the same code to route
+ // to the Settings → Agent CTA.
+ const hasKey = await isAnthropicKeyConfigured(organizationId);
+ if (!hasKey) {
+ return NextResponse.json(
+ { error: 'Anthropic API key required', code: 'missing_anthropic_key' },
+ { status: 403 },
+ );
+ }
+
+ let body: { brandId?: string; title?: string } = {};
+ try {
+ body = (await req.json()) as { brandId?: string; title?: string };
+ } catch {
+ // Empty body is fine — the form may not send one.
+ }
+
+ const { data, error } = await supabaseAdmin
+ .from('agent_conversations')
+ .insert({
+ user_id: auth.userId,
+ organization_id: auth.organizationId,
+ brand_id: body.brandId ?? null,
+ title: body.title ?? 'New conversation',
+ })
+ .select('id, title, brand_id, created_at, updated_at')
+ .single();
+
+ if (error || !data) {
+ return NextResponse.json(
+ { error: error?.message ?? 'Failed to create conversation' },
+ { status: 500 },
+ );
+ }
+
+ return NextResponse.json({ conversation: data }, { status: 201 });
+}
diff --git a/web/src/app/api/settings/anthropic-key/route.ts b/web/src/app/api/settings/anthropic-key/route.ts
new file mode 100644
index 000000000..5a7cd2d34
--- /dev/null
+++ b/web/src/app/api/settings/anthropic-key/route.ts
@@ -0,0 +1,168 @@
+import { NextResponse } from 'next/server';
+import { createClient } from '@/lib/supabase/server';
+import { supabaseAdmin } from '@/lib/supabase/admin';
+import { encryptApiKey, last4 } from '@/lib/agent/key-encryption';
+
+/**
+ * GET / PUT / DELETE /api/settings/anthropic-key
+ *
+ * Manages the org-level Anthropic API key the in-product agent uses on
+ * cloud. We never return the plaintext — GET surfaces only the metadata
+ * the Settings UI needs to render the "configured" state (last4, set_at,
+ * who saved it).
+ *
+ * Auth model:
+ * - GET: any signed-in org member can see whether a key is configured.
+ * The chat endpoint already gates, so leaking "we have a key" is fine.
+ * - PUT / DELETE: admins only. Same role bar as team management — adding
+ * a payment instrument (which is effectively what an Anthropic key is)
+ * shouldn't be a non-admin action.
+ */
+
+async function getCallerAndOrg() {
+ const supabase = await createClient();
+ const {
+ data: { user },
+ } = await supabase.auth.getUser();
+ if (!user) return { error: 'Unauthorized' as const };
+
+ const { data: profile } = await supabase
+ .from('profiles')
+ .select('id, role, organization_id')
+ .eq('id', user.id)
+ .single();
+
+ if (!profile?.organization_id) return { error: 'No organization' as const };
+
+ return {
+ user,
+ profile: profile as { id: string; role: string; organization_id: string },
+ };
+}
+
+export async function GET() {
+ const ctx = await getCallerAndOrg();
+ if ('error' in ctx) {
+ return NextResponse.json(
+ { error: ctx.error },
+ { status: ctx.error === 'Unauthorized' ? 401 : 400 },
+ );
+ }
+
+ const { data, error } = await supabaseAdmin
+ .from('organizations')
+ .select(
+ 'anthropic_api_key_last4, anthropic_api_key_set_at, anthropic_api_key_set_by, anthropic_api_key_encrypted',
+ )
+ .eq('id', ctx.profile.organization_id)
+ .single();
+
+ if (error) {
+ return NextResponse.json({ error: error.message }, { status: 500 });
+ }
+
+ // Fetch the saver's name separately — the FK we declared is to
+ // `profiles(id)`, which the auth user model already mirrors, so a quick
+ // second query is simpler than a join through PostgREST.
+ let setByEmail: string | null = null;
+ if (data?.anthropic_api_key_set_by) {
+ const { data: setter } = await supabaseAdmin.auth.admin.getUserById(
+ data.anthropic_api_key_set_by,
+ );
+ setByEmail = setter?.user?.email ?? null;
+ }
+
+ return NextResponse.json({
+ configured: !!data?.anthropic_api_key_encrypted,
+ last4: data?.anthropic_api_key_last4 ?? null,
+ setAt: data?.anthropic_api_key_set_at ?? null,
+ setByEmail,
+ });
+}
+
+export async function PUT(req: Request) {
+ const ctx = await getCallerAndOrg();
+ if ('error' in ctx) {
+ return NextResponse.json(
+ { error: ctx.error },
+ { status: ctx.error === 'Unauthorized' ? 401 : 400 },
+ );
+ }
+ if (ctx.profile.role !== 'admin') {
+ return NextResponse.json(
+ { error: 'Only admins can manage the Anthropic API key' },
+ { status: 403 },
+ );
+ }
+
+ const body = (await req.json().catch(() => ({}))) as { apiKey?: string };
+ const apiKey = (body.apiKey ?? '').trim();
+ if (!apiKey) {
+ return NextResponse.json({ error: 'apiKey is required' }, { status: 400 });
+ }
+ // Anthropic keys are `sk-ant-…`. We do a soft format check rather than a
+ // hard one — the prefix has changed before and we don't want to lock
+ // users out over a future format bump. A network validation against
+ // /v1/messages would be more rigorous but doubles save latency for
+ // little gain; the first chat turn will surface a bad key as a 401
+ // immediately anyway.
+ if (apiKey.length < 20 || apiKey.length > 200) {
+ return NextResponse.json({ error: 'apiKey looks malformed' }, { status: 400 });
+ }
+
+ let encrypted: string;
+ try {
+ encrypted = encryptApiKey(apiKey);
+ } catch (err) {
+ // Misconfigured server env — surface a clear 500 instead of writing
+ // unrecoverable data.
+ console.error('[anthropic-key] encryption failed:', err);
+ return NextResponse.json({ error: 'Server encryption is not configured' }, { status: 500 });
+ }
+
+ const { error } = await supabaseAdmin
+ .from('organizations')
+ .update({
+ anthropic_api_key_encrypted: encrypted,
+ anthropic_api_key_last4: last4(apiKey),
+ anthropic_api_key_set_at: new Date().toISOString(),
+ anthropic_api_key_set_by: ctx.profile.id,
+ })
+ .eq('id', ctx.profile.organization_id);
+
+ if (error) {
+ return NextResponse.json({ error: error.message }, { status: 500 });
+ }
+ return NextResponse.json({ ok: true });
+}
+
+export async function DELETE() {
+ const ctx = await getCallerAndOrg();
+ if ('error' in ctx) {
+ return NextResponse.json(
+ { error: ctx.error },
+ { status: ctx.error === 'Unauthorized' ? 401 : 400 },
+ );
+ }
+ if (ctx.profile.role !== 'admin') {
+ return NextResponse.json(
+ { error: 'Only admins can manage the Anthropic API key' },
+ { status: 403 },
+ );
+ }
+
+ const { error } = await supabaseAdmin
+ .from('organizations')
+ .update({
+ anthropic_api_key_encrypted: null,
+ anthropic_api_key_last4: null,
+ anthropic_api_key_set_at: null,
+ anthropic_api_key_set_by: null,
+ })
+ .eq('id', ctx.profile.organization_id);
+
+ if (error) {
+ return NextResponse.json({ error: error.message }, { status: 500 });
+ }
+ return NextResponse.json({ ok: true });
+}
diff --git a/web/src/components/layout/sidebar.tsx b/web/src/components/layout/sidebar.tsx
index 433fb4fba..601b9d8ba 100644
--- a/web/src/components/layout/sidebar.tsx
+++ b/web/src/components/layout/sidebar.tsx
@@ -33,6 +33,7 @@ export function Sidebar() {
const navKeyMap: Record<string, () => string> = {
Overview: () => t('overview'),
Brands: () => tBrands('title'),
+ Agent: () => t('agent'),
'Answer Engine Insights': () => t('insights'),
'AI Traffic Analytics': () => t('traffic'),
Prompts: () => t('prompts'),
diff --git a/web/src/components/settings/agent-section.tsx b/web/src/components/settings/agent-section.tsx
new file mode 100644
index 000000000..63860b0bd
--- /dev/null
+++ b/web/src/components/settings/agent-section.tsx
@@ -0,0 +1,209 @@
+'use client';
+
+import { useCallback, useEffect, useState } from 'react';
+import { toast } from 'sonner';
+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import { Badge } from '@/components/ui/badge';
+import { Skeleton } from '@/components/ui/skeleton';
+import { Loader2, Sparkles, Trash2, CheckCircle2 } from 'lucide-react';
+
+interface KeyState {
+ configured: boolean;
+ last4: string | null;
+ setAt: string | null;
+ setByEmail: string | null;
+}
+
+function formatDate(iso: string | null): string {
+ if (!iso) return '—';
+ return new Date(iso).toLocaleDateString(undefined, {
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric',
+ });
+}
+
+/**
+ * Settings → Agent.
+ *
+ * Bring-your-own-key UI for the in-product agent on cloud. Customers paste
+ * an Anthropic API key here and the chat endpoint reads it back per turn
+ * (encrypted at rest, see web/src/lib/agent/key-encryption.ts).
+ *
+ * The plaintext is never returned from the server — `configured` + `last4`
+ * are enough to render the "sk-…abcd" chip without a decrypt round-trip.
+ * On save / clear we just refetch.
+ */
+export function AgentSection() {
+ const [state, setState] = useState<KeyState | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [input, setInput] = useState('');
+ const [saving, setSaving] = useState(false);
+ const [clearing, setClearing] = useState(false);
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ try {
+ const res = await fetch('/api/settings/anthropic-key');
+ const body = (await res.json()) as Partial<KeyState> & { error?: string };
+ if (!res.ok) throw new Error(body.error || 'Failed to load');
+ setState({
+ configured: !!body.configured,
+ last4: body.last4 ?? null,
+ setAt: body.setAt ?? null,
+ setByEmail: body.setByEmail ?? null,
+ });
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : 'Failed to load');
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ void load();
+ }, [load]);
+
+ const handleSave = async () => {
+ const apiKey = input.trim();
+ if (!apiKey) return;
+ setSaving(true);
+ try {
+ const res = await fetch('/api/settings/anthropic-key', {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ apiKey }),
+ });
+ const body = (await res.json().catch(() => ({}))) as { error?: string };
+ if (!res.ok) throw new Error(body.error || 'Failed to save');
+ toast.success('Anthropic API key saved');
+ setInput('');
+ await load();
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : 'Failed to save');
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const handleClear = async () => {
+ if (
+ !confirm(
+ 'Remove the Anthropic API key? Team members will lose access to the agent until a new key is saved.',
+ )
+ ) {
+ return;
+ }
+ setClearing(true);
+ try {
+ const res = await fetch('/api/settings/anthropic-key', { method: 'DELETE' });
+ const body = (await res.json().catch(() => ({}))) as { error?: string };
+ if (!res.ok) throw new Error(body.error || 'Failed to clear');
+ toast.success('Key removed');
+ await load();
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : 'Failed to clear');
+ } finally {
+ setClearing(false);
+ }
+ };
+
+ const configured = state?.configured ?? false;
+ const isReplacing = configured && input.length > 0;
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle className="flex items-center gap-2">
+ <Sparkles className="h-4 w-4" />
+ Agent
+ </CardTitle>
+ <CardDescription>
+ Bring your own Anthropic API key. The in-product agent uses your key to call Claude
+ directly — usage is billed to your Anthropic account, not to Ansvisor.
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ {loading ? (
+ <Skeleton className="h-20 w-full" />
+ ) : configured && state ? (
+ <div className="rounded-md border bg-muted/40 p-3 space-y-2">
+ <div className="flex items-center gap-2">
+ <Badge variant="secondary" className="gap-1">
+ <CheckCircle2 className="h-3 w-3" />
+ Key configured
+ </Badge>
+ {state.last4 && (
+ <code className="text-xs font-mono text-muted-foreground">sk-…{state.last4}</code>
+ )}
+ </div>
+ <p className="text-xs text-muted-foreground">
+ Saved {formatDate(state.setAt)}
+ {state.setByEmail && ` by ${state.setByEmail}`}.
+ </p>
+ </div>
+ ) : (
+ <p className="text-sm text-muted-foreground">
+ No key configured. The agent will be locked for everyone in this organization until a
+ key is saved.
+ </p>
+ )}
+
+ <div className="space-y-2">
+ <Label htmlFor="anthropic-key">{configured ? 'Replace key' : 'Anthropic API key'}</Label>
+ <div className="flex gap-2">
+ <Input
+ id="anthropic-key"
+ type="password"
+ autoComplete="off"
+ spellCheck={false}
+ placeholder="sk-ant-…"
+ value={input}
+ onChange={(e) => setInput(e.target.value)}
+ disabled={saving}
+ className="font-mono"
+ />
+ <Button onClick={handleSave} disabled={saving || !input.trim()}>
+ {saving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
+ {isReplacing ? 'Replace' : 'Save'}
+ </Button>
+ </div>
+ <p className="text-xs text-muted-foreground">
+ Get a key from{' '}
+ <a
+ href="https://console.anthropic.com/settings/keys"
+ target="_blank"
+ rel="noreferrer"
+ className="underline"
+ >
+ console.anthropic.com
+ </a>
+ . The key is encrypted at rest; Ansvisor support cannot read it.
+ </p>
+ </div>
+
+ {configured && (
+ <div className="pt-2 border-t">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={handleClear}
+ disabled={clearing}
+ className="text-destructive hover:text-destructive"
+ >
+ {clearing ? (
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ ) : (
+ <Trash2 className="mr-2 h-4 w-4" />
+ )}
+ Remove key
+ </Button>
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/web/src/config/dashboard.ts b/web/src/config/dashboard.ts
index d904f43c6..87c0759df 100644
--- a/web/src/config/dashboard.ts
+++ b/web/src/config/dashboard.ts
@@ -6,6 +6,7 @@ import {
LineChart,
Quote,
Settings,
+ Sparkles,
Tag,
Users,
} from 'lucide-react';
@@ -33,6 +34,12 @@ export const dashboardNav: NavGroup[] = [
href: '/dashboard/brands',
icon: Building2,
},
+ {
+ title: 'Agent',
+ href: '/dashboard/agent',
+ icon: Sparkles,
+ requiredFeature: 'ai_agent',
+ },
],
},
{
diff --git a/web/src/config/plans.ts b/web/src/config/plans.ts
index d418a5e7e..a1f79bdda 100644
--- a/web/src/config/plans.ts
+++ b/web/src/config/plans.ts
@@ -35,12 +35,6 @@ 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 {
@@ -113,6 +107,11 @@ export const PLANS: Record<PlanId, Plan> = {
'content_optimization',
'custom_reports',
'api_access',
+ // Cloud is BYOK across the board: the customer pastes their own
+ // Anthropic key in Settings → Agent and we just use it. Plan no
+ // longer gates the feature — only "did you paste a key?" does.
+ // Self-host gets the feature unconditionally via env.
+ 'ai_agent',
],
},
},
@@ -143,11 +142,6 @@ export const PLANS: Record<PlanId, Plan> = {
'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: {
@@ -206,10 +200,7 @@ export function hasFeature(plan: Plan, feature: Feature): boolean {
export function isWithinLimit(
plan: Plan,
- key: keyof Omit<
- PlanLimits,
- 'features' | 'allowedScrapers' | 'allowedModels' | 'aiAgentTokenQuota'
- >,
+ key: keyof Omit<PlanLimits, 'features' | 'allowedScrapers' | 'allowedModels'>,
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.ts
index 924c0a2ac..bb4451ab5 100644
--- a/web/src/hooks/use-feature-gate.ts
+++ b/web/src/hooks/use-feature-gate.ts
@@ -24,20 +24,14 @@ export function useFeatureGate() {
},
withinLimit(
- key: keyof Omit<
- PlanLimits,
- 'features' | 'allowedScrapers' | 'allowedModels' | 'aiAgentTokenQuota'
- >,
+ key: keyof Omit<PlanLimits, 'features' | 'allowedScrapers' | 'allowedModels'>,
currentCount: number,
): boolean {
return isWithinLimit(plan, key, currentCount);
},
getLimit(
- key: keyof Omit<
- PlanLimits,
- 'features' | 'allowedScrapers' | 'allowedModels' | 'aiAgentTokenQuota'
- >,
+ key: keyof Omit<PlanLimits, 'features' | 'allowedScrapers' | 'allowedModels'>,
): number {
return plan.limits[key];
},
diff --git a/web/src/lib/agent/auth.ts b/web/src/lib/agent/auth.ts
new file mode 100644
index 000000000..995f21843
--- /dev/null
+++ b/web/src/lib/agent/auth.ts
@@ -0,0 +1,39 @@
+import { createClient } from '@/lib/supabase/server';
+import { supabaseAdmin } from '@/lib/supabase/admin';
+import type { McpAuthContext } from '@/lib/mcp-auth';
+
+/**
+ * Resolve the current dashboard session into the same shape the MCP data
+ * layer expects (`McpAuthContext`). The agent's tools are the MCP read
+ * functions called directly as JS — bypassing the MCP transport — so they
+ * need the same auth context the MCP layer relies on for org scoping.
+ *
+ * Returns `null` when the user isn't signed in or doesn't have a profile
+ * row pinning them to an organization.
+ */
+export async function resolveAgentAuth(): Promise<McpAuthContext | null> {
+ const supabase = await createClient();
+ const {
+ data: { user },
+ } = await supabase.auth.getUser();
+ if (!user) return null;
+
+ const { data: profile } = await supabaseAdmin
+ .from('profiles')
+ .select('organization_id')
+ .eq('id', user.id)
+ .maybeSingle();
+
+ if (!profile?.organization_id) return null;
+
+ return {
+ userId: user.id,
+ email: user.email ?? '',
+ organizationId: profile.organization_id,
+ // The MCP-auth shape expects an apiKeyId — the agent isn't behind an
+ // API key, this is just a marker so downstream code that switches on
+ // the field knows the call came from the in-product agent rather than
+ // an external MCP client.
+ apiKeyId: 'agent-internal',
+ };
+}
diff --git a/web/src/lib/agent/key-encryption.ts b/web/src/lib/agent/key-encryption.ts
new file mode 100644
index 000000000..23a52f77b
--- /dev/null
+++ b/web/src/lib/agent/key-encryption.ts
@@ -0,0 +1,104 @@
+import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
+
+/**
+ * App-level encryption for Anthropic API keys stored on `organizations`.
+ *
+ * Tradeoff vs. Supabase Vault / pgsodium: doing this at the app layer keeps
+ * the only thing that can decrypt the key out of the database entirely —
+ * a Postgres user or Supabase admin with read access to `organizations`
+ * sees ciphertext only. The master key lives in env (`ANSVISOR_ENCRYPTION_KEY`)
+ * which is rotated via Vercel env management.
+ *
+ * Algorithm: AES-256-GCM with a fresh 12-byte IV per encryption and the
+ * GCM auth tag attached. We store the envelope as a small JSON blob so
+ * future versions can bump `v` and migrate without ambiguity.
+ *
+ * Envelope format: `{ v: 1, iv: <base64>, tag: <base64>, ct: <base64> }`
+ */
+
+const ALGO = 'aes-256-gcm';
+const IV_BYTES = 12; // GCM recommended IV size
+const KEY_BYTES = 32; // AES-256 = 32-byte key
+const VERSION = 1;
+
+interface Envelope {
+ v: number;
+ iv: string;
+ tag: string;
+ ct: string;
+}
+
+function loadMasterKey(): Buffer {
+ const raw = process.env.ANSVISOR_ENCRYPTION_KEY;
+ if (!raw) {
+ throw new Error(
+ 'ANSVISOR_ENCRYPTION_KEY is not set. Generate one with `openssl rand -base64 32` and add it to web/.env.',
+ );
+ }
+ const key = Buffer.from(raw, 'base64');
+ if (key.length !== KEY_BYTES) {
+ throw new Error(
+ `ANSVISOR_ENCRYPTION_KEY must decode to ${KEY_BYTES} bytes (got ${key.length}). Use \`openssl rand -base64 32\`.`,
+ );
+ }
+ return key;
+}
+
+/**
+ * Encrypt a plaintext API key for storage. Throws if the env master key
+ * is missing or malformed — callers should let that bubble; refusing to
+ * write is the correct behavior for misconfigured envs.
+ */
+export function encryptApiKey(plaintext: string): string {
+ if (!plaintext) throw new Error('encryptApiKey: empty plaintext');
+ const key = loadMasterKey();
+ const iv = randomBytes(IV_BYTES);
+ const cipher = createCipheriv(ALGO, key, iv);
+ const ct = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
+ const tag = cipher.getAuthTag();
+ const envelope: Envelope = {
+ v: VERSION,
+ iv: iv.toString('base64'),
+ tag: tag.toString('base64'),
+ ct: ct.toString('base64'),
+ };
+ return JSON.stringify(envelope);
+}
+
+/**
+ * Decrypt an envelope produced by `encryptApiKey`. Returns null if the
+ * envelope is malformed, version is unsupported, or decryption fails —
+ * callers treat null as "key unusable, surface a re-entry prompt".
+ */
+export function decryptApiKey(envelopeJson: string | null | undefined): string | null {
+ if (!envelopeJson) return null;
+ let envelope: Envelope;
+ try {
+ envelope = JSON.parse(envelopeJson) as Envelope;
+ } catch {
+ return null;
+ }
+ if (envelope.v !== VERSION) return null;
+ if (!envelope.iv || !envelope.tag || !envelope.ct) return null;
+ try {
+ const key = loadMasterKey();
+ const iv = Buffer.from(envelope.iv, 'base64');
+ const tag = Buffer.from(envelope.tag, 'base64');
+ const ct = Buffer.from(envelope.ct, 'base64');
+ const decipher = createDecipheriv(ALGO, key, iv);
+ decipher.setAuthTag(tag);
+ const pt = Buffer.concat([decipher.update(ct), decipher.final()]);
+ return pt.toString('utf8');
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Last 4 chars of the plaintext, returned to the UI for "sk-…abcd" display.
+ * Mirrored into `organizations.anthropic_api_key_last4` so reading it back
+ * doesn't require decrypt.
+ */
+export function last4(plaintext: string): string {
+ return plaintext.slice(-4);
+}
diff --git a/web/src/lib/agent/key.ts b/web/src/lib/agent/key.ts
new file mode 100644
index 000000000..04e1c862e
--- /dev/null
+++ b/web/src/lib/agent/key.ts
@@ -0,0 +1,50 @@
+import { supabaseAdmin } from '@/lib/supabase/admin';
+import { isCloud } from '@/config/plans';
+import { decryptApiKey } from '@/lib/agent/key-encryption';
+
+/**
+ * Resolve the Anthropic API key that the agent should use for this org.
+ *
+ * - **Self-host** (`isCloud() === false`): falls back to the operator's
+ * own `ANTHROPIC_API_KEY` env var. The org table is ignored — self-host
+ * instances belong to one customer who configures the model centrally.
+ * - **Cloud**: reads `organizations.anthropic_api_key_encrypted`, decrypts
+ * via `decryptApiKey`, and returns the plaintext. Returns `null` if the
+ * org hasn't set a key yet or if the envelope can't be decrypted (master
+ * key rotated without re-saving, malformed row, etc.) — callers turn
+ * that into a 403 + "set a key in Settings" CTA.
+ *
+ * Never logs the plaintext. Never returns the env key on cloud (avoid the
+ * footgun of one customer falling back to Ansvisor's own quota).
+ */
+export async function resolveAnthropicKey(organizationId: string): Promise<string | null> {
+ if (!isCloud()) {
+ return process.env.ANTHROPIC_API_KEY ?? null;
+ }
+
+ const { data } = await supabaseAdmin
+ .from('organizations')
+ .select('anthropic_api_key_encrypted')
+ .eq('id', organizationId)
+ .maybeSingle();
+
+ if (!data?.anthropic_api_key_encrypted) return null;
+ return decryptApiKey(data.anthropic_api_key_encrypted);
+}
+
+/**
+ * Lightweight "is a key configured?" check that avoids decrypt — handy for
+ * page-load gating where we only need to know whether to render the chat
+ * UI vs the "set a key" empty state.
+ */
+export async function isAnthropicKeyConfigured(organizationId: string): Promise<boolean> {
+ if (!isCloud()) {
+ return !!process.env.ANTHROPIC_API_KEY;
+ }
+ const { data } = await supabaseAdmin
+ .from('organizations')
+ .select('anthropic_api_key_encrypted')
+ .eq('id', organizationId)
+ .maybeSingle();
+ return !!data?.anthropic_api_key_encrypted;
+}
diff --git a/web/src/lib/agent/model.ts b/web/src/lib/agent/model.ts
new file mode 100644
index 000000000..0e1008168
--- /dev/null
+++ b/web/src/lib/agent/model.ts
@@ -0,0 +1,18 @@
+import { createAnthropic, type AnthropicProvider } from '@ai-sdk/anthropic';
+
+/**
+ * Builds the in-product agent's LLM with the caller-supplied API key.
+ *
+ * We can't export a singleton model anymore — on cloud each org brings its
+ * own Anthropic key (Settings → Agent), so the key is request-scoped. The
+ * chat route resolves the key per turn via `resolveAnthropicKey(orgId)`
+ * and hands it to this builder; self-host passes the operator's env key.
+ *
+ * Model choice (claude-sonnet-4-6) stays consistent with the
+ * brief-generation flow on aeo-server so behavior + cost shape match
+ * across the product.
+ */
+export function buildAgentModel(apiKey: string): ReturnType<AnthropicProvider> {
+ const anthropic = createAnthropic({ apiKey });
+ return anthropic('claude-sonnet-4-6');
+}
diff --git a/web/src/lib/agent/system-prompt.ts b/web/src/lib/agent/system-prompt.ts
new file mode 100644
index 000000000..302ae66ec
--- /dev/null
+++ b/web/src/lib/agent/system-prompt.ts
@@ -0,0 +1,48 @@
+/**
+ * In-product agent persona. Distilled from the Ansvisor AEO Coach skill
+ * (`skills/ansvisor-aeo-coach/SKILL.md`) so the chat panel behaves like
+ * the same analyst the MCP-server users get inside Claude Desktop —
+ * just running against the same data via internal tool calls instead of
+ * the MCP transport.
+ *
+ * Key constraints:
+ * - never invent numbers; always go through a tool first
+ * - respond in plain language, not JSON dumps; act like a 30-second
+ * marketing standup
+ * - if the user doesn't name a brand, ask (single-line clarification)
+ * - acknowledge tool gaps explicitly rather than faking the answer
+ */
+export const AGENT_SYSTEM_PROMPT = `You are an Answer Engine Optimization (AEO) analyst working on the user's brand visibility inside AI search products (ChatGPT, Gemini, Perplexity, Claude, Copilot, Google AI Overview, Google AI Mode). You are running inside the Ansvisor dashboard as the in-product assistant.
+
+Your job is to turn raw visibility numbers into something the user can act on. A marketer asking "how are we doing?" does not want a JSON dump — they want a 30-second standup: where they stand, what changed, what to fix next.
+
+## Tools available
+
+You have these tools, all scoped to the authenticated user's organization:
+
+- **list_brands** — lists brands the user can access. Always call this first if the user doesn't specify a brand.
+- **get_visibility_summary** — point-in-time snapshot of avg visibility, mentions, citations for a brand over an optional window.
+- **get_visibility_trend** — time-series of visibility / mentions / citations over a date range, bucketed by day or week. Also includes avg competitor score per bucket. Use this for "how has it changed?" questions and to suggest charts.
+- **get_competitor_comparison** — competitor benchmark + share of voice for a brand. Returns the brand and every tracked competitor with avg visibility, mentions, citations, appearance count, plus overall SoV and per-platform SoV.
+- **list_citations** — URLs and domains AI engines cite alongside the brand, classified by source type (news / review / owned / social / forum / competitor / you). Returns totals, source-type breakdown, and top cited domains + URLs.
+- **list_topics** — topics on a brand with prompt count each. Use for coverage audits.
+- **list_prompts** — prompts being tracked for a brand. Use when the user asks what is being tracked or wants to drill into a specific topic.
+- **list_content_opportunities** — content gaps for a brand sorted by opportunity score. Use for "what should I write?" questions.
+
+## Rules
+
+1. **Never invent numbers.** Always call a tool to get the data before answering with numbers. If you don't have a tool for what's being asked, say so plainly.
+2. **If the user doesn't name a brand**, call list_brands. If there's only one, use it silently. If there are several, ask which one with a one-line clarification listing the names — do not pick for them.
+3. **Reply in plain language**, not JSON or tables of raw numbers. Numbers belong inline in sentences. A trend over 30 days is one sentence about the slope plus a number, not 30 rows.
+4. **Lead with the headline.** Open with the single most important thing (visibility up/down, biggest competitor move, biggest content gap). Details follow.
+5. **Be concrete about what to do next.** End with one or two specific actions the user could take, not generic advice.
+6. **Acknowledge tool gaps.** If you'd want to answer a question but lack a tool for it (e.g., the user asks about something only an upcoming tool would expose), say what's missing rather than guessing.
+7. **Respect the user's window.** If they ask about "this week," pass an explicit date_from to the time-aware tools; don't fall back to all-time.
+
+## Scoring reference
+
+- **Visibility score** is 0–100 per result, averaged across results in the window. Below 30 = essentially invisible; 30–60 = present but not dominant; 60+ = strong presence.
+- **Share of voice** is the brand's share of mentions among (brand + tracked competitors) in AI responses. SoV moves more slowly than visibility — a 5-point shift week-over-week is significant.
+- **Citations** are URLs AI engines explicitly link to. Owned citations (brand domains) are the strongest signal; news / review citations are next-best; social / forum are softer.
+
+Start by greeting briefly only on the first message in a conversation; on follow-ups, get straight to the answer.`;
diff --git a/web/src/lib/agent/token-quota.ts b/web/src/lib/agent/token-quota.ts
new file mode 100644
index 000000000..b08160aa5
--- /dev/null
+++ b/web/src/lib/agent/token-quota.ts
@@ -0,0 +1,64 @@
+import { supabaseAdmin } from '@/lib/supabase/admin';
+
+/**
+ * Returns the current calendar month in UTC as `YYYY-MM`, matching the
+ * shape stored in `agent_token_usage.year_month`. Used as the bucket key
+ * for the per-month usage row this module writes.
+ */
+export function currentYearMonth(): string {
+ const now = new Date();
+ const y = now.getUTCFullYear();
+ const m = String(now.getUTCMonth() + 1).padStart(2, '0');
+ return `${y}-${m}`;
+}
+
+/**
+ * Add this turn's token usage to the user's monthly bucket. Kept after the
+ * switch to BYOK on cloud purely for product analytics — we no longer pay
+ * for the tokens, but knowing how heavily each org uses the agent
+ * informs roadmap calls (e.g. "Starter customers are sending 5x what we
+ * expected through their own keys, the feature is sticky").
+ *
+ * Combined `prompt + completion` is what reports compare against; both
+ * are stored so we can break the cost shape down later.
+ *
+ * Uses Postgres `upsert` semantics through a fetch-then-write — the unique
+ * constraint on (user_id, organization_id, year_month) protects against
+ * races at the DB layer.
+ */
+export async function recordAgentTokenUsage(
+ userId: string,
+ organizationId: string,
+ promptTokens: number,
+ completionTokens: number,
+): Promise<void> {
+ if (promptTokens <= 0 && completionTokens <= 0) return;
+
+ const yearMonth = currentYearMonth();
+
+ const { data: existing } = await supabaseAdmin
+ .from('agent_token_usage')
+ .select('id, prompt_tokens, completion_tokens')
+ .eq('user_id', userId)
+ .eq('organization_id', organizationId)
+ .eq('year_month', yearMonth)
+ .maybeSingle();
+
+ if (existing) {
+ await supabaseAdmin
+ .from('agent_token_usage')
+ .update({
+ prompt_tokens: Number(existing.prompt_tokens ?? 0) + promptTokens,
+ completion_tokens: Number(existing.completion_tokens ?? 0) + completionTokens,
+ })
+ .eq('id', existing.id);
+ } else {
+ await supabaseAdmin.from('agent_token_usage').insert({
+ user_id: userId,
+ organization_id: organizationId,
+ year_month: yearMonth,
+ prompt_tokens: promptTokens,
+ completion_tokens: completionTokens,
+ });
+ }
+}
diff --git a/web/src/lib/agent/tools.ts b/web/src/lib/agent/tools.ts
new file mode 100644
index 000000000..81eadcb5b
--- /dev/null
+++ b/web/src/lib/agent/tools.ts
@@ -0,0 +1,172 @@
+import { tool } from 'ai';
+import { z } from 'zod';
+import type { McpAuthContext } from '@/lib/mcp-auth';
+import {
+ CONTENT_OPPORTUNITY_STATUSES,
+ getCompetitorComparisonFor,
+ getVisibilitySummaryFor,
+ getVisibilityTrendFor,
+ listBrandsFor,
+ listCitationsFor,
+ listContentOpportunitiesFor,
+ listPromptsFor,
+ listTopicsFor,
+} from '@/lib/mcp/data';
+
+/**
+ * Vercel AI SDK tool definitions for the in-product agent. Each tool is a
+ * thin wrapper around the same MCP data function the external MCP server
+ * exposes — `list_brands` is `listBrandsFor`, etc. — so the agent sees the
+ * exact same data Claude Desktop / Cursor users see, with the same
+ * org-ownership scoping. We don't duplicate any aggregation logic here.
+ *
+ * Tool names are kept identical to the MCP tool ids so the system prompt's
+ * tool list reads the same in both surfaces.
+ */
+export function buildAgentTools(auth: McpAuthContext) {
+ return {
+ list_brands: tool({
+ description:
+ 'List the brands the authenticated user can access. Returns id, name, slug, industry, region, created_at. Call this first when the user has not named a brand.',
+ inputSchema: z.object({}),
+ execute: async () => listBrandsFor(auth),
+ }),
+
+ get_visibility_summary: tool({
+ description:
+ 'Get aggregate visibility metrics for a brand over an optional date range. Returns result count, average visibility (0-100), total mentions, total citations, and the top 5 competitors by mention count. Use for snapshot / "how is my brand doing" questions.',
+ inputSchema: z.object({
+ brand_id: z.string().uuid(),
+ date_from: z.string().optional(),
+ date_to: z.string().optional(),
+ model: z.string().optional(),
+ region: z.string().optional(),
+ }),
+ execute: async (args) =>
+ getVisibilitySummaryFor(auth, {
+ brandId: args.brand_id,
+ dateFrom: args.date_from,
+ dateTo: args.date_to,
+ model: args.model,
+ region: args.region,
+ }),
+ }),
+
+ get_visibility_trend: tool({
+ description:
+ 'Visibility / mentions / citations over time for a brand, bucketed by day or week. Each bucket includes avg_visibility_score, total_mentions, total_citations, avg_competitor_score. Use for trend questions and as the data source for charts.',
+ inputSchema: z.object({
+ brand_id: z.string().uuid(),
+ date_from: z.string().optional(),
+ date_to: z.string().optional(),
+ granularity: z.enum(['day', 'week']).optional(),
+ model: z.string().optional(),
+ region: z.string().optional(),
+ topic_id: z.string().uuid().optional(),
+ }),
+ execute: async (args) =>
+ getVisibilityTrendFor(auth, {
+ brandId: args.brand_id,
+ dateFrom: args.date_from,
+ dateTo: args.date_to,
+ model: args.model,
+ region: args.region,
+ topicId: args.topic_id,
+ granularity: args.granularity,
+ }),
+ }),
+
+ get_competitor_comparison: tool({
+ description:
+ 'Competitor benchmark + share of voice for a brand. Returns the brand and every tracked competitor with avg_visibility_score, total_mentions, total_citations, appearance_count, plus overall_sov_pct and a per-(model_used, platform) SoV split.',
+ inputSchema: z.object({
+ brand_id: z.string().uuid(),
+ date_from: z.string().optional(),
+ date_to: z.string().optional(),
+ model: z.string().optional(),
+ region: z.string().optional(),
+ topic_id: z.string().uuid().optional(),
+ }),
+ execute: async (args) =>
+ getCompetitorComparisonFor(auth, {
+ brandId: args.brand_id,
+ dateFrom: args.date_from,
+ dateTo: args.date_to,
+ model: args.model,
+ region: args.region,
+ topicId: args.topic_id,
+ }),
+ }),
+
+ list_citations: tool({
+ description:
+ 'URLs and domains AI engines cite alongside a brand, classified by source type (news / review / owned / social / forum / competitor / you). Returns totals, source_type_breakdown, top_domains, top_urls.',
+ inputSchema: z.object({
+ brand_id: z.string().uuid(),
+ date_from: z.string().optional(),
+ date_to: z.string().optional(),
+ model: z.string().optional(),
+ region: z.string().optional(),
+ topic_id: z.string().uuid().optional(),
+ limit: z.number().int().min(1).max(200).optional(),
+ }),
+ execute: async (args) =>
+ listCitationsFor(auth, {
+ brandId: args.brand_id,
+ dateFrom: args.date_from,
+ dateTo: args.date_to,
+ model: args.model,
+ region: args.region,
+ topicId: args.topic_id,
+ limit: args.limit,
+ }),
+ }),
+
+ list_topics: tool({
+ description:
+ 'List topics for a brand, each with prompt_count. Use for coverage audits or before drilling into prompts on a theme.',
+ inputSchema: z.object({
+ brand_id: z.string().uuid(),
+ }),
+ execute: async (args) => listTopicsFor(auth, args.brand_id),
+ }),
+
+ list_prompts: tool({
+ description:
+ 'List the prompts tracked for a brand, optionally filtered by topic or active status. Returns each prompt with text, topic, platforms, models, regions, is_active.',
+ inputSchema: z.object({
+ brand_id: z.string().uuid(),
+ topic_id: z.string().uuid().optional(),
+ is_active: z.boolean().optional(),
+ limit: z.number().int().min(1).max(500).optional(),
+ }),
+ execute: async (args) =>
+ listPromptsFor(auth, {
+ brandId: args.brand_id,
+ topicId: args.topic_id,
+ isActive: args.is_active,
+ limit: args.limit,
+ }),
+ }),
+
+ list_content_opportunities: tool({
+ description:
+ 'List content opportunities / gaps for a brand, sorted by opportunity score descending. Use for "what should I write?" / strategy-priority questions.',
+ inputSchema: z.object({
+ brand_id: z.string().uuid(),
+ status: z.enum(CONTENT_OPPORTUNITY_STATUSES).optional(),
+ impact: z.enum(['high', 'medium', 'low']).optional(),
+ type: z.enum(['owned', 'earned']).optional(),
+ limit: z.number().int().min(1).max(200).optional(),
+ }),
+ execute: async (args) =>
+ listContentOpportunitiesFor(auth, {
+ brandId: args.brand_id,
+ status: args.status,
+ impact: args.impact,
+ type: args.type,
+ limit: args.limit,
+ }),
+ }),
+ };
+}
diff --git a/web/src/lib/guards/plan-guard.ts b/web/src/lib/guards/plan-guard.ts
index 724197b1d..34cf66a24 100644
--- a/web/src/lib/guards/plan-guard.ts
+++ b/web/src/lib/guards/plan-guard.ts
@@ -56,10 +56,7 @@ export async function enforceFeature(organizationId: string, feature: Feature):
export async function enforceLimit(
organizationId: string,
- key: keyof Omit<
- PlanLimits,
- 'features' | 'allowedScrapers' | 'allowedModels' | 'aiAgentTokenQuota'
- >,
+ key: keyof Omit<PlanLimits, 'features' | 'allowedScrapers' | 'allowedModels'>,
currentCount: number,
): Promise<void> {
const plan = await getOrgPlan(organizationId);
diff --git a/web/yarn.lock b/web/yarn.lock
index 8fec9f013..c7ea6908d 100644
--- a/web/yarn.lock
+++ b/web/yarn.lock
@@ -2,6 +2,49 @@
# yarn lockfile v1
+"@ai-sdk/anthropic@^3.0.58":
+ version "3.0.81"
+ resolved "https://registry.yarnpkg.com/@ai-sdk/anthropic/-/anthropic-3.0.81.tgz#9580a7fba6e5c525feafe94a885c085ff7d45aee"
+ integrity sha512-B1JDd9Ugq9R5AgIaW3674lhGCMMYJcPUxnrZh8fzbGojgg4QvHFRv6eZahGQAUsmGHbcf74G9bdSBDLWQGY2GA==
+ dependencies:
+ "@ai-sdk/provider" "3.0.10"
+ "@ai-sdk/provider-utils" "4.0.27"
+
+"@ai-sdk/[email protected]":
+ version "3.0.121"
+ resolved "https://registry.yarnpkg.com/@ai-sdk/gateway/-/gateway-3.0.121.tgz#14cd9daa48516ad5a8023c8889d8a63e254fe77e"
+ integrity sha512-uY248djJRxa5W68MHiyqO8WLdOeKQoRClGg7PVX/VPhVW8SJNM7/l5DcrA5WAM3YfQrLyNkgZa2VOu8T0t8LUw==
+ dependencies:
+ "@ai-sdk/provider" "3.0.10"
+ "@ai-sdk/provider-utils" "4.0.27"
+ "@vercel/oidc" "3.2.0"
+
+"@ai-sdk/[email protected]":
+ version "4.0.27"
+ resolved "https://registry.yarnpkg.com/@ai-sdk/provider-utils/-/provider-utils-4.0.27.tgz#d2183685768626bcf1c968b7d73ea2b974da59b9"
+ integrity sha512-ubkAJ+xODouwtmN1tYlvTPphH1hPOBfZaEQe8U7skGvFAnIRs9PPpsq57bC2+Ky/MB4yzhd6YOsxTAx9sGpazw==
+ dependencies:
+ "@ai-sdk/provider" "3.0.10"
+ "@standard-schema/spec" "^1.1.0"
+ eventsource-parser "^3.0.8"
+
+"@ai-sdk/[email protected]":
+ version "3.0.10"
+ resolved "https://registry.yarnpkg.com/@ai-sdk/provider/-/provider-3.0.10.tgz#abfb6776f699951f9b8ac20cf1d42a3fc7d79752"
+ integrity sha512-Q3BZ27qfpYqnCYGvE3vt+Qi6LGOF9R5Nmzn+9JoM1lCRsD9mYaIhfJLkSunN48nfGXJ6n+XNV0J/XVpqGQl7Dw==
+ dependencies:
+ json-schema "^0.4.0"
+
+"@ai-sdk/react@^3.0.81":
+ version "3.0.195"
+ resolved "https://registry.yarnpkg.com/@ai-sdk/react/-/react-3.0.195.tgz#dc74b0b27cddbc316433119edb9aaba161b4aa49"
+ integrity sha512-+yIH84d4bBNzLKfaDDf4EocEH0XQKKNwNShxbrz5xAiJMNIPnWVWT9cyrSerYaGH3iNVS/g2io42PE4HNbc4RA==
+ dependencies:
+ "@ai-sdk/provider-utils" "4.0.27"
+ ai "6.0.193"
+ swr "^2.2.5"
+ throttleit "2.1.0"
+
"@alloc/quick-lru@^5.2.0":
version "5.2.0"
resolved "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz"
@@ -1334,7 +1377,7 @@
resolved "https://registry.npmjs.org/@sindresorhus/merge-streams/-/merge-streams-4.0.0.tgz"
integrity sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ==
-"@standard-schema/spec@^1.0.0":
+"@standard-schema/spec@^1.0.0", "@standard-schema/spec@^1.1.0":
version "1.1.0"
resolved "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz"
integrity sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==
@@ -2003,6 +2046,11 @@
resolved "https://registry.yarnpkg.com/@vercel/analytics/-/analytics-2.0.1.tgz#d7d7bd37af7cfbeea95db5f132ae4889f4d26407"
integrity sha512-MTQG6V9qQrt1tsDeF+2Uoo5aPjqbVPys1xvnIftXSJYG2SrwXRHnqEvVoYID7BTruDz4lCd2Z7rM1BdkUehk2g==
+"@vercel/[email protected]":
+ version "3.2.0"
+ resolved "https://registry.yarnpkg.com/@vercel/oidc/-/oidc-3.2.0.tgz#5782a4d4904443f015808705b5537cf9c3b68528"
+ integrity sha512-UycprH3T6n3jH0k44NHMa7pnFHGu/N05MjojYr+Mc6I7obkoLIJujSWwin1pCvdy/eOxrI/l3uDLQsmcrOb4ug==
+
accepts@^2.0.0:
version "2.0.0"
resolved "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz"
@@ -2026,6 +2074,16 @@ agent-base@^7.1.2:
resolved "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz"
integrity sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==
[email protected], ai@^6.0.116:
+ version "6.0.193"
+ resolved "https://registry.yarnpkg.com/ai/-/ai-6.0.193.tgz#f35c21dda142e8c7fb55f8932562b1b586e404b7"
+ integrity sha512-VQOTOse8+X8kMtg61DNSXlYJzwOW4NjMLDJNk/qxClWsFe4oiyFJDHGGG1oezfGcFzuYuQe/8Z7r4kwiZWh2YQ==
+ dependencies:
+ "@ai-sdk/gateway" "3.0.121"
+ "@ai-sdk/provider" "3.0.10"
+ "@ai-sdk/provider-utils" "4.0.27"
+ "@opentelemetry/api" "^1.9.0"
+
ajv-formats@^3.0.1:
version "3.0.1"
resolved "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz"
@@ -2711,7 +2769,7 @@ depd@^2.0.0, depd@~2.0.0:
resolved "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz"
integrity sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==
-dequal@^2.0.0:
+dequal@^2.0.0, dequal@^2.0.3:
version "2.0.3"
resolved "https://registry.yarnpkg.com/dequal/-/dequal-2.0.3.tgz#2644214f1997d39ed0ee0ece72335490a7ac67be"
integrity sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==
@@ -3222,6 +3280,11 @@ eventsource-parser@^3.0.0, eventsource-parser@^3.0.1:
resolved "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.6.tgz"
integrity sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==
+eventsource-parser@^3.0.8:
+ version "3.1.0"
+ resolved "https://registry.yarnpkg.com/eventsource-parser/-/eventsource-parser-3.1.0.tgz#4e198eb91cd333d0a8ddcc036502b3618a25f449"
+ integrity sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg==
+
eventsource@^3.0.2:
version "3.0.7"
resolved "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz"
@@ -4249,6 +4312,11 @@ json-schema-typed@^8.0.2:
resolved "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz"
integrity sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==
+json-schema@^0.4.0:
+ version "0.4.0"
+ resolved "https://registry.yarnpkg.com/json-schema/-/json-schema-0.4.0.tgz#f7de4cf6efab838ebaeb3236474cbba5a1930ab5"
+ integrity sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==
+
json-stable-stringify-without-jsonify@^1.0.1:
version "1.0.1"
resolved "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz"
@@ -6376,6 +6444,14 @@ supports-preserve-symlinks-flag@^1.0.0:
resolved "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz"
integrity sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==
+swr@^2.2.5:
+ version "2.4.1"
+ resolved "https://registry.yarnpkg.com/swr/-/swr-2.4.1.tgz#c9e48abff6bf4b04846342e2f1f6be108a078cf6"
+ integrity sha512-2CC6CiKQtEwaEeNiqWTAw9PGykW8SR5zZX8MZk6TeAvEAnVS7Visz8WzphqgtQ8v2xz/4Q5K+j+SeMaKXeeQIA==
+ dependencies:
+ dequal "^2.0.3"
+ use-sync-external-store "^1.6.0"
+
tabbable@^6.4.0:
version "6.4.0"
resolved "https://registry.npmjs.org/tabbable/-/tabbable-6.4.0.tgz"
@@ -6401,6 +6477,11 @@ tapable@^2.3.0:
resolved "https://registry.npmjs.org/tapable/-/tapable-2.3.0.tgz"
integrity sha512-g9ljZiwki/LfxmQADO3dEY1CbpmXT5Hm2fJ+QaGKwSXUylMybePR7/67YW7jOrrvjEgL1Fmz5kzyAjWVWLlucg==
+ version "2.1.0"
+ resolved "https://registry.yarnpkg.com/throttleit/-/throttleit-2.1.0.tgz#a7e4aa0bf4845a5bd10daa39ea0c783f631a07b4"
+ integrity sha512-nt6AMGKW1p/70DF/hGBdJB57B8Tspmbp5gfJ8ilhLnt7kkr2ye7hzD6NVG8GGErk2HWF34igrL2CXmNIkzKqKw==
+
tiny-invariant@^1.3.3:
version "1.3.3"
resolved "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz"