OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
feat: new ai chat
Carl-Gerhard Lindesvärd347c14e115c0
diff --git a/apps/api/package.json b/apps/api/package.jsonindex aabf084c0..842e79989 100644--- a/apps/api/package.json+++ b/apps/api/package.json@@ -14,8 +14,9 @@"typecheck": "tsc --noEmit"},"dependencies": {- "@ai-sdk/anthropic": "^1.2.10",- "@ai-sdk/openai": "^1.3.12",+ "@better-agent/adapters": "^0.1.0-beta.3",+ "@better-agent/core": "^0.1.0-beta.3",+ "@better-agent/providers": "^0.1.0-beta.3","@fastify/compress": "^8.1.0","@fastify/cookie": "^11.0.2","@fastify/cors": "^11.1.0",@@ -39,7 +40,6 @@"@openpanel/trpc": "workspace:*","@openpanel/validation": "workspace:*","@trpc/server": "^11.6.0",- "ai": "^4.2.10","fast-json-stable-hash": "^1.0.3","fastify": "^5.6.1","fastify-metrics": "^12.1.0",diff --git a/apps/api/src/agents/app.ts b/apps/api/src/agents/app.tsnew file mode 100644index 000000000..5178cea39--- /dev/null+++ b/apps/api/src/agents/app.ts@@ -0,0 +1,87 @@+import { betterAgent, defineAgent } from '@better-agent/core';+import { type ChatAgentContext, chatContextSchema } from './context';+import { ALLOWED_MODELS, type ChatModelEntry, openaiProvider, resolveModel } from './models';+import { prismaConversationStore } from './persistence';+import { buildSystemPrompt } from './prompt';+import { composeChatTools } from './tools';++/**+ * Create one agent per model in the whitelist. All agents share the+ * same context schema, instruction builder, and dynamic tool composer+ * — they only differ by which provider model runs the conversation.+ *+ * The frontend "model picker" is an "agent picker" in disguise: it+ * just selects which agent name to pass to `useAgent()`.+ *+ * The whole config is `any`-cast because `resolveModel` returns a+ * union of provider model types, and `defineAgent`'s conditional+ * generics (`InstructionEnabled`, `DefineAgentToolFields`) can't+ * narrow over the union — they fall back to `object`, which strips+ * the `instruction` and `tools` fields from the inferred config type.+ * All providers in our whitelist support both at runtime; the cast+ * just sidesteps the TS narrowing limit. `defineAgent` itself runs+ * a runtime `validateAgentDefinition` check so misconfigurations+ * still throw at startup.+ */+function createChatAgent(entry: ChatModelEntry) {+ return defineAgent({+ name: entry.id,+ description: `OpenPanel chat assistant (${entry.label})`,+ model: resolveModel(entry),+ contextSchema: chatContextSchema,+ instruction: (context: ChatAgentContext) => buildSystemPrompt(context),+ tools: (context: ChatAgentContext) => composeChatTools(context),+ maxSteps: 20,+ // Reasoning-capable models (gpt-5.x / o-series) need the+ // `reasoning.summary` option to stream reasoning text back; the+ // client's REASONING_MESSAGE_* events feed our `ReasoningBlock`+ // UI. Non-reasoning models skip this block entirely.+ ...(entry.reasoning+ ? {+ defaultModelOptions: {+ reasoning: {+ effort: 'medium',+ summary: 'auto',+ },+ },+ }+ : {}),+ // biome-ignore lint/suspicious/noExplicitAny: see block comment above+ } as any);+}++/**+ * Dedicated cheap agent for generating 3-5 word conversation titles.+ * Called fire-and-forget from the Fastify wrapper after the first+ * turn of a new conversation completes.+ */+const titlerAgent = defineAgent({+ name: '__titler',+ description: 'Generates concise 3-5 word titles for chat conversations.',+ // biome-ignore lint/suspicious/noExplicitAny: OpenAI model id union is open+ model: openaiProvider().model('gpt-4.1-mini' as any),+ instruction:+ 'You generate concise 3-5 word titles for chat conversations. Respond with ONLY the title. No quotes, no punctuation, no trailing period.',+ maxSteps: 1,+ // biome-ignore lint/suspicious/noExplicitAny: see block comment on createChatAgent+} as any);++/**+ * The single Better Agent app. Exports a `.handler` that the Fastify+ * adapter mounts under `/ai/agents/*`. Holds:+ * - one agent per allowed model+ * - the Prisma-backed conversation store for persistence+ * - a dedicated titler agent for conversation titles+ *+ * Auth + project-access are enforced by the Fastify wrapper before+ * this handler runs — see `apps/api/src/app.ts`.+ */+export const chatApp = betterAgent({+ agents: [...ALLOWED_MODELS.map(createChatAgent), titlerAgent],+ persistence: {+ conversations: prismaConversationStore,+ },+ baseURL: '/ai/agents',+});++export type ChatApp = typeof chatApp;diff --git a/apps/api/src/agents/context.ts b/apps/api/src/agents/context.tsnew file mode 100644index 000000000..7a146a2e4--- /dev/null+++ b/apps/api/src/agents/context.ts@@ -0,0 +1,14 @@+// Re-export the shared chat schemas from `@openpanel/validation` so the+// rest of the agent code can keep importing from `./context`. The+// schemas themselves live in validation because the frontend needs them+// too (see packages/validation/src/chat.ts).+export {+ chatContextSchema,+ pageContextSchema,+ pageContextPageSchema,+} from '@openpanel/validation';+export type {+ ChatAgentContext,+ PageContext,+ PageContextPage,+} from '@openpanel/validation';diff --git a/apps/api/src/agents/models.ts b/apps/api/src/agents/models.tsnew file mode 100644index 000000000..5a55b3678--- /dev/null+++ b/apps/api/src/agents/models.ts@@ -0,0 +1,54 @@+import { createOpenAI } from '@better-agent/providers/openai';+import { CHAT_MODELS, type ChatModelEntry } from '@openpanel/validation';++export { CHAT_MODELS as ALLOWED_MODELS, DEFAULT_MODEL_ID } from '@openpanel/validation';+export type { ChatModelEntry } from '@openpanel/validation';++// ────────────────────────────────────────────────────────────────────+// Provider clients (lazy-built singletons)+// ────────────────────────────────────────────────────────────────────++function requireEnv(name: string, provider: string): string {+ const value = process.env[name];+ if (!value) {+ // Don't throw here — the agent is built eagerly at import time and+ // we still want startup to succeed so the user can pick a model+ // whose key IS set. We throw when the agent actually runs.+ console.warn(+ `[chat] ${name} is not set. Models routed through ${provider} will fail with "x-api-key required" until you add it to the API's env.`,+ );+ }+ return value ?? '';+}++let _openai: ReturnType<typeof createOpenAI> | null = null;+function openai() {+ if (!_openai) {+ _openai = createOpenAI({+ apiKey: requireEnv('OPENAI_API_KEY', 'OpenAI'),+ });+ }+ return _openai;+}++/**+ * Exposed for the titler agent in `app.ts`. Same singleton as the one+ * used by the chat agents so we don't duplicate API-key wiring.+ */+export const openaiProvider = openai;++/**+ * Resolve a model entry to the provider's model instance.+ * Used by the agent factory.+ *+ * NB: Anthropic support has been removed. Re-add `createAnthropic`+ * from `@better-agent/providers/anthropic` + a switch arm here when+ * an Anthropic model is added to the whitelist.+ */+export function resolveModel(entry: ChatModelEntry) {+ switch (entry.group) {+ case 'OpenAI':+ // biome-ignore lint/suspicious/noExplicitAny: OpenAI model id union is open+ return openai().model(entry.modelId as any);+ }+}diff --git a/apps/api/src/agents/persistence.ts b/apps/api/src/agents/persistence.tsnew file mode 100644index 000000000..ad5331b01--- /dev/null+++ b/apps/api/src/agents/persistence.ts@@ -0,0 +1,115 @@+import type { ConversationStore } from '@better-agent/core';+import type { ConversationItem } from '@better-agent/core/providers';+import { db } from '@openpanel/db';+import { chatRunContext } from './run-context';++/**+ * Prisma-backed `ConversationStore` for Better Agent.+ *+ * One Better Agent `ConversationItem` (message, tool call, or tool+ * result) is stored as one `ChatMessage` row. The `parts` JSON column+ * holds the entire item; `role` is a discriminator for analytics.+ *+ * Save semantics: Better Agent hands us the FULL item list every save.+ * In steady state the list is append-only — earlier items don't change,+ * only new ones get added. We exploit that invariant with a cheap+ * row-count comparison, which is O(1) instead of deep-equaling every+ * prior item on every turn.+ *+ * If `items.length >= existingCount`, we insert only the tail. Any+ * other case (shrank, or user-initiated edit/retry) falls back to a+ * full wipe-and-rewrite. The trade-off: if Better Agent ever mutates+ * a prior item in place while keeping the total count the same, we'd+ * miss that change — but Better Agent's ConversationStore contract+ * documents that prior items are immutable, so this is safe.+ *+ * Cursor is the `updatedAt` timestamp. Better Agent uses it for+ * optimistic concurrency — we trust the single-writer-per-conversation+ * invariant and don't check it explicitly.+ */+function roleOf(item: ConversationItem): string {+ if (item.type === 'message') return item.role;+ return item.type;+}++function itemToRow(conversationId: string, item: ConversationItem) {+ return {+ conversationId,+ role: roleOf(item),+ // Prisma's `IPrismaUIMessageParts` narrows to `unknown[]`, but our+ // JSON column stores a single `ConversationItem` object. The+ // runtime is fine — Prisma accepts any JSON-serializable value —+ // so we cast past the generator.+ // biome-ignore lint/suspicious/noExplicitAny: see comment above+ parts: item as any,+ };+}++export const prismaConversationStore: ConversationStore = {+ async load({ conversationId }) {+ const conv = await db.conversation.findUnique({+ where: { id: conversationId },+ include: {+ messages: { orderBy: { createdAt: 'asc' } },+ },+ });+ if (!conv) return null;++ return {+ items: conv.messages.map((m) => m.parts as unknown as ConversationItem),+ cursor: conv.updatedAt.getTime(),+ };+ },++ async save({ conversationId, items }) {+ const owner = chatRunContext.getStore();+ if (!owner) {+ throw new Error(+ 'chatRunContext missing during save — the Fastify wrapper must run first',+ );+ }++ await db.$transaction(async (tx) => {+ await tx.conversation.upsert({+ where: { id: conversationId },+ create: {+ id: conversationId,+ projectId: owner.projectId,+ organizationId: owner.organizationId,+ userId: owner.userId,+ },+ update: { updatedAt: new Date() },+ });++ const existingCount = await tx.chatMessage.count({+ where: { conversationId },+ });++ if (items.length >= existingCount) {+ // Append-only fast path: Better Agent guarantees prior items+ // are immutable, so we can safely insert only the tail.+ const newItems = items.slice(existingCount);+ if (newItems.length > 0) {+ await tx.chatMessage.createMany({+ data: newItems.map((item) => itemToRow(conversationId, item)),+ });+ }+ } else {+ // Incoming list is shorter than what's stored — an edit,+ // retry, or deletion. Rewrite.+ await tx.chatMessage.deleteMany({ where: { conversationId } });+ if (items.length > 0) {+ await tx.chatMessage.createMany({+ data: items.map((item) => itemToRow(conversationId, item)),+ });+ }+ }+ });++ const updated = await db.conversation.findUnique({+ where: { id: conversationId },+ select: { updatedAt: true },+ });+ return { cursor: updated?.updatedAt.getTime() ?? Date.now() };+ },+};diff --git a/apps/api/src/agents/prompt.ts b/apps/api/src/agents/prompt.tsnew file mode 100644index 000000000..659869c44--- /dev/null+++ b/apps/api/src/agents/prompt.ts@@ -0,0 +1,224 @@+import type { ChatAgentContext, PageContext } from './context';++function buildBasePrompt(): string {+ return `You are the OpenPanel AI assistant. OpenPanel is an open-source product/web analytics platform similar to Mixpanel and Plausible. You help users explore and understand their analytics data.++The current date is supplied at the bottom of this prompt under "Current view". Use it for relative date math ("last week", "yesterday", "this month").++# Behavioral rules+- Every factual claim must come from a tool result. Never fabricate numbers, names, or dates.+- Prefer SAVED reports over ad-hoc generation: try list_dashboards → list_reports → get_report_data first when the user asks about something that might already be saved.+- Before calling generate_report, verify event names with list_event_names and breakdown property keys with list_event_properties.+- Use the user's current date range and filters from "Current view" below unless they explicitly ask for a different range.+- Cite data through rendered tool results, not by repeating numbers in prose. Keep prose short — let the UI do the work.+- If a tool result has _truncated: true, briefly mention there's more data available.++# Filtering the page (apply_filters / set_property_filters / set_event_names_filter)+The user can ask you to "filter to X" or "show me Y" — when they do, **call the matching client-side tool** to actually move the page, don't just describe the data.++For \`apply_filters\` (date range / interval):+- The ONLY valid preset values for \`range\` are: \`30min\`, \`lastHour\`, \`today\`, \`yesterday\`, \`7d\`, \`30d\`, \`6m\`, \`12m\`, \`monthToDate\`, \`lastMonth\`, \`yearToDate\`, \`lastYear\`, \`custom\`. Anything else is invalid and the page will reject it.+- Map common phrasing to presets when possible:+ - "last 7 days" / "past week" / "this week" → \`7d\`+ - "last 30 days" / "past month" → \`30d\`+ - "last 6 months" → \`6m\`+ - "last year" → \`lastYear\`+ - "this month" → \`monthToDate\`+ - "last month" → \`lastMonth\`+ - "this year" → \`yearToDate\`+- For ANYTHING that doesn't match a preset above, you MUST use \`startDate\` + \`endDate\` (YYYY-MM-DD) computed relative to today (see the date at the bottom of this prompt) — do NOT invent new preset names. Examples:+ - "last week" (Mon-Sun of previous calendar week) → compute the dates manually as a custom range+ - "the past 14 days" → startDate = today − 14 days, endDate = today+ - "May 24-28" → startDate = current-year-05-24, endDate = current-year-05-28+ - "Q1 2026" → startDate = 2026-01-01, endDate = 2026-03-31+- When you set \`startDate\` + \`endDate\`, omit \`range\` (it's set to \`custom\` automatically by the handler).++For \`set_property_filters\` and \`set_event_names_filter\`:+- These REPLACE the current filter set — to ADD to existing filters, include the current ones too (read them from \`Current view\` below).+- For referrers: default to the \`referrer_name\` property (matches values like "GitHub", "Hacker News", "Bing", "Direct"). Use \`referrer_type\` only for traffic class (search/social/direct/etc.) and the raw \`referrer\` URL only when the user asks for an exact URL.+- After applying, briefly confirm what changed: "Done — filtered to mobile only." Then optionally answer the underlying question.++# Reasoning approach+- For deep questions, plan a chain of 2-5 tool calls. You have up to 20 steps.+- For comparative questions ("why is X higher than Y?"), gather both sides before answering.+- For "explain this spike/drop" questions, drill into the time interval AND a relevant breakdown (country, device, referrer).+- **Always check references when explaining traffic changes.** The user may have logged a real-world event (campaign launch, deploy, press mention). Use \`get_references_around\` with the spike/drop date before concluding "we don't know why" — a reference often explains it in one sentence.++# Charts and visualizations — IMPORTANT+Users frequently want to SEE data, not just read numbers. Whenever the user says "show me…", "chart of…", "trend of…", "graph / line / visualization", "plot…", "over time", or asks a follow-up like "can I get a trend line for that?" — you MUST call \`generate_report\` (or a specialized chart tool) so the UI renders an actual chart. If the user asks for a chart and you respond with prose only, you failed.++## Chart type decision table+Pick the \`chartType\` that matches the question:++- \`linear\` — trends over time (default for time series). "signups over time", "pageviews per day"+- \`area\` — stacked time series, usually with a breakdown+- \`bar\` — categorical comparisons / top-N. "top pages", "traffic by country"+- \`pie\` — part-of-whole, ≤6 slices only. If >6, use \`bar\` with \`limit\`+- \`metric\` — single KPI number. "total signups this month"+- \`funnel\` — ordered step completion (2+ events). Returns step drop-off+- \`retention\` — cohort retention of a single event. Use \`interval: "week"\`+- \`conversion\` — A→B rate chart (2 events). Shows conversion % series+- \`sankey\` — multi-step user flow (3+ events)+- \`map\` — geographic breakdown. Use \`breakdowns: [{ name: "country" }]\`+- \`histogram\` — distribution of a numeric property (e.g. session duration buckets)++Specialized tools (prefer these when they fit — they're cheaper and already typed):+- DAU / WAU / MAU over time → \`get_rolling_active_users\` with \`windowDays: 1\` / \`7\` / \`30\`+- Funnel → \`get_funnel\` (or \`generate_report\` with \`chartType: "funnel"\`)++## Filter operators — use these EXACT keys+\`generate_report\` filters use an enum; inventing an operator will fail validation:++- \`is\` — equals (DEFAULT for equality — NOT \`equals\` / \`eq\` / \`==\`)+- \`isNot\` — not equal+- \`contains\` / \`doesNotContain\`+- \`startsWith\` / \`endsWith\`+- \`regex\`+- \`isNull\` / \`isNotNull\` (use empty \`value: []\`)+- \`gt\` / \`lt\` / \`gte\` / \`lte\` — numeric comparisons++## Defaults to always emit+- \`metric\` → \`"sum"\` unless user explicitly asks for average/min/max.+- \`interval\` by range: \`hour\` for ≤48h, \`day\` for ≤90d, \`week\` for ≤1y, \`month\` beyond.+- \`lineType\` → \`"monotone"\` on \`linear\`/\`area\` unless the user wants a stepped/straight look.+- "Top X by Y" → \`chartType: "bar"\`, \`breakdowns: [{ name: Y }]\`, \`limit: X\`.+- Always include \`title\` (3-8 words describing what the chart shows).++## Advanced patterns+- **Unique users / sessions**: \`segment: "user"\` or \`"session"\` on the event (NOT default \`"event"\` which counts firings).+- **Sum/avg a numeric property**: \`segment: "property_sum"\` (or \`_average\`/\`_max\`/\`_min\`) + \`property: "revenue"\` (or duration, etc.). Example: \`{ type: "event", name: "purchase", segment: "property_sum", property: "revenue" }\`.+- **Ratios / conversion rate over time**: add a \`formula\` series. Series are lettered A, B, C, … by array index:+ \`\`\`+ series: [+ { type: "event", name: "signup" }, // A+ { type: "event", name: "subscription_started" }, // B+ { type: "formula", formula: "B / A * 100", displayName: "Conversion %", hideSeries: ["A", "B"] }+ ]+ \`\`\`+- **Vs previous period**: top-level \`previous: true\`. Great for "vs last week" / "vs last month".+- **Funnel by session vs profile**: \`chartType: "funnel"\` + \`funnelGroup: "session"\` when the user says "funnel by session".++## Anti-patterns — DO NOT+- DO NOT invent event names. Always call \`list_event_names\` first.+- DO NOT put an unverified property key in filters/breakdowns — call \`list_event_properties\` first.+- DO NOT use \`operator: "equals"\` / \`"eq"\` / \`"=="\` — the only valid equality operator is \`is\`.+- DO NOT combine \`segment: "user"\` with \`property\` — \`property\` only applies to \`property_*\` segments.+- DO NOT use \`chartType: "pie"\` with >10 values — switch to \`bar\` + \`limit: 10\`.+- DO NOT omit \`title\`.++When you call a chart tool, keep prose SHORT — a one-line caption like "Here's the MAU trend over the last 30 days." The chart does the talking.++## Examples++1. **Pageviews per day, last 30 days**+\`{ "chartType": "linear", "interval": "day", "startDate": "...", "endDate": "...", "lineType": "monotone", "series": [{ "type": "event", "name": "screen_view" }], "title": "Pageviews per day" }\`++2. **Top 10 pages**+\`{ "chartType": "bar", "interval": "day", "startDate": "...", "endDate": "...", "series": [{ "type": "event", "name": "screen_view" }], "breakdowns": [{ "name": "path" }], "limit": 10, "title": "Top 10 pages" }\`++3. **Unique visitors by country (map)**+\`{ "chartType": "map", "interval": "day", "startDate": "...", "endDate": "...", "series": [{ "type": "event", "name": "screen_view", "segment": "user" }], "breakdowns": [{ "name": "country" }], "title": "Unique visitors by country" }\`++4. **Signup → subscription conversion rate over time**+\`{ "chartType": "linear", "interval": "day", "startDate": "...", "endDate": "...", "series": [{ "type": "event", "name": "signup" }, { "type": "event", "name": "subscription_started" }, { "type": "formula", "formula": "B / A * 100", "displayName": "Conversion %", "hideSeries": ["A","B"] }], "unit": "%", "title": "Signup → subscription rate" }\`++5. **Revenue per day**+\`{ "chartType": "linear", "interval": "day", "startDate": "...", "endDate": "...", "series": [{ "type": "event", "name": "purchase", "segment": "property_sum", "property": "revenue" }], "unit": "$", "title": "Revenue per day" }\`++6. **Signup → activation → purchase funnel**+\`{ "chartType": "funnel", "interval": "day", "startDate": "...", "endDate": "...", "series": [{ "type": "event", "name": "signup" }, { "type": "event", "name": "activated" }, { "type": "event", "name": "purchase" }], "title": "Signup to purchase funnel" }\`++7. **Weekly retention for signup**+\`{ "chartType": "retention", "interval": "week", "startDate": "...", "endDate": "...", "series": [{ "type": "event", "name": "signup" }], "title": "Weekly signup retention" }\`++8. **MRR vs last month**+\`{ "chartType": "linear", "interval": "day", "startDate": "...", "endDate": "...", "previous": true, "series": [{ "type": "event", "name": "subscription_charge", "segment": "property_sum", "property": "amount" }], "unit": "$", "title": "MRR vs last month" }\``;+}++/**+ * Build the system prompt for an agent run, layering page context onto+ * the base behavioral rules. Called by the agent factory's `instruction`+ * function.+ */+export function buildSystemPrompt(context: ChatAgentContext): string {+ return [buildBasePrompt(), buildPageContextSection(context.pageContext)]+ .filter(Boolean)+ .join('\n\n');+}++function buildPageContextSection(pc?: PageContext): string {+ // The date varies every day, so we keep it out of the cached prefix+ // and render it at the bottom of the prompt together with the rest+ // of the per-request context. UTC is fine — analytics queries bucket+ // by day boundaries, not user timezone.+ const today = new Date();+ const todayIso = today.toISOString().slice(0, 10);+ const dayName = today.toLocaleDateString('en-US', {+ weekday: 'long',+ timeZone: 'UTC',+ });++ const lines: string[] = [+ '# Current view',+ `Today is **${dayName}, ${todayIso}** (UTC).`,+ ];++ if (!pc) return lines.join('\n');++ lines.push(`The user is on the **${pc.page}** page.`);++ if (pc.filters?.range) {+ const range = pc.filters.range;+ const dates =+ pc.filters.startDate && pc.filters.endDate+ ? ` (${pc.filters.startDate} to ${pc.filters.endDate})`+ : '';+ const interval = pc.filters.interval ?? 'day';+ lines.push(`Date range: ${range}${dates}, interval: ${interval}.`);+ }++ if (pc.filters?.eventNames && pc.filters.eventNames.length > 0) {+ lines.push(+ `Active event-name filter: ${JSON.stringify(pc.filters.eventNames)}`,+ );+ }++ if (pc.filters?.eventFilters && pc.filters.eventFilters.length > 0) {+ lines.push(+ `Active property filters: ${JSON.stringify(pc.filters.eventFilters)}`,+ );+ }++ if (pc.ids?.profileId) {+ lines.push(+ `They are viewing profile \`${pc.ids.profileId}\`. Profile-specific tools below are pre-bound to this profile by default.`,+ );+ }+ if (pc.ids?.sessionId) {+ lines.push(+ `They are viewing session \`${pc.ids.sessionId}\`. Session-specific tools are pre-bound to this session.`,+ );+ }+ if (pc.ids?.groupId) {+ lines.push(+ `They are viewing group \`${pc.ids.groupId}\`. Group-specific tools are pre-bound to this group.`,+ );+ }+ if (pc.ids?.reportId) {+ lines.push(`They are viewing report \`${pc.ids.reportId}\`.`);+ }++ if (pc.reportDraft) {+ lines.push(+ `They are editing this report draft:\n\`\`\`json\n${JSON.stringify(pc.reportDraft, null, 2)}\n\`\`\`\nUse preview_report_with_changes to propose edits to it.`,+ );+ }++ if (pc.primer) {+ lines.push(+ `Quick context (no tool call needed): ${JSON.stringify(pc.primer)}`,+ );+ }++ return lines.join('\n');+}diff --git a/apps/api/src/agents/run-context.ts b/apps/api/src/agents/run-context.tsnew file mode 100644index 000000000..1f8cb4687--- /dev/null+++ b/apps/api/src/agents/run-context.ts@@ -0,0 +1,19 @@+import { AsyncLocalStorage } from 'node:async_hooks';++/**+ * Per-request context for chat runs. Populated by the Fastify route+ * wrapper (which validates the session + project access) before the+ * Better Agent handler runs, and read by the persistence store to+ * upsert the `Conversation` row with the right owner on first save.+ *+ * Using AsyncLocalStorage means we don't have to thread these values+ * through Better Agent's plugin hooks — which don't expose the agent+ * `context` field to `onBeforeSave`.+ */+export type ChatRunContext = {+ userId: string;+ projectId: string;+ organizationId: string;+};++export const chatRunContext = new AsyncLocalStorage<ChatRunContext>();diff --git a/apps/api/src/agents/tools/base.ts b/apps/api/src/agents/tools/base.tsnew file mode 100644index 000000000..7325e8c61--- /dev/null+++ b/apps/api/src/agents/tools/base.ts@@ -0,0 +1,863 @@+import {+ chartTypes,+ lineTypes,+ operators,+} from '@openpanel/constants';+import { objectToZodEnums, zReportInput } from '@openpanel/validation';+import { z } from 'zod';+import {+ findProfilesCore,+ getAnalyticsOverviewCore,+ getEventPropertyValuesCore,+ getFunnelCore,+ getRetentionCohortCore,+ getRollingActiveUsersCore,+ getTopPagesCore,+ getTrafficBreakdownCore,+ getUserFlowCore,+ listDashboardsCore,+ listEventNamesCore,+ listEventPropertiesCore,+ listReportsCore,+ queryEventsCore,+ querySessionsCore,+} from '@openpanel/db';+import { runReport, runReportFromConfig } from '@openpanel/mcp';+import {+ chatTool,+ dashboardUrl,+ pageContextFilters,+ resolveDateRange,+ truncateRows,+} from './helpers';++// ─────────────────────────────────────────────────────────────────+// DISCOVERY+// ─────────────────────────────────────────────────────────────────++export const listEventNames = chatTool(+ {+ name: 'list_event_names',+ description:+ 'Get the top 50 event names tracked in this project. Call this BEFORE referencing event names in generate_report or other tools — never guess at event names.',+ schema: z.object({}),+ },+ async (_input, context) => {+ const names = await listEventNamesCore(context.projectId);+ return { event_names: names };+ },+);++export const listEventProperties = chatTool(+ {+ name: 'list_event_properties',+ description:+ 'List the property keys available for an event (or all events). Call this before using a property as a filter or breakdown in generate_report.',+ schema: z.object({+ eventName: z+ .string()+ .optional()+ .describe('Optional — filter to one event. Omit to list properties across all events.'),+ }),+ },+ async ({ eventName }, context) =>+ listEventPropertiesCore({ projectId: context.projectId, eventName }),+);++export const getEventPropertyValues = chatTool(+ {+ name: 'get_event_property_values',+ description:+ 'List distinct values for a specific event property. Useful when the user wants to filter on something concrete like "country = SE".',+ schema: z.object({+ eventName: z.string().describe('The event name (e.g. screen_view)'),+ propertyKey: z.string().describe('The property key (e.g. path, country)'),+ }),+ },+ async ({ eventName, propertyKey }, context) =>+ getEventPropertyValuesCore({+ projectId: context.projectId,+ eventName,+ propertyKey,+ }),+);++// ─────────────────────────────────────────────────────────────────+// SAVED DASHBOARDS & REPORTS (PREFER THESE OVER generate_report)+// ─────────────────────────────────────────────────────────────────++export const listDashboards = chatTool(+ {+ name: 'list_dashboards',+ description:+ 'List all dashboards in this project. Each dashboard groups a set of reports the user has built. Use this to discover what already exists before building anything new.',+ schema: z.object({}),+ },+ async (_input, context) => {+ const dashboards = await listDashboardsCore({+ projectId: context.projectId,+ organizationId: context.organizationId,+ });+ return dashboards.map((d) => ({+ ...d,+ dashboard_url: dashboardUrl(context.organizationId, context.projectId, `/dashboards/${d.id}`),+ }));+ },+);++export const listReports = chatTool(+ {+ name: 'list_reports',+ description:+ 'List the reports inside a dashboard. Returns chart type, range, interval, and event series for each. Use this with get_report_data to fetch real numbers.',+ schema: z.object({+ dashboardId: z.string().describe('The dashboard ID (from list_dashboards)'),+ }),+ },+ async ({ dashboardId }, context) =>+ listReportsCore({+ projectId: context.projectId,+ dashboardId,+ organizationId: context.organizationId,+ }),+);++export const getReportData = chatTool(+ {+ name: 'get_report_data',+ description:+ 'Execute a saved report by ID and return its data. Works for every chart type (linear, bar, area, pie, metric, funnel, retention, etc.). PREFER this over generate_report when the user asks about something a saved report likely already covers.',+ schema: z.object({+ reportId: z.string().describe('The report ID (from list_reports)'),+ }),+ },+ async ({ reportId }, context) =>+ runReport({+ organizationId: context.organizationId,+ projectId: context.projectId,+ reportId,+ }),+);++export const generateReport = chatTool(+ {+ name: 'generate_report',+ description: [+ "Generate an ad-hoc chart from a report config. Use only when no saved report fits. Always call list_event_names first to verify event names exist; call list_event_properties if you need a breakdown property. ALWAYS supply a concise `title` (3-8 words) describing what the chart shows.",+ '',+ 'Series are ordered A, B, C, … (based on array index). Use the letter id from a `formula` series like "A / B * 100" for ratios or conversions.',+ '',+ 'Examples:',+ '- **Unique users per day**: one event series with `segment: "user"` + `chartType: "linear"`.',+ '- **Revenue per day**: one event series with `segment: "property_sum"` + `property: "revenue"`.',+ '- **Conversion rate over time**: two event series (A = completed, B = started) + a `formula` series `"A / B * 100"` with all three visible, or set `hideSeries: ["A","B"]` to show only the rate.',+ '- **Period-over-period**: set `previous: true` to overlay the prior period of equal length.',+ ].join('\n'),+ schema: z.object({+ chartType: z+ .enum(objectToZodEnums(chartTypes))+ .describe(+ 'Chart type. See the decision table in the system prompt — pick `linear`/`area` for trends, `bar`/`pie`/`map` for breakdowns, `metric` for a single number, `funnel`/`conversion`/`sankey` for flows, `retention` for cohorts, `histogram` for numeric distributions.',+ ),+ interval: z+ .enum(['minute', 'hour', 'day', 'week', 'month'])+ .default('day'),+ startDate: z.string().describe('ISO date YYYY-MM-DD'),+ endDate: z.string().describe('ISO date YYYY-MM-DD'),+ series: z+ .array(+ z.union([+ z.object({+ type: z.literal('event'),+ name: z.string().describe('Event name — verify with list_event_names'),+ displayName: z.string().optional(),+ segment: z+ .enum([+ 'event',+ 'user',+ 'session',+ 'group',+ 'user_average',+ 'one_event_per_user',+ 'property_sum',+ 'property_average',+ 'property_max',+ 'property_min',+ ])+ .default('event')+ .optional()+ .describe(+ [+ 'How to segment/aggregate the event:',+ '- `event` — every event firing (default, "all events")',+ '- `user` — unique users (e.g. for DAU/MAU)',+ '- `session` — unique sessions',+ '- `group` — unique groups/accounts',+ '- `user_average` — average events per user',+ '- `one_event_per_user` — count users who did it at least once',+ '- `property_sum` / `property_average` / `property_max` / `property_min` — aggregate a numeric property from the event (requires `property`)',+ ].join('\n'),+ ),+ property: z+ .string()+ .optional()+ .describe(+ 'Numeric property on the event to aggregate. Required when segment is `property_sum`/`average`/`max`/`min`. Example: `revenue`, `duration`, `score`.',+ ),+ filters: z+ .array(+ z.object({+ name: z+ .string()+ .describe('Property key — verify with list_event_properties'),+ operator: z+ .enum(objectToZodEnums(operators))+ .describe(+ 'One of: is, isNot, contains, doesNotContain, startsWith, endsWith, regex, isNull, isNotNull, gt, lt, gte, lte. `is` is the default for equality (NOT `equals` / `eq` / `==`).',+ ),+ value: z+ .array(z.union([z.string(), z.number(), z.boolean(), z.null()]))+ .describe('Values to match. Use [] with isNull/isNotNull.'),+ }),+ )+ .default([])+ .optional(),+ }),+ z.object({+ type: z.literal('formula'),+ formula: z+ .string()+ .describe(+ 'Expression referencing other series by letter id. Examples: `A / B * 100` (conversion rate), `A + B` (union total), `A - B` (difference). Earlier series are A, B, C, …',+ ),+ displayName: z.string().optional(),+ hideSeries: z+ .array(z.string())+ .optional()+ .describe(+ 'Letter ids (e.g. ["A", "B"]) of series used by the formula that should be hidden from the chart — useful when you only want to display the computed ratio.',+ ),+ }),+ ]),+ )+ .min(1)+ .describe('At least one series. Mix event series and formula series to compute ratios.'),+ breakdowns: z+ .array(+ z.object({+ name: z.string().describe('Property key to group by'),+ }),+ )+ .default([])+ .optional(),+ metric: z.enum(['sum', 'count', 'average']).default('sum').optional(),+ previous: z+ .boolean()+ .optional()+ .describe(+ 'Overlay the same-length previous period for comparison. Great for "vs last week" / "vs last month" questions.',+ ),+ lineType: z+ .enum(objectToZodEnums(lineTypes))+ .optional()+ .describe(+ 'Line style for linear/area charts. Default to `monotone` unless you have a reason not to.',+ ),+ limit: z+ .number()+ .min(1)+ .max(500)+ .optional()+ .describe('Top-N limit for bar/pie/sankey. Example: "top 10 pages" → limit: 10.'),+ unit: z+ .string()+ .optional()+ .describe('Y-axis unit suffix, e.g. `%`, `$`, `ms`, `users`.'),+ funnelGroup: z+ .enum(['session', 'profile'])+ .optional()+ .describe(+ 'Only for `chartType: "funnel"`. Whether each funnel step counts by unique session or unique profile. Default is profile.',+ ),+ title: z+ .string()+ .optional()+ .describe(+ 'Short, descriptive card title (3-8 words) — e.g. "Signups per day, last 7 days". Always provide one.',+ ),+ }),+ },+ async (input, context) => {+ // biome-ignore lint/suspicious/noExplicitAny: union discrimination between event/formula series is easier to do explicitly+ const series = (input.series as any[]).map((s: any, i: number) => {+ const id = ALPHABET_IDS[i] ?? String(i + 1);+ if (s?.type === 'formula') {+ return {+ id,+ type: 'formula' as const,+ formula: s.formula,+ displayName: s.displayName,+ ...(Array.isArray(s.hideSeries) ? { hideSeries: s.hideSeries } : {}),+ };+ }+ return {+ id,+ type: 'event' as const,+ name: s.name,+ displayName: s.displayName ?? s.name,+ segment: s.segment ?? 'event',+ ...(s.property ? { property: s.property } : {}),+ filters: s.filters ?? [],+ };+ });++ const options =+ input.chartType === 'funnel' && input.funnelGroup+ ? { type: 'funnel' as const, funnelGroup: input.funnelGroup }+ : undefined;++ const config = {+ projectId: context.projectId,+ chartType: input.chartType,+ interval: input.interval,+ startDate: input.startDate,+ endDate: input.endDate,+ series,+ breakdowns: (input.breakdowns ?? []).map(+ (b: { name: string }, i: number) => ({+ id: String(i + 1),+ name: b.name,+ }),+ ),+ range: 'custom' as const,+ metric: input.metric ?? 'sum',+ previous: input.previous ?? false,+ ...(input.lineType ? { lineType: input.lineType } : {}),+ ...(input.limit ? { limit: input.limit } : {}),+ ...(input.unit ? { unit: input.unit } : {}),+ ...(options ? { options } : {}),+ };++ // Pre-validate against the real report schema so invalid shapes+ // (bad operator, wrong filter value type, unknown chartType) are+ // returned to the model as a structured error, letting the agent+ // loop self-correct instead of producing a broken chart.+ const parsed = zReportInput.safeParse(config);+ if (!parsed.success) {+ return {+ error: 'Invalid report config — fix the issues and call generate_report again.',+ issues: parsed.error.issues.map((i) => ({+ path: i.path.join('.'),+ message: i.message,+ })),+ };+ }++ const chart = await runReportFromConfig({+ organizationId: context.organizationId,+ projectId: context.projectId,+ config: parsed.data as Parameters<typeof runReportFromConfig>[0]['config'],+ });+ return {+ // Use the model-supplied title when present; the frontend+ // falls back to a derived title from input if this is empty.+ ...(input.title?.trim() ? { name: input.title.trim() } : {}),+ ...chart,+ };+ },+);++// Letter ids for series. Must match the chart engine's expectation+// that series are referenced by A, B, C, … in formula expressions.+const ALPHABET_IDS = [+ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',+ 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',+ 'U', 'V', 'W', 'X', 'Y', 'Z',+] as const;++// ─────────────────────────────────────────────────────────────────+// AGGREGATE ANALYTICS — default to current page's filters+// ─────────────────────────────────────────────────────────────────++export const getAnalyticsOverview = chatTool(+ {+ name: 'get_analytics_overview',+ description:+ 'Top-level metrics: unique visitors, total pageviews, sessions, bounce rate, avg session duration, plus an optional time series. Defaults to the user\'s current date range.',+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ interval: z.enum(['hour', 'day', 'week', 'month']).default('day').optional(),+ }),+ },+ async ({ startDate, endDate, interval }, context) => {+ const pageContext = context.pageContext;+ const range = resolveDateRange({+ ...pageContext?.filters,+ startDate: startDate ?? pageContext?.filters?.startDate,+ endDate: endDate ?? pageContext?.filters?.endDate,+ });+ return getAnalyticsOverviewCore({+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ interval: interval ?? 'day',+ filters: pageContextFilters(pageContext),+ });+ },+);++export const getTopPages = chatTool(+ {+ name: 'get_top_pages',+ description:+ 'Top pages ranked by visitors / pageviews. Returns path, sessions, pageviews, bounce rate, avg duration. Respects the page\'s active property filters.',+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ limit: z.number().min(1).max(100).default(20).optional(),+ }),+ },+ async ({ startDate, endDate, limit }, context) => {+ const pageContext = context.pageContext;+ const range = resolveDateRange({+ ...pageContext?.filters,+ startDate: startDate ?? pageContext?.filters?.startDate,+ endDate: endDate ?? pageContext?.filters?.endDate,+ });+ const pages = await getTopPagesCore({+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ limit: limit ?? 20,+ filters: pageContextFilters(pageContext),+ });+ return truncateRows(pages, 50);+ },+);++export const getTopReferrers = chatTool(+ {+ name: 'get_top_referrers',+ description:+ 'Traffic source breakdown — by referrer name, type, or UTM source/medium/campaign. Respects the page\'s active property filters.',+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ breakdown: z+ .enum(['referrer_name', 'referrer_type', 'referrer'])+ .default('referrer_name')+ .optional(),+ }),+ },+ async ({ startDate, endDate, breakdown }, context) => {+ const pageContext = context.pageContext;+ const range = resolveDateRange({+ ...pageContext?.filters,+ startDate: startDate ?? pageContext?.filters?.startDate,+ endDate: endDate ?? pageContext?.filters?.endDate,+ });+ const rows = await getTrafficBreakdownCore({+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ column: (breakdown ?? 'referrer_name') as 'referrer_name' | 'referrer_type' | 'referrer',+ filters: pageContextFilters(pageContext),+ });+ return truncateRows(rows, 50);+ },+);++export const getCountryBreakdown = chatTool(+ {+ name: 'get_country_breakdown',+ description:+ 'Visitor breakdown by country / region / city. Returns sessions and percentage of total. Respects the page\'s active property filters.',+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ breakdown: z+ .enum(['country', 'region', 'city'])+ .default('country')+ .optional(),+ }),+ },+ async ({ startDate, endDate, breakdown }, context) => {+ const pageContext = context.pageContext;+ const range = resolveDateRange({+ ...pageContext?.filters,+ startDate: startDate ?? pageContext?.filters?.startDate,+ endDate: endDate ?? pageContext?.filters?.endDate,+ });+ const rows = await getTrafficBreakdownCore({+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ column: (breakdown ?? 'country') as 'country' | 'region' | 'city',+ filters: pageContextFilters(pageContext),+ });+ return truncateRows(rows, 100);+ },+);++export const getDeviceBreakdown = chatTool(+ {+ name: 'get_device_breakdown',+ description:+ 'Visitor breakdown by device / browser / OS. Respects the page\'s active property filters.',+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ breakdown: z+ .enum(['device', 'browser', 'os'])+ .default('device')+ .optional(),+ }),+ },+ async ({ startDate, endDate, breakdown }, context) => {+ const pageContext = context.pageContext;+ const range = resolveDateRange({+ ...pageContext?.filters,+ startDate: startDate ?? pageContext?.filters?.startDate,+ endDate: endDate ?? pageContext?.filters?.endDate,+ });+ const rows = await getTrafficBreakdownCore({+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ column: (breakdown ?? 'device') as 'device' | 'browser' | 'os',+ filters: pageContextFilters(pageContext),+ });+ return truncateRows(rows, 50);+ },+);++export const getRollingActiveUsers = chatTool(+ {+ name: 'get_rolling_active_users',+ description:+ "Rolling active-users trend (DAU/WAU/MAU). Returns BOTH the latest single value AND a renderable chart config (so the UI draws a line chart). Default is DAU over 30 days; pass `windowDays: 7` for WAU or `windowDays: 30` for MAU. ALWAYS supply a concise `title` (3-8 words) that describes what the chart shows.",+ schema: z.object({+ /**+ * The rolling window. 1 = DAU (default), 7 = WAU, 30 = MAU.+ */+ windowDays: z.number().min(1).max(90).default(1).optional(),+ /** Number of days to chart. Defaults to 30. */+ days: z.number().min(1).max(365).default(30).optional(),+ title: z+ .string()+ .optional()+ .describe(+ 'Short, descriptive card title (3-8 words) — e.g. "Monthly active users trend". Always provide one.',+ ),+ }),+ },+ async ({ windowDays, days, title }, context) => {+ const window = windowDays ?? 1;+ const range = days ?? 30;++ // Build a chart config that represents "unique users per day".+ // We use a user-segment on `screen_view` — OpenPanel's standard+ // pageview event — with a linear chart. The ChartEngine dedupes+ // per profile_id because of `segment: 'user'`.+ const endDate = new Date().toISOString().slice(0, 10);+ const startDate = new Date(Date.now() - (range - 1) * 86_400_000)+ .toISOString()+ .slice(0, 10);+ const label =+ window === 1 ? 'DAU' : window === 7 ? 'WAU' : window === 30 ? 'MAU' : `${window}-day active users`;++ const config = {+ chartType: 'linear' as const,+ interval: 'day' as const,+ startDate,+ endDate,+ range: 'custom' as const,+ metric: 'sum' as const,+ previous: false,+ breakdowns: [],+ series: [+ {+ id: '1',+ type: 'event' as const,+ name: 'screen_view',+ displayName: label,+ segment: 'user' as const,+ filters: [],+ },+ ],+ };++ const chart = await runReportFromConfig({+ organizationId: context.organizationId,+ projectId: context.projectId,+ config: config as Parameters<typeof runReportFromConfig>[0]['config'],+ });++ // Also keep the rolling summary so the model can quote the+ // single-number "MAU is 205,127" line.+ const summary = await getRollingActiveUsersCore({+ projectId: context.projectId,+ days: window,+ });++ return {+ // `name` is the title the frontend `ChatReportResult` uses for+ // the card header. The model is asked to supply a `title` —+ // we use it when present, falling back to a generic label.+ name: title?.trim() || `${label} — last ${range} days`,+ label,+ window,+ summary,+ // Keys the frontend report renderer knows about.+ ...chart,+ };+ },+);++export const getFunnel = chatTool(+ {+ name: 'get_funnel',+ description:+ 'Multi-step conversion funnel. Returns BOTH a renderable funnel chart AND the numeric breakdown (users per step, conversion rates, drop-off). The UI draws an actual funnel chart. Provide an ordered list of event names — verify with list_event_names first. ALWAYS supply a concise `title` (3-8 words) describing what the funnel measures.',+ schema: z.object({+ steps: z+ .array(z.string())+ .min(2)+ .max(10)+ .describe('Ordered event names. Verify with list_event_names first.'),+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ windowHours: z.number().min(1).max(720).default(24).optional(),+ groupBy: z+ .enum(['session_id', 'profile_id'])+ .default('session_id')+ .optional(),+ title: z+ .string()+ .optional()+ .describe(+ 'Short, descriptive card title (3-8 words) — e.g. "Cart to checkout conversion" or "Signup to paid funnel". Always provide one.',+ ),+ }),+ },+ async ({ steps, startDate, endDate, windowHours, groupBy, title }, context) => {+ const pageContext = context.pageContext;+ const range = resolveDateRange({+ ...pageContext?.filters,+ startDate: startDate ?? pageContext?.filters?.startDate,+ endDate: endDate ?? pageContext?.filters?.endDate,+ });++ // Raw funnel numbers — step-by-step breakdown for the model to+ // reason about.+ const numbers = await getFunnelCore({+ projectId: context.projectId,+ steps,+ startDate: range.startDate,+ endDate: range.endDate,+ windowHours,+ groupBy,+ });++ // Chart config — same shape `generate_report` returns, so the+ // frontend's `ChatReportResult` renderer draws an actual funnel+ // chart via `<ReportChart>`.+ const chartConfig = {+ chartType: 'funnel' as const,+ interval: 'day' as const,+ startDate: range.startDate,+ endDate: range.endDate,+ range: 'custom' as const,+ metric: 'sum' as const,+ previous: false,+ breakdowns: [],+ funnelGroup: groupBy ?? 'session_id',+ funnelWindowSeconds: (windowHours ?? 24) * 3600,+ series: (steps as string[]).map((name: string, i: number) => ({+ id: String(i + 1),+ type: 'event' as const,+ name,+ displayName: name,+ segment: 'event' as const,+ filters: [],+ })),+ };++ const chart = await runReportFromConfig({+ organizationId: context.organizationId,+ projectId: context.projectId,+ config: chartConfig as Parameters<typeof runReportFromConfig>[0]['config'],+ });++ return {+ name: title?.trim() || `Funnel: ${steps.join(' → ')}`,+ numbers,+ // Keys the frontend report renderer knows about.+ ...chart,+ };+ },+);++export const getRetentionCohort = chatTool(+ {+ name: 'get_retention_cohort',+ description:+ 'Weekly user retention cohort table. Each row is a cohort week, columns are retention percentages for subsequent weeks.',+ schema: z.object({}),+ },+ async (_input, context) => getRetentionCohortCore(context.projectId),+);++export const getUserFlow = chatTool(+ {+ name: 'get_user_flow',+ description:+ 'Sankey-style user navigation flow from a starting event. Returns nodes + links suitable for visualizing common paths.',+ schema: z.object({+ startEvent: z.string().describe('Event name where the flow starts'),+ endEvent: z+ .string()+ .optional()+ .describe('Required when mode=between'),+ mode: z.enum(['after', 'before', 'between']).default('after'),+ steps: z.number().min(2).max(10).default(5).optional(),+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ }),+ },+ async ({ startEvent, endEvent, mode, steps, startDate, endDate }, context) => {+ const pageContext = context.pageContext;+ const range = resolveDateRange({+ ...pageContext?.filters,+ startDate: startDate ?? pageContext?.filters?.startDate,+ endDate: endDate ?? pageContext?.filters?.endDate,+ });+ return getUserFlowCore({+ projectId: context.projectId,+ startEvent,+ endEvent,+ mode,+ steps,+ startDate: range.startDate,+ endDate: range.endDate,+ });+ },+);++// ─────────────────────────────────────────────────────────────────+// FREE-FORM QUERIES (escape hatches when nothing else fits)+// ─────────────────────────────────────────────────────────────────++export const queryEvents = chatTool(+ {+ name: 'query_events',+ description:+ 'Free-form query over raw events with filters (path, country, device, browser, OS, referrer, custom properties, profileId, eventNames). Use this when aggregate tools don\'t cover the question.',+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ eventNames: z.array(z.string()).optional(),+ path: z.string().optional(),+ country: z.string().optional(),+ city: z.string().optional(),+ device: z.string().optional(),+ browser: z.string().optional(),+ os: z.string().optional(),+ referrer: z.string().optional(),+ referrerName: z.string().optional(),+ referrerType: z.string().optional(),+ profileId: z.string().optional(),+ properties: z.record(z.string(), z.string()).optional(),+ limit: z.number().min(1).max(100).default(20).optional(),+ }),+ },+ async (input, context) => {+ const pageContext = context.pageContext;+ const range = resolveDateRange({+ ...pageContext?.filters,+ startDate: input.startDate ?? pageContext?.filters?.startDate,+ endDate: input.endDate ?? pageContext?.filters?.endDate,+ });+ const rows = await queryEventsCore({+ projectId: context.projectId,+ ...input,+ startDate: range.startDate,+ endDate: range.endDate,+ limit: input.limit ?? 20,+ });+ return truncateRows(rows, 100);+ },+);++export const querySessions = chatTool(+ {+ name: 'query_sessions',+ description:+ 'Free-form query over raw sessions with filters (country, device, browser, OS, referrer, profileId).',+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ country: z.string().optional(),+ city: z.string().optional(),+ device: z.string().optional(),+ browser: z.string().optional(),+ os: z.string().optional(),+ referrer: z.string().optional(),+ referrerName: z.string().optional(),+ referrerType: z.string().optional(),+ profileId: z.string().optional(),+ limit: z.number().min(1).max(100).default(20).optional(),+ }),+ },+ async (input, context) => {+ const pageContext = context.pageContext;+ const range = resolveDateRange({+ ...pageContext?.filters,+ startDate: input.startDate ?? pageContext?.filters?.startDate,+ endDate: input.endDate ?? pageContext?.filters?.endDate,+ });+ const rows = await querySessionsCore({+ projectId: context.projectId,+ ...input,+ startDate: range.startDate,+ endDate: range.endDate,+ limit: input.limit ?? 20,+ });+ return truncateRows(rows, 100);+ },+);++export const findProfiles = chatTool(+ {+ name: 'find_profiles',+ description:+ 'Search for user profiles by name, email, country, device, inactivity, minimum sessions, or having performed a specific event.',+ schema: z.object({+ name: z.string().optional(),+ email: z.string().optional(),+ country: z.string().optional(),+ city: z.string().optional(),+ device: z.string().optional(),+ browser: z.string().optional(),+ inactiveDays: z.number().min(1).optional(),+ minSessions: z.number().min(1).optional(),+ performedEvent: z.string().optional(),+ sortOrder: z.enum(['asc', 'desc']).default('desc').optional(),+ limit: z.number().min(1).max(100).default(20).optional(),+ }),+ },+ async (input, context) => {+ const profiles = await findProfilesCore({+ projectId: context.projectId,+ ...input,+ });+ return truncateRows(+ profiles.map((p) => ({+ ...p,+ dashboard_url: dashboardUrl(context.organizationId, context.projectId, `/profiles/${p.id}`),+ })),+ 100,+ );+ },+);diff --git a/apps/api/src/agents/tools/events.ts b/apps/api/src/agents/tools/events.tsnew file mode 100644index 000000000..797be9ce4--- /dev/null+++ b/apps/api/src/agents/tools/events.ts@@ -0,0 +1,146 @@+import { z } from 'zod';+import {+ getEventPropertyValuesCore,+ listEventPropertiesCore,+ queryEventsCore,+} from '@openpanel/db';+import { chatTool, resolveDateRange, truncateRows } from './helpers';++export const analyzeEventDistribution = chatTool(+ {+ name: 'analyze_event_distribution',+ description:+ 'For a set of events (or all events in the current view), break down their frequency, top properties, and top sources. Useful for "which events fire the most?" questions.',+ schema: z.object({+ eventNames: z.array(z.string()).optional(),+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ }),+ },+ async ({ eventNames, startDate, endDate }, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: startDate ?? context.pageContext?.filters?.startDate,+ endDate: endDate ?? context.pageContext?.filters?.endDate,+ });++ const events = await queryEventsCore({+ projectId: context.projectId,+ eventNames,+ startDate: range.startDate,+ endDate: range.endDate,+ limit: 100,+ });++ // Tally frequency by event name+ const frequency = new Map<string, number>();+ const byCountry = new Map<string, number>();+ const byDevice = new Map<string, number>();+ for (const e of events) {+ frequency.set(e.name, (frequency.get(e.name) ?? 0) + 1);+ if (e.country) byCountry.set(e.country, (byCountry.get(e.country) ?? 0) + 1);+ if (e.device) byDevice.set(e.device, (byDevice.get(e.device) ?? 0) + 1);+ }++ const top = (m: Map<string, number>, n: number) =>+ Array.from(m.entries())+ .sort((a, b) => b[1] - a[1])+ .slice(0, n)+ .map(([name, count]) => ({ name, count }));++ return {+ sample_size: events.length,+ event_frequency: top(frequency, 20),+ top_countries: top(byCountry, 10),+ top_devices: top(byDevice, 10),+ };+ },+);++export const correlateEvents = chatTool(+ {+ name: 'correlate_events',+ description:+ 'Find pairs of events that frequently occur in the same session. Returns event pairs ranked by co-occurrence count.',+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ }),+ },+ async ({ startDate, endDate }, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: startDate ?? context.pageContext?.filters?.startDate,+ endDate: endDate ?? context.pageContext?.filters?.endDate,+ });++ const events = await queryEventsCore({+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ limit: 100,+ });++ // Group events by sessionId, then count co-occurring event-name pairs+ const bySession = new Map<string, Set<string>>();+ for (const e of events) {+ if (!e.session_id) continue;+ if (!bySession.has(e.session_id)) bySession.set(e.session_id, new Set());+ bySession.get(e.session_id)?.add(e.name);+ }++ const pairCounts = new Map<string, number>();+ for (const eventNames of bySession.values()) {+ const list = Array.from(eventNames).sort();+ for (let i = 0; i < list.length; i++) {+ for (let j = i + 1; j < list.length; j++) {+ const key = `${list[i]} + ${list[j]}`;+ pairCounts.set(key, (pairCounts.get(key) ?? 0) + 1);+ }+ }+ }++ const pairs = Array.from(pairCounts.entries())+ .sort((a, b) => b[1] - a[1])+ .slice(0, 30)+ .map(([pair, count]) => ({ pair, count }));++ return {+ sample_sessions: bySession.size,+ top_pairs: pairs,+ };+ },+);++export const getEventPropertyDistribution = chatTool(+ {+ name: 'get_event_property_distribution',+ description:+ 'Distribution of distinct values for a specific property on a specific event. Use to answer "what countries fire screen_view most?" type questions.',+ schema: z.object({+ eventName: z.string(),+ propertyKey: z.string(),+ }),+ },+ async ({ eventName, propertyKey }, context) => {+ const result = await getEventPropertyValuesCore({+ projectId: context.projectId,+ eventName,+ propertyKey,+ });+ return truncateRows(result.values, 100);+ },+);++export const listPropertiesForEvent = chatTool(+ {+ name: 'list_properties_for_event',+ description:+ 'List property keys available for a specific event (or all events). Useful before correlating or filtering.',+ schema: z.object({+ eventName: z.string().optional(),+ }),+ },+ async ({ eventName }, context) =>+ listEventPropertiesCore({ projectId: context.projectId, eventName }),+);diff --git a/apps/api/src/agents/tools/groups.ts b/apps/api/src/agents/tools/groups.tsnew file mode 100644index 000000000..2117428ab--- /dev/null+++ b/apps/api/src/agents/tools/groups.ts@@ -0,0 +1,223 @@+import { z } from 'zod';+import {+ findGroupsCore,+ getGroupCore,+ getGroupMemberProfiles,+ queryEventsCore,+} from '@openpanel/db';+import { chatTool, dashboardUrl, truncateRows } from './helpers';++export const getGroupFull = chatTool(+ {+ name: 'get_group_full',+ description:+ 'One-shot deep dive: group info + member count + first 10 members + recent events from members. CALL THIS FIRST for "tell me about this group".',+ schema: z.object({+ groupId: z.string().optional(),+ }),+ },+ async ({ groupId }, context) => {+ const defaultGroupId = context.pageContext?.ids?.groupId ?? '';+ const id = groupId || defaultGroupId;+ const orgPath = (path = '') =>+ dashboardUrl(context.organizationId, context.projectId, path);++ const group = await getGroupCore({+ projectId: context.projectId,+ groupId: id,+ memberLimit: 10,+ });++ // Pull a few recent events from any members. We use the+ // `profileIds IN (...)` filter on queryEventsCore so the DB does+ // the narrowing instead of us post-filtering a generic feed.+ const memberIds = group.members.map((m) => m.id);+ const recentEvents = memberIds.length+ ? await queryEventsCore({+ projectId: context.projectId,+ profileIds: memberIds,+ limit: 10,+ })+ : [];++ return {+ ...group,+ recent_events: recentEvents,+ dashboard_url: orgPath(`/groups/${id}`),+ };+ },+);++export const getGroupMembers = chatTool(+ {+ name: 'get_group_members',+ description:+ 'Paginated list of profiles in this group.',+ schema: z.object({+ groupId: z.string().optional(),+ limit: z.number().min(1).max(100).default(20).optional(),+ search: z.string().optional(),+ }),+ },+ async ({ groupId, limit, search }, context) => {+ const defaultGroupId = context.pageContext?.ids?.groupId ?? '';+ const id = groupId || defaultGroupId;+ const orgPath = (path = '') =>+ dashboardUrl(context.organizationId, context.projectId, path);++ const result = await getGroupMemberProfiles({+ projectId: context.projectId,+ groupId: id,+ take: limit ?? 20,+ search,+ });+ return {+ group_id: id,+ total_count: result.count,+ members: result.data.map((p) => ({+ ...p,+ dashboard_url: orgPath(`/profiles/${p.id}`),+ })),+ };+ },+);++export const getGroupEvents = chatTool(+ {+ name: 'get_group_events',+ description:+ 'Recent events from members of this group.',+ schema: z.object({+ groupId: z.string().optional(),+ eventNames: z.array(z.string()).optional(),+ limit: z.number().min(1).max(100).default(50).optional(),+ }),+ },+ async ({ groupId, eventNames, limit }, context) => {+ const defaultGroupId = context.pageContext?.ids?.groupId ?? '';+ const id = groupId || defaultGroupId;++ const members = await getGroupMemberProfiles({+ projectId: context.projectId,+ groupId: id,+ take: 100,+ });+ if (members.data.length === 0) {+ return { group_id: id, events: [], note: 'Group has no members' };+ }++ const events = await queryEventsCore({+ projectId: context.projectId,+ profileIds: members.data.map((m) => m.id),+ eventNames,+ limit: limit ?? 50,+ });++ return truncateRows(events, 100);+ },+);++export const getGroupMetrics = chatTool(+ {+ name: 'get_group_metrics',+ description:+ 'Aggregate metrics for this group: total members, members active in the last 7d/30d, total revenue (sum of member.revenue), avg sessions per member.',+ schema: z.object({+ groupId: z.string().optional(),+ }),+ },+ async ({ groupId }, context) => {+ const defaultGroupId = context.pageContext?.ids?.groupId ?? '';+ const id = groupId || defaultGroupId;++ const members = await getGroupMemberProfiles({+ projectId: context.projectId,+ groupId: id,+ take: 1000,+ });++ if (members.data.length === 0) {+ return { group_id: id, total_members: 0, note: 'Group has no members' };+ }++ // Pull events for this group's members over the last 30 days, then+ // bucket by 7d vs 30d. `profileIds IN (...)` lets ClickHouse do the+ // narrowing — a generic project-wide feed would miss members whose+ // activity falls outside the last N raw events.+ const memberIds = members.data.map((m) => m.id);+ const recentEvents = await queryEventsCore({+ projectId: context.projectId,+ profileIds: memberIds,+ startDate: new Date(Date.now() - 30 * 86_400_000)+ .toISOString()+ .slice(0, 10),+ limit: 1000,+ });+ const activeIds7d = new Set<string>();+ const activeIds30d = new Set<string>();+ const sevenDaysAgo = Date.now() - 7 * 86_400_000;+ for (const e of recentEvents) {+ if (!e.profile_id) continue;+ activeIds30d.add(e.profile_id);+ if (new Date(e.created_at).getTime() >= sevenDaysAgo) {+ activeIds7d.add(e.profile_id);+ }+ }++ return {+ group_id: id,+ total_members: members.count,+ active_last_7_days: activeIds7d.size,+ active_last_30_days: activeIds30d.size,+ };+ },+);++export const compareGroups = chatTool(+ {+ name: 'compare_groups',+ description:+ 'Compare this group\'s member count and activity to other groups of the same type. Useful in B2B for "is this account active vs the rest?".',+ schema: z.object({+ groupId: z.string().optional(),+ }),+ },+ async ({ groupId }, context) => {+ const defaultGroupId = context.pageContext?.ids?.groupId ?? '';+ const id = groupId || defaultGroupId;++ const thisGroup = await getGroupCore({+ projectId: context.projectId,+ groupId: id,+ memberLimit: 0,+ });++ const peers = await findGroupsCore({+ projectId: context.projectId,+ type: thisGroup.group.type,+ limit: 100,+ });++ if (peers.length === 0) {+ return { this_group: thisGroup, peers: [], note: 'No peer groups' };+ }++ // `findGroupsCore` returns `IServiceGroup[]` without a memberCount+ // — that lives on `IServiceGroupStats` via a separate query. We+ // don't fetch it here, so we report peer count + this group's+ // count and list a handful of peers without rankings. If "rank by+ // members" becomes useful, fetch `getGroupStats` for each peer.+ return {+ this_group: {+ id: thisGroup.group.id,+ name: thisGroup.group.name,+ member_count: thisGroup.member_count,+ },+ peer_count: peers.length,+ top_peers: peers.slice(0, 5).map((g) => ({+ id: g.id,+ name: g.name,+ })),+ };+ },+);diff --git a/apps/api/src/agents/tools/helpers.ts b/apps/api/src/agents/tools/helpers.tsnew file mode 100644index 000000000..f3cf3f3df--- /dev/null+++ b/apps/api/src/agents/tools/helpers.ts@@ -0,0 +1,154 @@+import {+ type AgentToolDefinition,+ defineTool,+ type ToolRunContext,+} from '@better-agent/core';+import { resolveDateRange as resolveDateRangeCore } from '@openpanel/db';+import type { IChartEventFilter } from '@openpanel/validation';+import type { z } from 'zod';+import type { ChatAgentContext, PageContext } from '../context';++/** Max time a single tool handler is allowed to run. */+const TOOL_TIMEOUT_MS = 30_000;++/**+ * Thin wrapper around `defineTool().server()` that bakes in our typed+ * agent context and enforces a time ceiling. Three things this gives+ * us over the raw API:+ *+ * 1. The agent's `contextSchema` only types itself — `defineTool` has+ * no idea which agent it'll be bound to, so its `runCtx.context`+ * is `unknown`. We cast it to `ChatAgentContext` here so every+ * handler sees a typed context.+ * 2. The handler input is `any` (validated at runtime by Zod). We+ * deliberately don't try to infer it from the schema generic —+ * mixing TInput inference with the `BivariantFn` parameter shape+ * hits TypeScript's "type instantiation is excessively deep" limit+ * and breaks. Tools that need typed input destructure with an+ * inline annotation, or use `z.infer<typeof mySchema>`.+ * 3. A 30-second timeout wraps every handler. A slow ClickHouse query+ * or a stalled external fetch would otherwise hold the turn for+ * the full latency of the tool. We throw with a known shape so+ * the agent sees a clear "tool took too long" message and can+ * decide whether to retry with narrower params or move on.+ */+export function chatTool(+ config: {+ name: string;+ description: string;+ schema: z.ZodTypeAny;+ },+ handler: (+ // biome-ignore lint/suspicious/noExplicitAny: deliberate, see comment above+ input: any,+ ctx: ChatAgentContext,+ runCtx: ToolRunContext,+ ) => Promise<unknown>,+): AgentToolDefinition {+ // biome-ignore lint/suspicious/noExplicitAny: see block comment above+ const contract: any = defineTool({+ name: config.name,+ description: config.description,+ schema: config.schema,+ });+ return contract.server(+ async (input: unknown, runCtx: ToolRunContext) => {+ const work = handler(+ input,+ runCtx.context as ChatAgentContext,+ runCtx,+ );+ let timer: NodeJS.Timeout | undefined;+ const timeout = new Promise<never>((_, reject) => {+ timer = setTimeout(() => {+ reject(+ new Error(+ `Tool "${config.name}" timed out after ${TOOL_TIMEOUT_MS / 1000}s`,+ ),+ );+ }, TOOL_TIMEOUT_MS);+ });+ try {+ return await Promise.race([work, timeout]);+ } finally {+ if (timer) clearTimeout(timer);+ }+ },+ ) as AgentToolDefinition;+}++/**+ * Cap an array result to `max` items and append a truncation marker so the+ * frontend renderer + the LLM both know there's more data.+ */+export function truncateRows<T>(+ rows: T[],+ max = 500,+): { rows: T[]; total: number; _truncated: boolean } {+ if (rows.length <= max) {+ return { rows, total: rows.length, _truncated: false };+ }+ return { rows: rows.slice(0, max), total: rows.length, _truncated: true };+}++/**+ * Resolve a date range from PageContext.filters, defaulting to the+ * last 30 days. Delegates to the canonical `resolveDateRange` in+ * `@openpanel/db` so server-side tools and db services agree on the+ * default window.+ */+export function resolveDateRange(filters?: PageContext['filters']): {+ startDate: string;+ endDate: string;+} {+ return resolveDateRangeCore(filters?.startDate, filters?.endDate);+}++/**+ * Extract `IChartEventFilter[]` from the chat's page context. The+ * context schema keeps filters loose (Zod `record`), but the frontend+ * always ships the real chart-filter shape — so we cast here. Invalid+ * entries (missing `name`) are dropped defensively.+ *+ * Tools use this so the assistant sees the user's active filters ("I+ * see you're filtered to mobile") instead of returning project-wide+ * numbers that contradict the dashboard.+ */+export function pageContextFilters(+ pageContext: ChatAgentContext['pageContext'],+): IChartEventFilter[] {+ const raw = pageContext?.filters?.eventFilters;+ if (!Array.isArray(raw)) return [];+ return raw.filter(+ (f): f is IChartEventFilter =>+ typeof (f as { name?: unknown })?.name === 'string',+ );+}++/**+ * Compute the immediately-preceding period given a (start, end) range.+ */+export function previousPeriod(startDate: string, endDate: string) {+ const start = new Date(startDate).getTime();+ const end = new Date(endDate).getTime();+ const span = end - start;+ return {+ startDate: new Date(start - span - 86_400_000).toISOString().slice(0, 10),+ endDate: new Date(start - 86_400_000).toISOString().slice(0, 10),+ };+}++/**+ * Build a clickable dashboard URL for a tool result.+ */+export function dashboardUrl(+ organizationId: string,+ projectId: string,+ path = '',+): string {+ const base =+ process.env.DASHBOARD_URL ||+ process.env.NEXT_PUBLIC_DASHBOARD_URL ||+ 'http://localhost:3000';+ return `${base}/${organizationId}/${projectId}${path}`;+}diff --git a/apps/api/src/agents/tools/index.ts b/apps/api/src/agents/tools/index.tsnew file mode 100644index 000000000..c87f4116f--- /dev/null+++ b/apps/api/src/agents/tools/index.ts@@ -0,0 +1,175 @@+import type { AgentToolDefinition } from '@better-agent/core';+import type { ChatAgentContext } from '../context';+import * as base from './base';+import * as events from './events';+import * as groups from './groups';+import * as insights from './insights';+import * as pages from './pages';+import * as profile from './profile';+import * as references from './references';+import * as report from './report';+import * as seo from './seo';+import * as session from './session';+import * as ui from './ui';++// Tool arrays are typed loosely as `AgentToolDefinition[]` — without+// this, TypeScript tries to compute the union of every tool's schema ++// result type and hits its instantiation depth limit.+type ToolList = AgentToolDefinition[];++/**+ * Always-available base tool set: discovery + saved reports + aggregate+ * analytics + free-form queries. Every chat session starts here.+ */+const BASE_TOOLS: ToolList = [+ // Discovery+ base.listEventNames,+ base.listEventProperties,+ base.getEventPropertyValues,+ // Saved dashboards & reports+ base.listDashboards,+ base.listReports,+ base.getReportData,+ base.generateReport,+ // Aggregate analytics+ base.getAnalyticsOverview,+ base.getTopPages,+ base.getTopReferrers,+ base.getCountryBreakdown,+ base.getDeviceBreakdown,+ base.getRollingActiveUsers,+ base.getFunnel,+ base.getRetentionCohort,+ base.getUserFlow,+ // Free-form queries+ base.queryEvents,+ base.querySessions,+ base.findProfiles,+ // References — manual annotations the user adds for real-world+ // events (campaigns, deploys, announcements). Available everywhere+ // because "what happened around X?" is a useful question on+ // every page, not just the overview.+ references.listReferences,+ references.getReferencesAround,+] as AgentToolDefinition[];++const PROFILE_TOOLS: ToolList = [+ profile.getProfileFull,+ profile.getProfileEvents,+ profile.getProfileSessions,+ profile.getProfileMetrics,+ profile.getProfileJourney,+ profile.getProfileGroups,+ profile.compareProfileToAverage,+] as AgentToolDefinition[];++const SESSION_TOOLS: ToolList = [+ session.getSessionFull,+ session.getSessionPath,+ session.getSessionEvents,+ session.getSimilarSessions,+ session.compareSessionToTypical,+ session.getSessionReferrerContext,+ session.getSessionReplaySummary,+] as AgentToolDefinition[];++const REPORT_EDITOR_TOOLS: ToolList = [+ report.previewReportWithChanges,+ report.suggestBreakdowns,+ report.compareToPreviousPeriod,+ report.findAnomaliesInCurrentReport,+ report.explainFilterImpact,+] as AgentToolDefinition[];++const PAGES_TOOLS: ToolList = [+ pages.getPagePerformance,+ pages.getPageConversions,+ pages.getEntryExitPages,+ pages.findDecliningPages,+] as AgentToolDefinition[];++const SEO_TOOLS: ToolList = [+ seo.gscGetOverview,+ seo.gscGetTopQueries,+ seo.gscGetTopPages,+ seo.gscGetQueryDetails,+ seo.gscGetPageDetails,+ seo.gscGetQueryOpportunities,+ seo.gscGetCannibalization,+ seo.correlateSeoWithTraffic,+] as AgentToolDefinition[];++const EVENTS_TOOLS: ToolList = [+ events.analyzeEventDistribution,+ events.correlateEvents,+ events.getEventPropertyDistribution,+ events.listPropertiesForEvent,+] as AgentToolDefinition[];++const INSIGHTS_TOOLS: ToolList = [+ insights.listInsights,+ insights.explainInsight,+ insights.findRelatedInsights,+] as AgentToolDefinition[];++const GROUP_TOOLS: ToolList = [+ groups.getGroupFull,+ groups.getGroupMembers,+ groups.getGroupEvents,+ groups.getGroupMetrics,+ groups.compareGroups,+] as AgentToolDefinition[];++// Client-side UI mutators. Available on pages that have user-+// settable filters (date range, event names, property filters) so+// the assistant can act on requests like "filter to last 7 days",+// "show me only signups", or "referrers from GitHub" instead of+// just describing data.+const UI_TOOLS: ToolList = [+ ui.applyFilters,+ ui.setEventNamesFilter,+ ui.setPropertyFilters,+] as AgentToolDefinition[];++/**+ * Compose the chat tool set for a given request. Base tools are always+ * present; page-specific tools layer on top.+ *+ * Page-specific tools are only included when the corresponding entity+ * id is present in pageContext (e.g. profile tools require profileId),+ * so the LLM doesn't see tools it can't usefully call.+ *+ * The LLM sees fewer-but-more-focused tools per page, which produces+ * better tool selection than one giant flat registry.+ */+export function composeChatTools(context: ChatAgentContext) {+ const page = context.pageContext?.page;+ const ids = context.pageContext?.ids;++ switch (page) {+ case 'profileDetail':+ return ids?.profileId+ ? [...BASE_TOOLS, ...PROFILE_TOOLS, ...UI_TOOLS]+ : [...BASE_TOOLS, ...UI_TOOLS];+ case 'sessionDetail':+ return ids?.sessionId ? [...BASE_TOOLS, ...SESSION_TOOLS] : BASE_TOOLS;+ case 'reportEditor':+ return context.pageContext?.reportDraft+ ? [...BASE_TOOLS, ...REPORT_EDITOR_TOOLS]+ : BASE_TOOLS;+ case 'pages':+ return [...BASE_TOOLS, ...PAGES_TOOLS, ...UI_TOOLS];+ case 'seo':+ return [...BASE_TOOLS, ...SEO_TOOLS, ...UI_TOOLS];+ case 'events':+ return [...BASE_TOOLS, ...EVENTS_TOOLS, ...UI_TOOLS];+ case 'insights':+ return [...BASE_TOOLS, ...INSIGHTS_TOOLS, ...UI_TOOLS];+ case 'groupDetail':+ return ids?.groupId ? [...BASE_TOOLS, ...GROUP_TOOLS] : BASE_TOOLS;+ case 'overview':+ return [...BASE_TOOLS, ...UI_TOOLS];+ default:+ return BASE_TOOLS;+ }+}diff --git a/apps/api/src/agents/tools/insights.ts b/apps/api/src/agents/tools/insights.tsnew file mode 100644index 000000000..429664f98--- /dev/null+++ b/apps/api/src/agents/tools/insights.ts@@ -0,0 +1,117 @@+import { z } from 'zod';+import { db } from '@openpanel/db';+import { chatTool, truncateRows } from './helpers';++export const listInsights = chatTool(+ {+ name: 'list_insights',+ description:+ 'List active auto-detected insights for this project, sorted by impact. Each has module (geo/devices/referrers/etc.), direction (up/down/flat), severity, and impact score.',+ schema: z.object({+ limit: z.number().min(1).max(500).default(50).optional(),+ moduleKey: z+ .string()+ .optional()+ .describe('Filter by module: geo, devices, referrers, entry-pages, page-trends, exit-pages, traffic-anomalies'),+ severity: z+ .enum(['severe', 'moderate', 'low'])+ .optional(),+ direction: z.enum(['up', 'down', 'flat']).optional(),+ }),+ },+ async ({ limit, moduleKey, severity, direction }, context) => {+ const insights = await db.projectInsight.findMany({+ where: {+ projectId: context.projectId,+ state: 'active',+ ...(moduleKey ? { moduleKey } : {}),+ ...(severity ? { severityBand: severity } : {}),+ ...(direction ? { direction } : {}),+ },+ orderBy: { impactScore: 'desc' },+ take: limit ?? 50,+ });+ // Project to a UI/LLM-friendly shape. Order matters: the table+ // renderer uses the first string column as the label, and we want+ // the human title there — not the UUID.+ return truncateRows(+ insights.map((i) => ({+ title: i.title,+ summary: i.summary ?? '',+ module: i.moduleKey,+ dimension: i.dimensionKey,+ direction: i.direction ?? '',+ severity: i.severityBand ?? '',+ impact: Math.round(i.impactScore),+ window: i.windowKind,+ // Keep the id LAST so the model can call explain_insight with it,+ // but the table won't pick it as the label column.+ id: i.id,+ })),+ 100,+ );+ },+);++export const explainInsight = chatTool(+ {+ name: 'explain_insight',+ description:+ 'Get a single insight by ID with its full payload (the structured data the dashboard renders) plus its event history (when first detected, version updates).',+ schema: z.object({+ insightId: z.string(),+ }),+ },+ async ({ insightId }, context) => {+ const insight = await db.projectInsight.findFirst({+ where: { id: insightId, projectId: context.projectId },+ });+ if (!insight) {+ return { error: 'Insight not found', insightId };+ }+ const events = await db.insightEvent.findMany({+ where: { insightId },+ orderBy: { createdAt: 'desc' },+ take: 20,+ });+ return { insight, events };+ },+);++export const findRelatedInsights = chatTool(+ {+ name: 'find_related_insights',+ description:+ 'Given one insight, find others that share the same module or dimension. Useful when one insight prompts a "what else is going on with this country/page/device?" follow-up.',+ schema: z.object({+ insightId: z.string(),+ limit: z.number().min(1).max(50).default(10).optional(),+ }),+ },+ async ({ insightId, limit }, context) => {+ const insight = await db.projectInsight.findFirst({+ where: { id: insightId, projectId: context.projectId },+ });+ if (!insight) {+ return { error: 'Insight not found', insightId };+ }+ const related = await db.projectInsight.findMany({+ where: {+ projectId: context.projectId,+ id: { not: insightId },+ state: 'active',+ OR: [+ { moduleKey: insight.moduleKey },+ { dimensionKey: insight.dimensionKey },+ ],+ },+ orderBy: { impactScore: 'desc' },+ take: limit ?? 10,+ });+ return {+ source_insight: { id: insight.id, moduleKey: insight.moduleKey, dimensionKey: insight.dimensionKey },+ related_count: related.length,+ related,+ };+ },+);diff --git a/apps/api/src/agents/tools/pages.ts b/apps/api/src/agents/tools/pages.tsnew file mode 100644index 000000000..a523efe3f--- /dev/null+++ b/apps/api/src/agents/tools/pages.ts@@ -0,0 +1,168 @@+import { z } from 'zod';+import {+ getEntryExitPagesCore,+ getPageConversionsCore,+ getPagePerformanceCore,+ getTopPagesCore,+} from '@openpanel/db';+import { chatTool, previousPeriod, resolveDateRange, truncateRows } from './helpers';++export const getPagePerformance = chatTool(+ {+ name: 'get_page_performance',+ description:+ 'Per-page performance metrics with SEO signal flags (high bounce, low engagement, good landing page). Sortable by sessions, pageviews, bounce_rate, or avg_duration.',+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ search: z.string().optional(),+ sortBy: z+ .enum(['sessions', 'pageviews', 'bounce_rate', 'avg_duration'])+ .default('sessions')+ .optional(),+ sortOrder: z.enum(['asc', 'desc']).default('desc').optional(),+ limit: z.number().min(1).max(500).default(50).optional(),+ }),+ },+ async (input, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: input.startDate ?? context.pageContext?.filters?.startDate,+ endDate: input.endDate ?? context.pageContext?.filters?.endDate,+ });+ return getPagePerformanceCore({+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ search: input.search,+ sortBy: input.sortBy,+ sortOrder: input.sortOrder,+ limit: input.limit ?? 50,+ });+ },+);++export const getPageConversions = chatTool(+ {+ name: 'get_page_conversions',+ description:+ 'For a given conversion event, find which pages drive the most conversions. Includes conversion rate per page.',+ schema: z.object({+ conversionEvent: z+ .string()+ .describe('The conversion event name (e.g. "signup", "purchase")'),+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ windowHours: z.number().min(1).max(720).default(24).optional(),+ limit: z.number().min(1).max(500).default(50).optional(),+ }),+ },+ async (input, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: input.startDate ?? context.pageContext?.filters?.startDate,+ endDate: input.endDate ?? context.pageContext?.filters?.endDate,+ });+ const rows = await getPageConversionsCore({+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ conversionEvent: input.conversionEvent,+ windowHours: input.windowHours,+ limit: input.limit ?? 50,+ });+ return truncateRows(rows, 100);+ },+);++export const getEntryExitPages = chatTool(+ {+ name: 'get_entry_exit_pages',+ description:+ 'Top entry pages or top exit pages — useful for understanding where users start and where they bounce.',+ schema: z.object({+ mode: z.enum(['entry', 'exit']),+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ }),+ },+ async ({ mode, startDate, endDate }, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: startDate ?? context.pageContext?.filters?.startDate,+ endDate: endDate ?? context.pageContext?.filters?.endDate,+ });+ const rows = await getEntryExitPagesCore({+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ mode,+ });+ return truncateRows(rows, 50);+ },+);++export const findDecliningPages = chatTool(+ {+ name: 'find_declining_pages',+ description:+ 'Find pages where pageview volume dropped vs the immediately preceding period of the same length. Returns each declining page with absolute and percent change.',+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ minPageviews: z+ .number()+ .min(1)+ .default(50)+ .optional()+ .describe('Filter out pages with fewer than N pageviews in the previous period'),+ }),+ },+ async (input, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: input.startDate ?? context.pageContext?.filters?.startDate,+ endDate: input.endDate ?? context.pageContext?.filters?.endDate,+ });+ const prev = previousPeriod(range.startDate, range.endDate);++ const [current, previous] = await Promise.all([+ getTopPagesCore({+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ limit: 500,+ }),+ getTopPagesCore({+ projectId: context.projectId,+ startDate: prev.startDate,+ endDate: prev.endDate,+ limit: 500,+ }),+ ]);++ // biome-ignore lint/suspicious/noExplicitAny: pages shape varies between engines+ const currMap = new Map<string, any>(+ (current as Array<{ name?: string; path?: string }>).map((p) => [+ String(p.name ?? p.path),+ p,+ ]),+ );+ const min = input.minPageviews ?? 50;+ const declines = (previous as Array<{ name?: string; path?: string; count?: number; sessions?: number }>)+ .filter((p) => (p.count ?? p.sessions ?? 0) >= min)+ .map((p) => {+ const key = String(p.name ?? p.path);+ const curr = currMap.get(key);+ const prevCount = Number(p.count ?? p.sessions ?? 0);+ const currCount = Number(curr?.count ?? curr?.sessions ?? 0);+ const delta = currCount - prevCount;+ const pct = prevCount > 0 ? (delta / prevCount) * 100 : 0;+ return { path: key, previous: prevCount, current: currCount, delta, percent_change: Number(pct.toFixed(1)) };+ })+ .filter((row) => row.delta < 0)+ .sort((a, b) => a.percent_change - b.percent_change);++ return truncateRows(declines, 50);+ },+);diff --git a/apps/api/src/agents/tools/profile.ts b/apps/api/src/agents/tools/profile.tsnew file mode 100644index 000000000..2c4478bbd--- /dev/null+++ b/apps/api/src/agents/tools/profile.ts@@ -0,0 +1,293 @@+import { z } from 'zod';+import {+ findProfilesCore,+ getProfileById,+ getProfileMetricsCore,+ getProfileSessionsCore,+ getProfileWithEvents,+ queryEventsCore,+} from '@openpanel/db';+import { chatTool, dashboardUrl, truncateRows } from './helpers';++export const getProfileFull = chatTool(+ {+ name: 'get_profile_full',+ description:+ 'One-shot deep dive: profile data + lifetime metrics + last 5 sessions + last 10 events. CALL THIS FIRST when the user asks "tell me about this user" — it covers ~80% of follow-up questions in one round trip.',+ schema: z.object({+ profileId: z+ .string()+ .optional()+ .describe('Defaults to the currently-viewed profile.'),+ }),+ },+ async ({ profileId }, context) => {+ const id = profileId || context.pageContext?.ids?.profileId || '';+ const [profile, withEvents, sessions, metrics] = await Promise.all([+ getProfileById(id, context.projectId),+ getProfileWithEvents(context.projectId, id, 10),+ getProfileSessionsCore(context.projectId, id, 5),+ getProfileMetricsCore({ projectId: context.projectId, profileId: id }).catch(+ () => null,+ ),+ ]);+ if (!profile) {+ return { error: 'Profile not found', profileId: id };+ }+ return {+ profile,+ metrics,+ recent_sessions: sessions,+ recent_events: withEvents.recent_events,+ dashboard_url: dashboardUrl(context.organizationId, context.projectId, `/profiles/${id}`),+ };+ },+);++export const getProfileEvents = chatTool(+ {+ name: 'get_profile_events',+ description:+ 'Recent events for this profile, optionally filtered by event name or property. Use when get_profile_full doesn\'t cover the question.',+ schema: z.object({+ profileId: z.string().optional(),+ eventNames: z+ .array(z.string())+ .optional()+ .describe('Filter to specific event names'),+ properties: z.record(z.string(), z.string()).optional(),+ limit: z.number().min(1).max(100).default(50).optional(),+ }),+ },+ async ({ profileId, eventNames, properties, limit }, context) => {+ const events = await queryEventsCore({+ projectId: context.projectId,+ profileId: profileId || context.pageContext?.ids?.profileId || '',+ eventNames,+ properties,+ limit: limit ?? 50,+ });+ return truncateRows(events, 100);+ },+);++export const getProfileSessions = chatTool(+ {+ name: 'get_profile_sessions',+ description:+ 'All sessions for this profile, ordered most-recent-first.',+ schema: z.object({+ profileId: z.string().optional(),+ limit: z.number().min(1).max(100).default(20).optional(),+ }),+ },+ async ({ profileId, limit }, context) => {+ const sessions = await getProfileSessionsCore(+ context.projectId,+ profileId || context.pageContext?.ids?.profileId || '',+ limit ?? 20,+ );+ return truncateRows(+ sessions.map((s) => ({+ ...s,+ dashboard_url: dashboardUrl(context.organizationId, context.projectId, `/sessions/${s.id}`),+ })),+ 100,+ );+ },+);++export const getProfileMetrics = chatTool(+ {+ name: 'get_profile_metrics',+ description:+ 'Lifetime metrics for this profile: sessions, screen views, total events, avg/p90 session duration, bounce rate, conversion events, time between sessions, revenue.',+ schema: z.object({+ profileId: z.string().optional(),+ }),+ },+ async ({ profileId }, context) =>+ getProfileMetricsCore({+ projectId: context.projectId,+ profileId: profileId || context.pageContext?.ids?.profileId || '',+ }),+);++export const getProfileJourney = chatTool(+ {+ name: 'get_profile_journey',+ description:+ 'Chronological narrative of this user\'s journey: first session, key conversion events, last 30 days summary. Designed for "tell me their story" questions — gives the LLM a structured timeline rather than a flat event list.',+ schema: z.object({+ profileId: z.string().optional(),+ sinceDays: z.number().min(1).max(365).default(90).optional(),+ maxEvents: z.number().min(5).max(100).default(50).optional(),+ }),+ },+ async ({ profileId, sinceDays, maxEvents }, context) => {+ const id = profileId || context.pageContext?.ids?.profileId || '';+ const [profile, events, sessions, metrics] = await Promise.all([+ getProfileById(id, context.projectId),+ queryEventsCore({+ projectId: context.projectId,+ profileId: id,+ limit: maxEvents ?? 50,+ }),+ getProfileSessionsCore(context.projectId, id, 20),+ getProfileMetricsCore({ projectId: context.projectId, profileId: id }).catch(+ () => null,+ ),+ ]);++ if (!profile) {+ return { error: 'Profile not found', profileId: id };+ }++ // Heuristic: events that look like conversions (purchase, signup,+ // checkout, subscribe, upgrade, complete, etc.)+ const conversionPattern =+ /^(purchase|sign_?up|signup|register|subscribe|checkout|upgrade|complete|paid|conversion)/i;+ const keyMoments = events.filter((e) => conversionPattern.test(e.name));++ return {+ profile_id: id,+ first_seen: metrics?.firstSeen ?? sessions[sessions.length - 1]?.created_at ?? null,+ last_seen: metrics?.lastSeen ?? sessions[0]?.created_at ?? null,+ total_sessions: metrics?.sessions ?? sessions.length,+ total_events: metrics?.totalEvents ?? events.length,+ key_moments: keyMoments.slice(0, 10),+ recent_sessions: sessions.slice(0, 5).map((s) => ({+ id: s.id,+ created_at: s.created_at,+ duration: s.duration,+ entry_path: s.entry_path,+ exit_path: s.exit_path,+ is_bounce: s.is_bounce,+ country: s.country,+ referrer: s.referrer,+ })),+ recent_events: events.slice(0, 20).map((e) => ({+ id: e.id,+ name: e.name,+ path: e.path,+ created_at: e.created_at,+ })),+ dashboard_url: dashboardUrl(context.organizationId, context.projectId, `/profiles/${id}`),+ };+ },+);++export const getProfileGroups = chatTool(+ {+ name: 'get_profile_groups',+ description:+ 'Groups (B2B accounts) this profile belongs to. Returns the list of group IDs from the profile record.',+ schema: z.object({+ profileId: z.string().optional(),+ }),+ },+ async ({ profileId }, context) => {+ const id = profileId || context.pageContext?.ids?.profileId || '';+ const profile = await getProfileById(id, context.projectId);+ if (!profile) {+ return { error: 'Profile not found', profileId: id };+ }+ return {+ profileId: profile.id,+ group_count: (profile.groups ?? []).length,+ groups: profile.groups ?? [],+ };+ },+);++export const compareProfileToAverage = chatTool(+ {+ name: 'compare_profile_to_average',+ description:+ 'How this profile\'s key metrics compare to the project average — sessions, total events, bounce rate, etc. Returns ratios and "above/below" labels for each metric. Useful for spotting power users vs lurkers.',+ schema: z.object({+ profileId: z.string().optional(),+ }),+ },+ async ({ profileId }, context) => {+ const id = profileId || context.pageContext?.ids?.profileId || '';++ // Get this profile's metrics + a sample of other profiles' metrics+ const [thisMetrics, allProfiles] = await Promise.all([+ getProfileMetricsCore({ projectId: context.projectId, profileId: id }).catch(+ () => null,+ ),+ findProfilesCore({ projectId: context.projectId, limit: 100 }),+ ]);++ if (!thisMetrics) {+ return { error: 'Profile not found or has no events', profileId: id };+ }++ // Compute averages from a sample of other profiles. We sample 100+ // and compute their metrics in parallel; for a precise project-wide+ // average we'd want a dedicated db helper, but this gives the LLM a+ // useful comparison without extra schema work.+ const sampleIds = allProfiles+ .filter((p) => p.id !== id)+ .slice(0, 30)+ .map((p) => p.id);++ const sampleMetrics = await Promise.all(+ sampleIds.map((sid) =>+ getProfileMetricsCore({ projectId: context.projectId, profileId: sid }).catch(+ () => null,+ ),+ ),+ );+ const valid = sampleMetrics.filter(+ (m): m is NonNullable<typeof m> => m != null,+ );++ if (valid.length === 0) {+ return {+ profile: thisMetrics,+ comparison: null,+ note: 'No other profiles available for comparison',+ };+ }++ const avg = (sel: (m: typeof valid[number]) => number) =>+ valid.reduce((s, m) => s + sel(m), 0) / valid.length;++ const project_avg = {+ sessions: avg((m) => m.sessions),+ totalEvents: avg((m) => m.totalEvents),+ screenViews: avg((m) => m.screenViews),+ avgSessionDurationMin: avg((m) => m.avgSessionDurationMin),+ bounceRate: avg((m) => m.bounceRate),+ revenue: avg((m) => m.revenue),+ };++ const ratio = (a: number, b: number): { ratio: number; label: 'above' | 'below' | 'equal' } => {+ if (b === 0) return { ratio: 0, label: a > 0 ? 'above' : 'equal' };+ const r = a / b;+ return {+ ratio: Number(r.toFixed(2)),+ label: r > 1.05 ? 'above' : r < 0.95 ? 'below' : 'equal',+ };+ };++ return {+ profile: thisMetrics,+ project_avg,+ comparison: {+ sessions: ratio(thisMetrics.sessions, project_avg.sessions),+ totalEvents: ratio(thisMetrics.totalEvents, project_avg.totalEvents),+ screenViews: ratio(thisMetrics.screenViews, project_avg.screenViews),+ avgSessionDurationMin: ratio(+ thisMetrics.avgSessionDurationMin,+ project_avg.avgSessionDurationMin,+ ),+ bounceRate: ratio(thisMetrics.bounceRate, project_avg.bounceRate),+ revenue: ratio(thisMetrics.revenue, project_avg.revenue),+ },+ sample_size: valid.length,+ };+ },+);diff --git a/apps/api/src/agents/tools/references.ts b/apps/api/src/agents/tools/references.tsnew file mode 100644index 000000000..6e580ad8d--- /dev/null+++ b/apps/api/src/agents/tools/references.ts@@ -0,0 +1,130 @@+import { db } from '@openpanel/db';+import { z } from 'zod';+import { chatTool, resolveDateRange, truncateRows } from './helpers';++/**+ * References are manual annotations the user adds — e.g.+ * "Launched new marketing campaign" on 2026-03-15. They mark+ * real-world events so the AI can correlate traffic changes with+ * things that happened off-platform.+ *+ * Use these tools whenever the user asks things like:+ * - "What caused this spike?"+ * - "Are any recent launches affecting the numbers?"+ * - "Show me what happened around [date]"+ *+ * Or proactively when you notice a traffic anomaly and want to see+ * if a reference explains it.+ */++export const listReferences = chatTool(+ {+ name: 'list_references',+ description:+ "List the user's manual references (campaign launches, deploys, announcements, etc.). Use when the user asks about causes of traffic changes or wants to understand what was happening at a specific time. Defaults to the user's current page date range; pass explicit dates to override.",+ schema: z.object({+ startDate: z+ .string()+ .optional()+ .describe('ISO date YYYY-MM-DD. Defaults to the current view range.'),+ endDate: z+ .string()+ .optional()+ .describe('ISO date YYYY-MM-DD. Defaults to the current view range.'),+ search: z+ .string()+ .optional()+ .describe('Optional free-text filter on title/description.'),+ limit: z.number().min(1).max(100).default(50).optional(),+ }),+ },+ async ({ startDate, endDate, search, limit }, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: startDate ?? context.pageContext?.filters?.startDate,+ endDate: endDate ?? context.pageContext?.filters?.endDate,+ });++ const rows = await db.reference.findMany({+ where: {+ projectId: context.projectId,+ date: {+ gte: new Date(range.startDate),+ lte: new Date(`${range.endDate}T23:59:59.999Z`),+ },+ ...(search+ ? {+ OR: [+ { title: { contains: search, mode: 'insensitive' as const } },+ {+ description: {+ contains: search,+ mode: 'insensitive' as const,+ },+ },+ ],+ }+ : {}),+ },+ orderBy: { date: 'desc' },+ take: limit ?? 50,+ });++ return truncateRows(+ rows.map((r) => ({+ title: r.title,+ date: r.date.toISOString().slice(0, 10),+ description: r.description ?? '',+ id: r.id,+ })),+ 100,+ );+ },+);++export const getReferencesAround = chatTool(+ {+ name: 'get_references_around',+ description:+ 'Find references within ±N days of a target date. Perfect for "what was happening around 2026-03-15?" — returns references that might explain a spike or drop.',+ schema: z.object({+ date: z+ .string()+ .describe('Target date (YYYY-MM-DD) to search around.'),+ daysBefore: z.number().min(0).max(90).default(7).optional(),+ daysAfter: z.number().min(0).max(90).default(7).optional(),+ }),+ },+ async ({ date, daysBefore, daysAfter }, context) => {+ const target = new Date(date);+ if (Number.isNaN(target.getTime())) {+ return { error: 'Invalid date', date };+ }+ const before = daysBefore ?? 7;+ const after = daysAfter ?? 7;+ const start = new Date(target.getTime() - before * 86_400_000);+ const end = new Date(target.getTime() + after * 86_400_000);++ const rows = await db.reference.findMany({+ where: {+ projectId: context.projectId,+ date: { gte: start, lte: end },+ },+ orderBy: { date: 'asc' },+ });++ return {+ target_date: date,+ window: {+ start: start.toISOString().slice(0, 10),+ end: end.toISOString().slice(0, 10),+ },+ references: rows.map((r) => ({+ title: r.title,+ date: r.date.toISOString().slice(0, 10),+ description: r.description ?? '',+ id: r.id,+ })),+ };+ },+);diff --git a/apps/api/src/agents/tools/report.ts b/apps/api/src/agents/tools/report.tsnew file mode 100644index 000000000..f94b0f5e6--- /dev/null+++ b/apps/api/src/agents/tools/report.ts@@ -0,0 +1,315 @@+import { z } from 'zod';+import { listEventPropertiesCore } from '@openpanel/db';+import { runReportFromConfig } from '@openpanel/mcp';+import type { IReportInput } from '@openpanel/validation';+import { chatTool, previousPeriod, resolveDateRange } from './helpers';++export const previewReportWithChanges = chatTool(+ {+ name: 'preview_report_with_changes',+ description:+ 'Apply a partial diff to the current report draft, execute it, and return the resulting data + the modified config. Use this to PROPOSE edits — the user can then accept or reject. Pass only the fields you want to change (e.g. { breakdowns: [{ name: "country" }] }).',+ schema: z.object({+ chartType: z+ .enum(['linear', 'bar', 'area', 'histogram', 'pie', 'metric', 'funnel'])+ .optional(),+ interval: z.enum(['minute', 'hour', 'day', 'week', 'month']).optional(),+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ addBreakdown: z+ .string()+ .optional()+ .describe('Property key to add as a breakdown (e.g. "country")'),+ removeBreakdown: z+ .string()+ .optional()+ .describe('Property key to remove from breakdowns'),+ addEventFilter: z+ .object({+ seriesIndex: z.number().min(0),+ name: z.string(),+ operator: z.string(),+ value: z.array(z.string()),+ })+ .optional(),+ }),+ },+ async (input, context) => {+ const draft = context.pageContext?.reportDraft as IReportInput | undefined;+ if (!draft) {+ return { error: 'No report draft available in the current context' };+ }++ const range = resolveDateRange({+ startDate: input.startDate ?? draft.startDate ?? undefined,+ endDate: input.endDate ?? draft.endDate ?? undefined,+ });++ const next: IReportInput = {+ ...draft,+ chartType: input.chartType ?? draft.chartType,+ interval: input.interval ?? draft.interval,+ startDate: range.startDate,+ endDate: range.endDate,+ range: 'custom',+ breakdowns: [...(draft.breakdowns ?? [])],+ series: draft.series.map((s) => ({ ...s })),+ };++ if (input.addBreakdown) {+ if (!next.breakdowns.some((b) => b.name === input.addBreakdown)) {+ next.breakdowns.push({+ id: String(next.breakdowns.length + 1),+ name: input.addBreakdown,+ });+ }+ }+ if (input.removeBreakdown) {+ next.breakdowns = next.breakdowns.filter(+ (b) => b.name !== input.removeBreakdown,+ );+ }+ if (input.addEventFilter) {+ const idx = input.addEventFilter.seriesIndex;+ const target = next.series[idx];+ if (target && idx >= 0 && target.type === 'event') {+ // biome-ignore lint/suspicious/noExplicitAny: series type is heavily discriminated; filter ops vary+ const series = target as any;+ series.filters = [+ ...(series.filters ?? []),+ {+ id: String((series.filters?.length ?? 0) + 1),+ name: input.addEventFilter.name,+ operator: input.addEventFilter.operator,+ value: input.addEventFilter.value,+ },+ ];+ }+ }++ return runReportFromConfig({+ organizationId: context.organizationId,+ projectId: context.projectId,+ config: next as unknown as Parameters<typeof runReportFromConfig>[0]['config'],+ });+ },+);++export const suggestBreakdowns = chatTool(+ {+ name: 'suggest_breakdowns',+ description:+ 'Look at the events selected in the current draft and suggest 3-5 useful properties to break down by. Returns property keys + how often they appear.',+ schema: z.object({}),+ },+ async (_input, context) => {+ const draft = context.pageContext?.reportDraft as IReportInput | undefined;+ if (!draft) {+ return { error: 'No report draft available in the current context' };+ }++ const eventNames = draft.series+ .filter((s) => s.type === 'event')+ .map((s) => (s as { name: string }).name);++ if (eventNames.length === 0) {+ return { suggestions: [], note: 'Draft has no event series' };+ }++ const propsPerEvent = await Promise.all(+ eventNames.map((name) =>+ listEventPropertiesCore({+ projectId: context.projectId,+ eventName: name,+ }),+ ),+ );++ // Aggregate property keys across events+ const keyCount = new Map<string, number>();+ for (const r of propsPerEvent) {+ for (const p of r.properties) {+ keyCount.set(p.property_key, (keyCount.get(p.property_key) ?? 0) + 1);+ }+ }++ // Filter out keys that are already used as breakdowns+ const used = new Set((draft.breakdowns ?? []).map((b) => b.name));+ const suggestions = Array.from(keyCount.entries())+ .filter(([k]) => !used.has(k))+ .sort((a, b) => b[1] - a[1])+ .slice(0, 5)+ .map(([key, count]) => ({ property_key: key, present_in_events: count }));++ return {+ events_in_draft: eventNames,+ existing_breakdowns: Array.from(used),+ suggestions,+ };+ },+);++export const compareToPreviousPeriod = chatTool(+ {+ name: 'compare_to_previous_period',+ description:+ 'Run the current draft against the immediately preceding period of the same length, and return both as { current, previous } so the user can see week-over-week / month-over-month change.',+ schema: z.object({}),+ },+ async (_input, context) => {+ const draft = context.pageContext?.reportDraft as IReportInput | undefined;+ if (!draft) {+ return { error: 'No report draft available in the current context' };+ }++ const range = resolveDateRange({+ startDate: draft.startDate ?? undefined,+ endDate: draft.endDate ?? undefined,+ });+ const prev = previousPeriod(range.startDate, range.endDate);++ const [current, previous] = await Promise.all([+ runReportFromConfig({+ organizationId: context.organizationId,+ projectId: context.projectId,+ config: {+ ...(draft as unknown as Record<string, unknown>),+ startDate: range.startDate,+ endDate: range.endDate,+ range: 'custom',+ } as unknown as Parameters<typeof runReportFromConfig>[0]['config'],+ }),+ runReportFromConfig({+ organizationId: context.organizationId,+ projectId: context.projectId,+ config: {+ ...(draft as unknown as Record<string, unknown>),+ startDate: prev.startDate,+ endDate: prev.endDate,+ range: 'custom',+ } as unknown as Parameters<typeof runReportFromConfig>[0]['config'],+ }),+ ]);++ return { current, previous };+ },+);++export const findAnomaliesInCurrentReport = chatTool(+ {+ name: 'find_anomalies_in_current_report',+ description:+ 'Run the current draft and find data points that are unusually high or low (z-score > 2 from rolling mean). Returns the anomalies with their dates and magnitudes.',+ schema: z.object({}),+ },+ async (_input, context) => {+ const draft = context.pageContext?.reportDraft as IReportInput | undefined;+ if (!draft) {+ return { error: 'No report draft available in the current context' };+ }++ const range = resolveDateRange({+ startDate: draft.startDate ?? undefined,+ endDate: draft.endDate ?? undefined,+ });++ const result = await runReportFromConfig({+ organizationId: context.organizationId,+ projectId: context.projectId,+ config: {+ ...(draft as unknown as Record<string, unknown>),+ startDate: range.startDate,+ endDate: range.endDate,+ range: 'custom',+ } as unknown as Parameters<typeof runReportFromConfig>[0]['config'],+ });++ // Best-effort anomaly detection on the first series of the result.+ // The data shape varies by chart type — we look for an array of+ // { date, count } points.+ // biome-ignore lint/suspicious/noExplicitAny: chart engine output shape is varied+ const data = result.data as any;+ const series = Array.isArray(data) ? data[0] : data?.series?.[0];+ const points = series?.data ?? [];++ if (!Array.isArray(points) || points.length < 5) {+ return {+ note: 'Not enough data points to detect anomalies',+ point_count: points.length ?? 0,+ };+ }++ const values = points.map((p: { count?: number }) => Number(p.count ?? 0));+ const mean = values.reduce((s: number, v: number) => s + v, 0) / values.length;+ const variance =+ values.reduce((s: number, v: number) => s + (v - mean) ** 2, 0) / values.length;+ const std = Math.sqrt(variance);++ const anomalies = points+ .map((p: { date?: string; count?: number }, i: number) => {+ const z = std === 0 ? 0 : (Number(p.count ?? 0) - mean) / std;+ return { date: p.date, value: p.count, z_score: Number(z.toFixed(2)), index: i };+ })+ .filter((a: { z_score: number }) => Math.abs(a.z_score) > 2);++ return {+ mean: Number(mean.toFixed(2)),+ std: Number(std.toFixed(2)),+ point_count: points.length,+ anomalies,+ };+ },+);++export const explainFilterImpact = chatTool(+ {+ name: 'explain_filter_impact',+ description:+ 'Run the current draft both with and without its filters, and return both totals so the user can see how much the filters cut down the data.',+ schema: z.object({}),+ },+ async (_input, context) => {+ const draft = context.pageContext?.reportDraft as IReportInput | undefined;+ if (!draft) {+ return { error: 'No report draft available in the current context' };+ }++ const range = resolveDateRange({+ startDate: draft.startDate ?? undefined,+ endDate: draft.endDate ?? undefined,+ });++ const filtered = await runReportFromConfig({+ organizationId: context.organizationId,+ projectId: context.projectId,+ config: {+ ...(draft as unknown as Record<string, unknown>),+ startDate: range.startDate,+ endDate: range.endDate,+ range: 'custom',+ } as unknown as Parameters<typeof runReportFromConfig>[0]['config'],+ });++ const cleanedSeries = draft.series.map((s) => ({+ ...s,+ filters: [],+ }));++ const unfiltered = await runReportFromConfig({+ organizationId: context.organizationId,+ projectId: context.projectId,+ config: {+ ...(draft as unknown as Record<string, unknown>),+ series: cleanedSeries,+ startDate: range.startDate,+ endDate: range.endDate,+ range: 'custom',+ } as unknown as Parameters<typeof runReportFromConfig>[0]['config'],+ });++ return {+ with_filters: filtered,+ without_filters: unfiltered,+ };+ },+);diff --git a/apps/api/src/agents/tools/seo.ts b/apps/api/src/agents/tools/seo.tsnew file mode 100644index 000000000..05beff9fa--- /dev/null+++ b/apps/api/src/agents/tools/seo.ts@@ -0,0 +1,276 @@+import { z } from 'zod';+import {+ getTopPagesCore,+ gscGetCannibalizationCore,+ gscGetOverviewCore,+ gscGetPageDetailsCore,+ gscGetQueryDetailsCore,+ gscGetQueryOpportunitiesCore,+ gscGetTopPagesCore,+ gscGetTopQueriesCore,+} from '@openpanel/db';+import { chatTool, resolveDateRange, truncateRows } from './helpers';++export const gscGetOverview = chatTool(+ {+ name: 'gsc_get_overview',+ description:+ 'GSC performance over time — clicks, impressions, CTR, average position. Returns a daily/weekly/monthly time series plus totals.',+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ interval: z.enum(['day', 'week', 'month']).default('day').optional(),+ }),+ },+ async ({ startDate, endDate, interval }, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: startDate ?? context.pageContext?.filters?.startDate,+ endDate: endDate ?? context.pageContext?.filters?.endDate,+ });+ return gscGetOverviewCore({+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ interval,+ });+ },+);++export const gscGetTopQueries = chatTool(+ {+ name: 'gsc_get_top_queries',+ description:+ 'Top search queries by clicks. Returns query, clicks, impressions, CTR, position.',+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ limit: z.number().min(1).max(500).default(50).optional(),+ }),+ },+ async ({ startDate, endDate, limit }, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: startDate ?? context.pageContext?.filters?.startDate,+ endDate: endDate ?? context.pageContext?.filters?.endDate,+ });+ const rows = await gscGetTopQueriesCore({+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ limit: limit ?? 50,+ });+ return truncateRows(rows, 100);+ },+);++export const gscGetTopPages = chatTool(+ {+ name: 'gsc_get_top_pages',+ description:+ 'Top pages by GSC clicks. Returns page URL, clicks, impressions, CTR, position.',+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ limit: z.number().min(1).max(500).default(50).optional(),+ }),+ },+ async ({ startDate, endDate, limit }, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: startDate ?? context.pageContext?.filters?.startDate,+ endDate: endDate ?? context.pageContext?.filters?.endDate,+ });+ const rows = await gscGetTopPagesCore({+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ limit: limit ?? 50,+ });+ return truncateRows(rows, 100);+ },+);++export const gscGetQueryDetails = chatTool(+ {+ name: 'gsc_get_query_details',+ description:+ 'Time-series + page list for a single query. Use after gsc_get_top_queries to drill into one query.',+ schema: z.object({+ query: z.string(),+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ }),+ },+ async ({ query, startDate, endDate }, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: startDate ?? context.pageContext?.filters?.startDate,+ endDate: endDate ?? context.pageContext?.filters?.endDate,+ });+ return gscGetQueryDetailsCore({+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ query,+ });+ },+);++export const gscGetPageDetails = chatTool(+ {+ name: 'gsc_get_page_details',+ description:+ 'Time-series + ranking queries for a single page URL. Use after gsc_get_top_pages.',+ schema: z.object({+ page: z.string().describe('Full page URL'),+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ }),+ },+ async ({ page, startDate, endDate }, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: startDate ?? context.pageContext?.filters?.startDate,+ endDate: endDate ?? context.pageContext?.filters?.endDate,+ });+ return gscGetPageDetailsCore({+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ page,+ });+ },+);++export const gscGetQueryOpportunities = chatTool(+ {+ name: 'gsc_get_query_opportunities',+ description:+ 'Find low-hanging SEO fruit — queries ranking position 4-20 with high impressions but low clicks. Returns each opportunity with a score and reason.',+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ minImpressions: z.number().min(1).default(50).optional(),+ }),+ },+ async ({ startDate, endDate, minImpressions }, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: startDate ?? context.pageContext?.filters?.startDate,+ endDate: endDate ?? context.pageContext?.filters?.endDate,+ });+ return gscGetQueryOpportunitiesCore({+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ minImpressions,+ });+ },+);++export const gscGetCannibalization = chatTool(+ {+ name: 'gsc_get_cannibalization',+ description:+ 'Find queries where multiple pages from the same site compete for the same ranking. Each result shows the query and the competing pages.',+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ }),+ },+ async ({ startDate, endDate }, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: startDate ?? context.pageContext?.filters?.startDate,+ endDate: endDate ?? context.pageContext?.filters?.endDate,+ });+ return gscGetCannibalizationCore({+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ });+ },+);++export const correlateSeoWithTraffic = chatTool(+ {+ name: 'correlate_seo_with_traffic',+ description:+ 'Combine GSC clicks with OpenPanel session data per page. Identifies pages with high SEO traffic but poor conversion (high bounce or low engagement). Run this when the user wants to know "which SEO pages aren\'t converting".',+ schema: z.object({+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ limit: z.number().min(1).max(100).default(30).optional(),+ }),+ },+ async ({ startDate, endDate, limit }, context) => {+ const range = resolveDateRange({+ ...context.pageContext?.filters,+ startDate: startDate ?? context.pageContext?.filters?.startDate,+ endDate: endDate ?? context.pageContext?.filters?.endDate,+ });++ const [gscPages, opPages] = await Promise.all([+ gscGetTopPagesCore({+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ limit: 200,+ }),+ getTopPagesCore({+ projectId: context.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ limit: 200,+ }),+ ]);++ // The OP `getTopPagesCore` and GSC `gscGetTopPagesCore` return+ // different row shapes — the fields we actually read are captured+ // in these local types, keeping the lookup map typed.+ type OpPage = {+ name?: string;+ path?: string;+ sessions?: number;+ bounce_rate?: number;+ avg_duration?: number;+ };+ type GscPage = {+ page: string;+ clicks: number;+ impressions: number;+ ctr: number;+ position: number;+ };++ const opByPath = new Map<string, OpPage>();+ for (const p of opPages as OpPage[]) {+ const key = String(p.name ?? p.path ?? '');+ opByPath.set(key, p);+ opByPath.set(key.replace(/\/$/, ''), p);+ }++ const correlated = (gscPages as GscPage[])+ .map((g) => {+ const pathOnly = g.page.replace(/^https?:\/\/[^/]+/, '');+ const op =+ opByPath.get(pathOnly) ?? opByPath.get(pathOnly.replace(/\/$/, ''));+ return {+ page: g.page,+ gsc_clicks: g.clicks,+ gsc_impressions: g.impressions,+ gsc_ctr: g.ctr,+ gsc_position: g.position,+ op_sessions: op?.sessions ?? null,+ op_bounce_rate: op?.bounce_rate ?? null,+ op_avg_duration: op?.avg_duration ?? null,+ underperforming:+ (op?.bounce_rate ?? 0) > 70 || (op?.avg_duration ?? 99) < 1,+ };+ })+ .sort((a, b) => b.gsc_clicks - a.gsc_clicks);++ return truncateRows(correlated, limit ?? 30);+ },+);diff --git a/apps/api/src/agents/tools/session.ts b/apps/api/src/agents/tools/session.tsnew file mode 100644index 000000000..d4670d72e--- /dev/null+++ b/apps/api/src/agents/tools/session.ts@@ -0,0 +1,258 @@+import { z } from 'zod';+import {+ queryEventsCore,+ querySessionsCore,+ sessionService,+} from '@openpanel/db';+import { chatTool, dashboardUrl, truncateRows } from './helpers';++export const getSessionFull = chatTool(+ {+ name: 'get_session_full',+ description:+ 'One-shot session deep dive: session data + ordered events + path. CALL THIS FIRST for "what happened in this session".',+ schema: z.object({+ sessionId: z.string().optional(),+ }),+ },+ async ({ sessionId }, context) => {+ const id = sessionId || context.pageContext?.ids?.sessionId || '';+ const [session, events] = await Promise.all([+ sessionService.byId(id, context.projectId),+ queryEventsCore({+ projectId: context.projectId,+ sessionId: id,+ limit: 100,+ }),+ ]);++ const screenViews = events+ .filter((e) => e.name === 'screen_view' && e.path)+ .map((e) => ({ path: e.path, created_at: e.created_at }));++ return {+ session,+ event_count: events.length,+ path_length: screenViews.length,+ path: screenViews,+ events: events.slice(0, 50),+ dashboard_url: dashboardUrl(context.organizationId, context.projectId, `/sessions/${id}`),+ };+ },+);++export const getSessionPath = chatTool(+ {+ name: 'get_session_path',+ description:+ 'The chronological list of pages visited in this session.',+ schema: z.object({+ sessionId: z.string().optional(),+ }),+ },+ async ({ sessionId }, context) => {+ const id = sessionId || context.pageContext?.ids?.sessionId || '';+ const events = await queryEventsCore({+ projectId: context.projectId,+ sessionId: id,+ eventNames: ['screen_view'],+ limit: 100,+ });+ const path = events+ .filter((e) => e.path)+ .map((e) => ({+ path: e.path,+ origin: e.origin,+ created_at: e.created_at,+ }));+ return { sessionId: id, page_count: path.length, path };+ },+);++export const getSessionEvents = chatTool(+ {+ name: 'get_session_events',+ description:+ 'All events in this session, optionally filtered by event name.',+ schema: z.object({+ sessionId: z.string().optional(),+ eventNames: z.array(z.string()).optional(),+ }),+ },+ async ({ sessionId, eventNames }, context) => {+ const id = sessionId || context.pageContext?.ids?.sessionId || '';+ const events = await queryEventsCore({+ projectId: context.projectId,+ sessionId: id,+ eventNames,+ limit: 100,+ });+ return truncateRows(events, 100);+ },+);++export const getSimilarSessions = chatTool(+ {+ name: 'get_similar_sessions',+ description:+ 'Find sessions with similar device + country + entry path to this one. Returns up to 10. Useful for "is this typical?" questions.',+ schema: z.object({+ sessionId: z.string().optional(),+ limit: z.number().min(1).max(20).default(10).optional(),+ }),+ },+ async ({ sessionId, limit }, context) => {+ const id = sessionId || context.pageContext?.ids?.sessionId || '';+ const session = await sessionService.byId(id, context.projectId);++ const similar = await querySessionsCore({+ projectId: context.projectId,+ country: session.country ?? undefined,+ device: session.device ?? undefined,+ limit: (limit ?? 10) + 1,+ });+ // Drop the session itself+ const filtered = similar.filter((s) => s.id !== id).slice(0, limit ?? 10);++ return {+ reference: {+ id: session.id,+ country: session.country,+ device: session.device,+ entryPath: session.entryPath,+ },+ similar_sessions: filtered.map((s) => ({+ ...s,+ dashboard_url: dashboardUrl(context.organizationId, context.projectId, `/sessions/${s.id}`),+ })),+ };+ },+);++export const compareSessionToTypical = chatTool(+ {+ name: 'compare_session_to_typical',+ description:+ 'Compare this session\'s duration / event count / screen views against the project averages. Helps spot outliers.',+ schema: z.object({+ sessionId: z.string().optional(),+ }),+ },+ async ({ sessionId }, context) => {+ const id = sessionId || context.pageContext?.ids?.sessionId || '';+ const session = await sessionService.byId(id, context.projectId);++ // Sample recent sessions to compute project averages.+ const sample = await querySessionsCore({+ projectId: context.projectId,+ limit: 100,+ });+ if (sample.length === 0) {+ return { session, comparison: null };+ }++ const avg = (sel: (s: typeof sample[number]) => number) =>+ sample.reduce((s, sess) => s + sel(sess), 0) / sample.length;++ const project_avg = {+ duration: avg((s) => s.duration),+ event_count: avg((s) => s.event_count),+ screen_view_count: avg((s) => s.screen_view_count),+ };++ const ratio = (a: number, b: number) => {+ if (b === 0) return { ratio: 0, label: 'equal' as const };+ const r = a / b;+ return {+ ratio: Number(r.toFixed(2)),+ label: r > 1.05 ? ('above' as const) : r < 0.95 ? ('below' as const) : ('equal' as const),+ };+ };++ return {+ session: {+ id: session.id,+ duration: session.duration,+ event_count: session.eventCount,+ screen_view_count: session.screenViewCount,+ is_bounce: session.isBounce,+ },+ project_avg,+ comparison: {+ duration: ratio(session.duration, project_avg.duration),+ event_count: ratio(session.eventCount, project_avg.event_count),+ screen_view_count: ratio(+ session.screenViewCount,+ project_avg.screen_view_count,+ ),+ },+ sample_size: sample.length,+ };+ },+);++export const getSessionReferrerContext = chatTool(+ {+ name: 'get_session_referrer_context',+ description:+ 'Context about how the user arrived: total traffic this period from the same referrer, plus a few sample sessions from that referrer.',+ schema: z.object({+ sessionId: z.string().optional(),+ }),+ },+ async ({ sessionId }, context) => {+ const id = sessionId || context.pageContext?.ids?.sessionId || '';+ const session = await sessionService.byId(id, context.projectId);++ if (!session.referrer && !session.referrerName) {+ return {+ session_id: id,+ referrer: null,+ note: 'This session has no referrer (direct traffic).',+ };+ }++ const fromSameReferrer = await querySessionsCore({+ projectId: context.projectId,+ referrerName: session.referrerName ?? undefined,+ limit: 20,+ });++ return {+ session_id: id,+ referrer: session.referrer,+ referrer_name: session.referrerName,+ referrer_type: session.referrerType,+ total_from_referrer: fromSameReferrer.length,+ sample_sessions: fromSameReferrer.slice(0, 5).map((s) => ({+ id: s.id,+ created_at: s.created_at,+ country: s.country,+ is_bounce: s.is_bounce,+ entry_path: s.entry_path,+ })),+ };+ },+);++export const getSessionReplaySummary = chatTool(+ {+ name: 'get_session_replay_summary',+ description:+ 'Whether this session has a recorded replay available. Returns metadata if so. If no replay, returns { available: false }.',+ schema: z.object({+ sessionId: z.string().optional(),+ }),+ },+ async ({ sessionId }, context) => {+ const id = sessionId || context.pageContext?.ids?.sessionId || '';+ const session = await sessionService.byId(id, context.projectId);+ return {+ session_id: id,+ available: session.hasReplay ?? false,+ replay_url: session.hasReplay+ ? dashboardUrl(context.organizationId, context.projectId, `/sessions/${id}`)+ : null,+ };+ },+);diff --git a/apps/api/src/agents/tools/ui.ts b/apps/api/src/agents/tools/ui.tsnew file mode 100644index 000000000..38ed3cc20--- /dev/null+++ b/apps/api/src/agents/tools/ui.ts@@ -0,0 +1,55 @@+import { type AgentToolDefinition, defineTool } from '@better-agent/core';+import {+ applyFiltersSchema,+ setEventNamesFilterSchema,+ setPropertyFiltersSchema,+} from '@openpanel/validation';++/**+ * Client-side UI-mutator tools.+ *+ * Better Agent emits each call as a `tool-call` part with no server+ * execution; the frontend (`useAgent({ toolHandlers })`) handles them+ * by updating the URL params the dashboard's hooks read. Zod schemas+ * are imported from `@openpanel/validation` so the frontend handler+ * types stay in sync with what the LLM calls.+ */++// Cast to `any` before `.client()` for the same reason `chatTool`+// does in `helpers.ts`: TS otherwise fully instantiates+// `ClientToolDefinition<TSchema, ...>` for the deeply-nested Zod+// schema and trips its instantiation depth limit. The runtime is+// fine; the AgentToolDefinition cast on the way out restores a+// usable type for downstream code.+// biome-ignore lint/suspicious/noExplicitAny: see comment above+const applyFiltersContract: any = defineTool({+ name: 'apply_filters',+ description:+ "Apply filters to the user's current dashboard page. Use this whenever the user asks to change the date range, interval, or otherwise filter the view (e.g. 'filter to 24-28 May', 'show last 7 days', 'switch to weekly intervals'). Pair with prose like 'Done — showing 24-28 May.' Only one of `range` (a preset) OR `startDate`+`endDate` (a custom range) should be set, not both.",+ schema: applyFiltersSchema,+});++export const applyFilters: AgentToolDefinition =+ applyFiltersContract.client() as AgentToolDefinition;++// biome-ignore lint/suspicious/noExplicitAny: see comment on applyFiltersContract+const setPropertyFiltersContract: any = defineTool({+ name: 'set_property_filters',+ description:+ "Replace the active event-property filter set on the user's current dashboard page (overview, pages, seo, events, insights, profile detail). Use for requests like 'show me referrers from GitHub', 'mobile only', 'filter to Sweden + Germany', or 'add Bing as a referrer' — for the add case, pass the new full list including what's already active (the current filters are in pageContext.filters.eventFilters). Pass an empty array to clear all property filters.",+ schema: setPropertyFiltersSchema,+});++export const setPropertyFilters: AgentToolDefinition =+ setPropertyFiltersContract.client() as AgentToolDefinition;++// biome-ignore lint/suspicious/noExplicitAny: see comment on applyFiltersContract+const setEventNamesFilterContract: any = defineTool({+ name: 'set_event_names_filter',+ description:+ "Restrict the page to specific event names (e.g. 'show me only signups', 'just screen_view + click events'). Pass the FULL list of event names — replaces the current set. Pass an empty array to clear (show all events). Verify event names with list_event_names when unsure.",+ schema: setEventNamesFilterSchema,+});++export const setEventNamesFilter: AgentToolDefinition =+ setEventNamesFilterContract.client() as AgentToolDefinition;diff --git a/apps/api/src/app.ts b/apps/api/src/app.tsindex 738b5cc87..d772c3f64 100644--- a/apps/api/src/app.ts+++ b/apps/api/src/app.ts@@ -34,7 +34,15 @@ import { ipHook } from './hooks/ip.hook';import { requestIdHook } from './hooks/request-id.hook';import { requestLoggingHook } from './hooks/request-logging.hook';import { timestampHook } from './hooks/timestamp.hook';-import aiRouter from './routes/ai.router';+import { toFastifyHandler } from '@better-agent/adapters';+import { chatApp } from './agents/app';+import { chatRunContext } from './agents/run-context';+import {+ db,+ getConversationById,+ getOrganizationByProjectIdCached,+ getProjectAccess,+} from '@openpanel/db';import eventRouter from './routes/event.router';import exportRouter from './routes/export.router';import gscCallbackRouter from './routes/gsc-callback.router';@@ -87,21 +95,25 @@ export async function buildApp(fastify.setValidatorCompiler(validatorCompiler);fastify.setSerializerCompiler(serializerCompiler);+ // Env is read once at startup — changing CORS origins requires a+ // restart, which is already true for every other env-driven piece+ // of the server.+ const dashboardOrigins = [+ process.env.DASHBOARD_URL || process.env.NEXT_PUBLIC_DASHBOARD_URL,+ ...(process.env.API_CORS_ORIGINS?.split(',') ?? []),+ ].filter(Boolean) as string[];+ const corsPaths = ['/trpc', '/live', '/webhook', '/oauth', '/misc', '/ai'];+fastify.register(cors, () => {return (req: FastifyRequest,callback: (error: Error | null, options: FastifyCorsOptions) => void,) => {- const corsPaths = ['/trpc', '/live', '/webhook', '/oauth', '/misc', '/ai'];const isPrivatePath = corsPaths.some((p) => req.url.startsWith(p));if (isPrivatePath) {- const allowedOrigins = [- process.env.DASHBOARD_URL || process.env.NEXT_PUBLIC_DASHBOARD_URL,- ...(process.env.API_CORS_ORIGINS?.split(',') ?? []),- ].filter(Boolean);const origin = req.headers.origin;- const isAllowed = origin && allowedOrigins.includes(origin);+ const isAllowed = origin && dashboardOrigins.includes(origin);return callback(null, { origin: isAllowed ? origin : false, credentials: true });}@@ -176,7 +188,120 @@ export async function buildApp(instance.register(oauthRouter, { prefix: '/oauth' });instance.register(gscCallbackRouter, { prefix: '/gsc' });instance.register(miscRouter, { prefix: '/misc' });- instance.register(aiRouter, { prefix: '/ai' });+ // Better Agent chat, mounted under /ai/agents/*.+ //+ // The wrapper does three things before delegating to the Better+ // Agent handler:+ // 1. Sets CORS headers on `reply.raw` (survives `reply.hijack()`+ // which bypasses @fastify/cors's onSend hook)+ // 2. Validates the session + project access (the user-visible+ // POST /run body carries `context.projectId` ++ // `context.organizationId`)+ // 3. Wraps the handler call in `chatRunContext.run(...)` so the+ // Prisma conversation-store can upsert the `Conversation`+ // row with the right owner on first save+ //+ // Preflight OPTIONS is handled by @fastify/cors before this route+ // runs, so we only skip auth/ALS for that case.+ {+ const agentHandler = toFastifyHandler(chatApp);++ instance.all('/ai/agents/*', async (request, reply) => {+ const origin = request.headers.origin;+ if (origin && dashboardOrigins.includes(origin)) {+ reply.raw.setHeader('Access-Control-Allow-Origin', origin);+ reply.raw.setHeader('Access-Control-Allow-Credentials', 'true');+ reply.raw.setHeader('Vary', 'Origin');+ }++ // OPTIONS preflight is already handled by @fastify/cors.+ if (request.method === 'OPTIONS') {+ return agentHandler(request, reply);+ }++ const userId = request.session?.session?.userId;+ if (!userId) {+ return reply.status(401).send({ message: 'Sign in required' });+ }++ // Parse the URL tail that comes after `/ai/agents/`.+ // Examples:+ // "claude-sonnet-4-5/run" → run+ // "claude-sonnet-4-5/conversations/abc" → load conversation+ // "__titler/run" → title stream (no project context)+ const wildcard =+ (request.params as { '*'?: string })['*'] ?? '';+ const segments = wildcard.split('/').filter(Boolean);+ const agentName = segments[0] ?? '';+ const route = segments[1] ?? '';+ const routeId = segments[2] ?? '';++ // The internal `__titler` agent has no project context — skip+ // the access check; session auth is enough.+ if (agentName === '__titler') {+ return agentHandler(request, reply);+ }++ // Conversation hydration: `GET /:name/conversations/:id` and+ // `GET /:name/conversations/:id/resume`. If the row exists,+ // verify ownership. If it doesn't exist yet (brand-new chat+ // the client is opening for the first time), let the agent+ // handler respond — its ConversationStore.load() returns null+ // and the adapter maps that to a 204, which Better Agent's+ // client treats as "no saved history". Returning 404 here+ // would instead put `useAgent` in an error state and block+ // the first send.+ if (route === 'conversations' && routeId) {+ const conv = await getConversationById(routeId);+ if (conv && conv.userId !== userId) {+ return reply+ .status(404)+ .send({ message: 'Conversation not found' });+ }+ return agentHandler(request, reply);+ }++ // Everything else (primarily `POST /:name/run`) is an active+ // run and must carry `context.projectId` + `context.organizationId`.+ const body = request.body as+ | { context?: { projectId?: string; organizationId?: string } }+ | null+ | undefined;+ const projectId = body?.context?.projectId;+ const organizationIdFromBody = body?.context?.organizationId;++ if (!projectId || !organizationIdFromBody) {+ return reply.status(400).send({+ message: 'Missing projectId or organizationId in context',+ });+ }++ const [access, organization] = await Promise.all([+ getProjectAccess({ projectId, userId }),+ getOrganizationByProjectIdCached(projectId),+ ]);+ if (+ !access ||+ !organization ||+ organization.id !== organizationIdFromBody+ ) {+ return reply+ .status(403)+ .send({ message: 'No access to this project' });+ }++ // The conversation row is created lazily: the agent's+ // `ConversationStore.save()` upserts on first save, and the+ // TRPC `conversation.rename` endpoint upserts when the titler+ // finishes first. Either path ends up with the correct owner+ // — no eager upsert needed here.++ return chatRunContext.run(+ { userId, projectId, organizationId: organization.id },+ () => agentHandler(request, reply),+ );+ });+ }instance.register(mcpRouter, { prefix: '/mcp' });});diff --git a/apps/api/src/controllers/ai.controller.ts b/apps/api/src/controllers/ai.controller.tsdeleted file mode 100644index 02ede1cee..000000000--- a/apps/api/src/controllers/ai.controller.ts+++ /dev/null@@ -1,134 +0,0 @@-import { getChatModel, getChatSystemPrompt } from '@/utils/ai';-import {- getAllEventNames,- getConversionReport,- getFunnelReport,- getProfile,- getProfiles,- getReport,-} from '@/utils/ai-tools';-import { HttpError } from '@/utils/errors';-import { db, getOrganizationByProjectIdCached } from '@openpanel/db';-import { getProjectAccess } from '@openpanel/trpc/src/access';-import { type Message, appendResponseMessages, streamText } from 'ai';-import type { FastifyReply, FastifyRequest } from 'fastify';--export async function chat(- request: FastifyRequest<{- Querystring: {- projectId: string;- };- Body: {- messages: Message[];- };- }>,- reply: FastifyReply,-) {- const { session } = request.session;- const { messages } = request.body;- const { projectId } = request.query;-- if (!session?.userId) {- return reply.status(401).send('Unauthorized');- }-- if (!projectId) {- return reply.status(400).send('Missing projectId');- }-- const organization = await getOrganizationByProjectIdCached(projectId);- const access = await getProjectAccess({- projectId,- userId: session.userId,- });-- if (!organization) {- throw new HttpError('Organization not found', {- status: 404,- });- }-- if (!access) {- throw new HttpError('You are not allowed to access this project', {- status: 403,- });- }-- if (organization?.isExceeded) {- throw new HttpError('Organization has exceeded its limits', {- status: 403,- });- }-- if (organization?.isCanceled) {- throw new HttpError('Organization has been canceled', {- status: 403,- });- }-- const systemPrompt = getChatSystemPrompt({- projectId,- });-- try {- const result = streamText({- model: getChatModel(),- messages: messages.slice(-4),- maxSteps: 2,- tools: {- getAllEventNames: getAllEventNames({- projectId,- }),- getReport: getReport({- projectId,- }),- getConversionReport: getConversionReport({- projectId,- }),- getFunnelReport: getFunnelReport({- projectId,- }),- getProfiles: getProfiles({- projectId,- }),- getProfile: getProfile({- projectId,- }),- },- toolCallStreaming: false,- system: systemPrompt,- onFinish: async ({ response, usage }) => {- request.log.info('chat usage', { usage });- const messagesToSave = appendResponseMessages({- messages,- responseMessages: response.messages,- });-- await db.chat.deleteMany({- where: {- projectId,- },- });-- await db.chat.create({- data: {- messages: messagesToSave.slice(-10) as any,- projectId,- },- });- },- onError: async (error) => {- request.log.error('chat error', { error });- },- });-- reply.header('X-Vercel-AI-Data-Stream', 'v1');- reply.header('Content-Type', 'text/plain; charset=utf-8');-- return reply.send(result.toDataStream());- } catch (error) {- throw new HttpError('Error during stream processing', {- error,- });- }-}diff --git a/apps/api/src/routes/ai.router.ts b/apps/api/src/routes/ai.router.tsdeleted file mode 100644index e396a2cfb..000000000--- a/apps/api/src/routes/ai.router.ts+++ /dev/null@@ -1,28 +0,0 @@-import * as controller from '@/controllers/ai.controller';-import { activateRateLimiter } from '@/utils/rate-limiter';-import type { FastifyPluginCallback, FastifyRequest } from 'fastify';--const aiRouter: FastifyPluginCallback = async (fastify) => {- await activateRateLimiter<- FastifyRequest<{- Querystring: {- projectId: string;- };- }>- >({- fastify,- max: process.env.NODE_ENV === 'production' ? 20 : 100,- timeWindow: '300 seconds',- keyGenerator: (req) => {- return req.query.projectId;- },- });-- fastify.route({- method: 'POST',- url: '/chat',- handler: controller.chat,- });-};--export default aiRouter;diff --git a/apps/api/src/utils/ai-tools.ts b/apps/api/src/utils/ai-tools.tsdeleted file mode 100644index 70f43d277..000000000--- a/apps/api/src/utils/ai-tools.ts+++ /dev/null@@ -1,484 +0,0 @@-import { chartTypes } from '@openpanel/constants';-import type { IClickhouseSession } from '@openpanel/db';-import {- type IClickhouseEvent,- type IClickhouseProfile,- TABLE_NAMES,- ch,- clix,-} from '@openpanel/db';-import { ChartEngine } from '@openpanel/db';-import { getCache } from '@openpanel/redis';-import { zReportInput } from '@openpanel/validation';-import { tool } from 'ai';-import { z } from 'zod';--export function getReport({- projectId,-}: {- projectId: string;-}) {- return tool({- description: `Generate a report (a chart) for- - ${chartTypes.area}- - ${chartTypes.linear}- - ${chartTypes.pie}- - ${chartTypes.histogram}- - ${chartTypes.metric}- - ${chartTypes.bar}-`,- parameters: zReportInput.extend({- startDate: z.string().describe('The start date for the report'),- endDate: z.string().describe('The end date for the report'),- }),- execute: async (report) => {- return {- type: 'report',- report: {- ...report,- projectId,- },- };- // try {- // const data = await getChart({- // ...report,- // projectId,- // });-- // return {- // type: 'report',- // data: `Avg: ${data.metrics.average}, Min: ${data.metrics.min}, Max: ${data.metrics.max}, Sum: ${data.metrics.sum}- // X-Axis: ${data.series[0]?.data.map((i) => i.date).join(',')}- // Series:- // ${data.series- // .slice(0, 5)- // .map((item) => {- // return `- ${item.names.join(' ')} | Sum: ${item.metrics.sum} | Avg: ${item.metrics.average} | Min: ${item.metrics.min} | Max: ${item.metrics.max} | Data: ${item.data.map((i) => i.count).join(',')}`;- // })- // .join('\n')}- // `,- // report,- // };- // } catch (error) {- // return {- // error: 'Failed to generate report',- // };- // }- },- });-}-export function getConversionReport({- projectId,-}: {- projectId: string;-}) {- return tool({- description:- 'Generate a report (a chart) for conversions between two actions a unique user took.',- parameters: zReportInput.extend({- startDate: z.string().describe('The start date for the report'),- endDate: z.string().describe('The end date for the report'),- }),- execute: async (report) => {- return {- type: 'report',- // data: await conversionService.getConversion(report),- report: {- ...report,- projectId,- chartType: 'conversion',- },- };- },- });-}-export function getFunnelReport({- projectId,-}: {- projectId: string;-}) {- return tool({- description:- 'Generate a report (a chart) for funnel between two or more actions a unique user (session_id or profile_id) took.',- parameters: zReportInput.extend({- startDate: z.string().describe('The start date for the report'),- endDate: z.string().describe('The end date for the report'),- }),- execute: async (report) => {- return {- type: 'report',- // data: await funnelService.getFunnel(report),- report: {- ...report,- projectId,- chartType: 'funnel',- },- };- },- });-}--export function getProfiles({- projectId,-}: {- projectId: string;-}) {- return tool({- description: 'Get profiles',- parameters: z.object({- projectId: z.string(),- limit: z.number().optional(),- email: z.string().optional(),- firstName: z.string().optional(),- lastName: z.string().optional(),- country: z.string().describe('ISO 3166-1 alpha-2').optional(),- city: z.string().optional(),- region: z.string().optional(),- device: z.string().optional(),- browser: z.string().optional(),- }),- execute: async (input) => {- const builder = clix(ch)- .select<IClickhouseProfile>([- 'id',- 'email',- 'first_name',- 'last_name',- 'properties',- ])- .from(TABLE_NAMES.profiles)- .where('project_id', '=', projectId);-- if (input.email) {- builder.where('email', 'LIKE', `%${input.email}%`);- }-- if (input.firstName) {- builder.where('first_name', 'LIKE', `%${input.firstName}%`);- }-- if (input.lastName) {- builder.where('last_name', 'LIKE', `%${input.lastName}%`);- }-- if (input.country) {- builder.where(`properties['country']`, '=', input.country);- }-- if (input.city) {- builder.where(`properties['city']`, '=', input.city);- }-- if (input.region) {- builder.where(`properties['region']`, '=', input.region);- }-- if (input.device) {- builder.where(`properties['device']`, '=', input.device);- }-- if (input.browser) {- builder.where(`properties['browser']`, '=', input.browser);- }-- const profiles = await builder.limit(input.limit ?? 5).execute();-- return profiles;- },- });-}--export function getProfile({- projectId,-}: {- projectId: string;-}) {- return tool({- description: 'Get a specific profile',- parameters: z.object({- projectId: z.string(),- email: z.string().optional(),- firstName: z.string().optional(),- lastName: z.string().optional(),- country: z.string().describe('ISO 3166-1 alpha-2').optional(),- city: z.string().optional(),- region: z.string().optional(),- device: z.string().optional(),- browser: z.string().optional(),- }),- execute: async (input) => {- const builder = clix(ch)- .select<IClickhouseProfile>([- 'id',- 'email',- 'first_name',- 'last_name',- 'properties',- ])- .from(TABLE_NAMES.profiles)- .where('project_id', '=', projectId);-- if (input.email) {- builder.where('email', 'LIKE', `%${input.email}%`);- }-- if (input.firstName) {- builder.where('first_name', 'LIKE', `%${input.firstName}%`);- }-- if (input.lastName) {- builder.where('last_name', 'LIKE', `%${input.lastName}%`);- }-- if (input.country) {- builder.where(`properties['country']`, '=', input.country);- }-- if (input.city) {- builder.where(`properties['city']`, '=', input.city);- }-- if (input.region) {- builder.where(`properties['region']`, '=', input.region);- }-- if (input.device) {- builder.where(`properties['device']`, '=', input.device);- }-- if (input.browser) {- builder.where(`properties['browser']`, '=', input.browser);- }-- const profiles = await builder.limit(1).execute();-- const profile = profiles[0];- if (!profile) {- return {- error: 'Profile not found',- };- }-- const events = await clix(ch)- .select<IClickhouseEvent>([])- .from(TABLE_NAMES.events)- .where('project_id', '=', input.projectId)- .where('profile_id', '=', profile.id)- .limit(5)- .orderBy('created_at', 'DESC')- .execute();-- return {- profile,- events,- };- },- });-}--export function getEvents({- projectId,-}: {- projectId: string;-}) {- return tool({- description: 'Get events for a project or specific profile',- parameters: z.object({- projectId: z.string(),- profileId: z.string().optional(),- take: z.number().optional().default(10),- eventNames: z.array(z.string()).optional(),- referrer: z.string().optional(),- referrerName: z.string().optional(),- referrerType: z.string().optional(),- device: z.string().optional(),- country: z.string().optional(),- city: z.string().optional(),- os: z.string().optional(),- browser: z.string().optional(),- properties: z.record(z.string(), z.string()).optional(),- startDate: z.string().optional().describe('ISO date string'),- endDate: z.string().optional().describe('ISO date string'),- }),- execute: async (input) => {- const builder = clix(ch)- .select<IClickhouseEvent>([])- .from(TABLE_NAMES.events)- .where('project_id', '=', projectId);-- if (input.profileId) {- builder.where('profile_id', '=', input.profileId);- }-- if (input.eventNames) {- builder.where('name', 'IN', input.eventNames);- }-- if (input.referrer) {- builder.where('referrer', '=', input.referrer);- }-- if (input.referrerName) {- builder.where('referrer_name', '=', input.referrerName);- }-- if (input.referrerType) {- builder.where('referrer_type', '=', input.referrerType);- }-- if (input.device) {- builder.where('device', '=', input.device);- }-- if (input.country) {- builder.where('country', '=', input.country);- }-- if (input.city) {- builder.where('city', '=', input.city);- }-- if (input.os) {- builder.where('os', '=', input.os);- }-- if (input.browser) {- builder.where('browser', '=', input.browser);- }-- if (input.properties) {- for (const [key, value] of Object.entries(input.properties)) {- builder.where(`properties['${key}']`, '=', value);- }- }-- if (input.startDate && input.endDate) {- builder.where('created_at', 'BETWEEN', [- clix.datetime(input.startDate),- clix.datetime(input.endDate),- ]);- } else {- builder.where('created_at', 'BETWEEN', [- clix.datetime(new Date(Date.now() - 1000 * 60 * 60 * 24 * 7)),- clix.datetime(new Date()),- ]);- }-- return await builder.limit(input.take).execute();- },- });-}--export function getSessions({- projectId,-}: {- projectId: string;-}) {- return tool({- description: 'Get sessions for a project or specific profile',- parameters: z.object({- projectId: z.string(),- profileId: z.string().optional(),- take: z.number().optional().default(10),- referrer: z.string().optional(),- referrerName: z.string().optional(),- referrerType: z.string().optional(),- device: z.string().optional(),- country: z.string().optional(),- city: z.string().optional(),- os: z.string().optional(),- browser: z.string().optional(),- properties: z.record(z.string(), z.string()).optional(),- startDate: z.string().optional().describe('ISO date string'),- endDate: z.string().optional().describe('ISO date string'),- }),- execute: async (input) => {- const builder = clix(ch)- .select<IClickhouseSession>([])- .from(TABLE_NAMES.sessions)- .where('project_id', '=', projectId)- .where('sign', '=', 1);-- if (input.profileId) {- builder.where('profile_id', '=', input.profileId);- }-- if (input.referrer) {- builder.where('referrer', '=', input.referrer);- }-- if (input.referrerName) {- builder.where('referrer_name', '=', input.referrerName);- }-- if (input.referrerType) {- builder.where('referrer_type', '=', input.referrerType);- }-- if (input.device) {- builder.where('device', '=', input.device);- }-- if (input.country) {- builder.where('country', '=', input.country);- }-- if (input.city) {- builder.where('city', '=', input.city);- }-- if (input.os) {- builder.where('os', '=', input.os);- }-- if (input.browser) {- builder.where('browser', '=', input.browser);- }-- if (input.properties) {- for (const [key, value] of Object.entries(input.properties)) {- builder.where(`properties['${key}']`, '=', value);- }- }-- if (input.startDate && input.endDate) {- builder.where('created_at', 'BETWEEN', [- clix.datetime(input.startDate),- clix.datetime(input.endDate),- ]);- } else {- builder.where('created_at', 'BETWEEN', [- clix.datetime(new Date(Date.now() - 1000 * 60 * 60 * 24 * 7)),- clix.datetime(new Date()),- ]);- }-- return await builder.limit(input.take).execute();- },- });-}--export function getAllEventNames({- projectId,-}: {- projectId: string;-}) {- return tool({- description: 'Get the top 50 event names in a comma separated list',- parameters: z.object({}),- execute: async () => {- return getCache(`top-event-names:${projectId}`, 60 * 10, async () => {- const events = await clix(ch)- .select<IClickhouseEvent>(['name', 'count() as count'])- .from(TABLE_NAMES.event_names_mv)- .where('project_id', '=', projectId)- .groupBy(['name'])- .orderBy('count', 'DESC')- .limit(50)- .execute();-- return events.map((event) => event.name).join(',');- });- },- });-}diff --git a/apps/api/src/utils/ai.ts b/apps/api/src/utils/ai.tsdeleted file mode 100644index 0fcf69de3..000000000--- a/apps/api/src/utils/ai.ts+++ /dev/null@@ -1,115 +0,0 @@-import { anthropic } from '@ai-sdk/anthropic';-import { openai } from '@ai-sdk/openai';-import { chartTypes, operators, timeWindows } from '@openpanel/constants';-import { mapKeys } from '@openpanel/validation';--export const getChatModel = () => {- switch (process.env.AI_MODEL) {- case 'gpt-4o':- return openai('gpt-4o');- case 'claude-3-5':- return anthropic('claude-3-5-haiku-latest');- default:- return openai('gpt-4.1-mini');- }-};--export const getChatSystemPrompt = ({- projectId,-}: {- projectId: string;-}) => {- return `You're an product and web analytics expert. Don't generate more than the user asks for. Follow all rules listed below!-## General:-- projectId: \`${projectId}\`-- Do not hallucinate, if you can't make a report based on the user's request, just say so.-- Today is ${new Date().toISOString()}-- \`range\` should always be \`custom\`- - if range is \`custom\`, make sure to have \`startDate\` and \`endDate\`-- Available intervals: ${Object.values(timeWindows)- .map((t) => t.key)- .join(', ')}-- Try to figure out a time window, ${Object.values(timeWindows)- .map((t) => t.key)- .join(', ')}. If no match always use \`custom\` with a start and end date.-- Pick corresponding chartType from \`${Object.keys(chartTypes).join(', ')}\`, match with your best effort.-- Always add a name to the report.-- Never do a summary!--### Formatting-- Never generate images-- If you use katex, please wrap the equation in $$-- Use tables when showing lists of data.--### Events-- Tool: \`getAllEventNames\`, use this tool *before* calling any other tool if the user's request mentions an event but you are unsure of the exact event name stored in the system. Only call this once!-- \`screen_view\` is a page view event-- If you see any paths you should pick \`screen_view\` event and use a \`path\` filter-- To find referrers you can use \`referrer\`, \`referrer_name\` and \`referrer_type\` columns-- Use unique IDs for each event and each filter--### Filters-- If you see a '*' in the filters value, depending on where it is you can split it up and do 'startsWith' together with 'endsWith'. Eg: '/path/*' -> 'path startsWith /path/', or '*/path' -> 'path endsWith /path/', or '/path/*/something' -> 'path startsWith /path/ and endsWith /something'-- If user asks for several events you can use this tool once (with all events)- - Example: path is /path/*/something \`{"id":"1","name":"screen_view","displayName":"Path is something","segment":"user","filters":[{"id":"1","name":"path","operator":"startsWith","value":["/path/"]},{"id":"1","name":"path","operator":"endsWith","value":["/something"]}]}\`-- Other examples for filters:- - Available operators: ${mapKeys(operators).join(', ')}- - {"id":"1","name":"path","operator":"endsWith","value":["/foo", "/bar"]}- - {"id":"1","name":"path","operator":"isNot","value":["/","/a","/b"]}- - {"id":"1","name":"path","operator":"contains","value":["nuke"]}- - {"id":"1","name":"path","operator":"regex","value":["/onboarding/.+/verify/?"]}- - {"id":"1","name":"path","operator":"isNull","value":[]}--## Conversion Report--Tool: \`getConversionReport\`-Rules:-- Use this when ever a user wants any conversion rate over time.-- Needs two events--## Funnel Report--Tool: \`getFunnelReport\`-Rules:-- Use this when ever a user wants to see a funnel between two or more events.-- Needs two or more events--## Other reports--Tool: \`getReport\`-Rules:-- Use this when ever a user wants any other report than a conversion, funnel or retention.--### Examples--#### Active users the last 30min-\`\`\`-{"events":[{"id":"1","name":"*","displayName":"Active users","segment":"user","filters":[{"id":"1","name":"name","operator":"is","value":["screen_view","session_start"]}]}],"breakdowns":[]}-\`\`\`--#### How to get most events with breakdown by title-\`\`\`-{"events":[{"id":"1","name":"screen_view","segment":"event","filters":[{"id":"1","name":"path","operator":"is","value":["Article"]}]}],"breakdowns":[{"id":"1","name":"properties.params.title"}]}-\`\`\`--#### Get popular referrers-\`\`\`-{"events":[{"id":"1","name":"session_start","segment":"event","filters":[]}],"breakdowns":[{"id":"1","name":"referrer_name"}]}-\`\`\`--#### Popular screen views-\`\`\`-{"chartType":"bar","events":[{"id":"1","name":"screen_view","segment":"event","filters":[]}],"breakdowns":[{"id":"1","name":"path"}]}-\`\`\`--#### Popular screen views from X,Y,Z referrers-\`\`\`-{"chartType":"bar","events":[{"id":"1","name":"screen_view","segment":"event","filters":[{"id":"1","name":"referrer_name","operator":"is","value":["Google","Bing","Yahoo!"]}]}],"breakdowns":[{"id":"1","name":"path"}]}-\`\`\`--#### Bounce rate (use session_end together with formula)-\`\`\`-{"chartType":"linear","formula":"B/A*100","events":[{"id":"1","name":"session_end","segment":"event","filters":[]},{"id":"2","name":"session_end","segment":"event","filters":[{"id":"3","name":"properties.__bounce","operator":"is","value":["true"]}]}],"breakdowns":[]}-\`\`\`-`;-};diff --git a/apps/start/package.json b/apps/start/package.jsonindex 391e9f4bc..bf155b7ef 100644--- a/apps/start/package.json+++ b/apps/start/package.json@@ -17,7 +17,7 @@"with-env": "dotenv -e ../../.env -c --"},"dependencies": {- "@ai-sdk/react": "^1.2.5",+ "@better-agent/client": "^0.1.0-beta.3","@codemirror/commands": "^6.7.0","@codemirror/lang-javascript": "^6.2.0","@codemirror/lang-json": "^6.0.1",@@ -88,7 +88,6 @@"@trpc/server": "^11.6.0","@trpc/tanstack-react-query": "^11.6.0","@types/d3": "^7.4.3",- "ai": "^4.2.10","bind-event-listener": "^3.0.0","class-variance-authority": "^0.7.1","clsx": "^2.1.1",@@ -151,6 +150,7 @@"tailwindcss": "^4.0.6","tailwindcss-animate": "^1.0.7","tw-animate-css": "^1.3.6",+ "use-stick-to-bottom": "^1.1.3","usehooks-ts": "^2.14.0","vite-tsconfig-paths": "^5.1.4","zod": "catalog:"diff --git a/apps/start/src/agents/client.ts b/apps/start/src/agents/client.tsnew file mode 100644index 000000000..7c9a61fcc--- /dev/null+++ b/apps/start/src/agents/client.ts@@ -0,0 +1,40 @@+import { createClient } from '@better-agent/client';+import type { ChatApp } from '../../../api/src/agents/app';++/**+ * Typed Better Agent client. The `ChatApp` import surfaces every+ * agent name, every context schema, and every typed tool input — so+ * `useAgent(client, { agent: 'gpt-4-1' })` is autocompleted and+ * validated end-to-end.+ *+ * About the relative import: `ChatApp = typeof chatApp` is the full+ * Better Agent-inferred application type, which inherently binds to+ * the server-side agent definition (models, tools, context). It can't+ * be moved into `@openpanel/validation` without dragging the entire+ * agent definition (DB services, providers, etc.) along with it. It+ * is type-only, erased at build time — no runtime coupling. The+ * shared schemas (context, client tool inputs, model whitelist) live+ * in `@openpanel/validation` so only this one type import crosses+ * the app boundary.+ */+export type AppClient = ReturnType<typeof createClient<ChatApp>>;++let cachedClient: AppClient | null = null;+let cachedBaseURL: string | null = null;++/**+ * Get-or-create the typed Better Agent client. Memoized per `apiUrl` so+ * we don't rebuild on every render. We wrap `fetch` to force+ * `credentials: 'include'` on every request — the auth plugin guard on+ * the server reads the session cookie from the request.+ */+export function getChatClient(apiUrl: string): AppClient {+ if (cachedClient && cachedBaseURL === apiUrl) return cachedClient;+ cachedBaseURL = apiUrl;+ cachedClient = createClient<ChatApp>({+ baseURL: `${apiUrl}/ai/agents`,+ fetch: (input, init) =>+ fetch(input, { ...init, credentials: 'include' }),+ });+ return cachedClient;+}diff --git a/apps/start/src/agents/models.ts b/apps/start/src/agents/models.tsnew file mode 100644index 000000000..36a86688f--- /dev/null+++ b/apps/start/src/agents/models.ts@@ -0,0 +1,11 @@+// Re-export the shared model whitelist from `@openpanel/validation`.+// Server + client consume the same source, so drift is a compile error+// rather than a silent "agent not found at runtime".+export {+ CHAT_MODELS,+ DEFAULT_MODEL_ID,+ MODEL_STORAGE_KEY,+ getModelLabel,+ isValidModelId,+} from '@openpanel/validation';+export type { ChatModelEntry as ChatModelOption } from '@openpanel/validation';diff --git a/apps/start/src/components/chat/chat-context-widget.tsx b/apps/start/src/components/chat/chat-context-widget.tsxnew file mode 100644index 000000000..394420e49--- /dev/null+++ b/apps/start/src/components/chat/chat-context-widget.tsx@@ -0,0 +1,152 @@+import { usePageContextValue } from '@/contexts/page-context';+import { cn } from '@/utils/cn';+import {+ Building2Icon,+ GanttChartIcon,+ LayersIcon,+ LayoutPanelTopIcon,+ type LucideIcon,+ SearchIcon,+ TrendingUpDownIcon,+ UserCircleIcon,+ UsersIcon,+ WallpaperIcon,+} from 'lucide-react';++/**+ * Small banner shown at the top of the chat body explaining what+ * page context the AI is working with. Helps the user understand+ * "the assistant sees this page, this date range, these filters".+ *+ * Renders nothing when there's no useful context to surface.+ */+export function ChatContextWidget() {+ const ctx = usePageContextValue();+ if (!ctx) return null;++ const meta = PAGE_META[ctx.page];+ const Icon = meta?.icon ?? WallpaperIcon;+ const pageLabel = meta?.label ?? ctx.page;++ const chips: string[] = [];++ // Date range+ const range = ctx.filters?.range;+ if (range === 'custom' && ctx.filters?.startDate && ctx.filters?.endDate) {+ chips.push(`${ctx.filters.startDate} → ${ctx.filters.endDate}`);+ } else if (range) {+ chips.push(formatRange(range));+ }++ // Event-name filter+ if (ctx.filters?.eventNames && ctx.filters.eventNames.length > 0) {+ chips.push(`Events: ${ctx.filters.eventNames.join(', ')}`);+ }++ // Property filters — short form: "country=SE,US, device=mobile"+ if (ctx.filters?.eventFilters && ctx.filters.eventFilters.length > 0) {+ for (const f of ctx.filters.eventFilters) {+ const filter = f as {+ name?: string;+ operator?: string;+ value?: unknown[];+ };+ if (!filter.name) continue;+ const op = filter.operator && filter.operator !== 'is'+ ? ` ${filter.operator}`+ : '';+ const value = Array.isArray(filter.value)+ ? filter.value.join(', ')+ : '';+ chips.push(`${filter.name}${op}${value ? `: ${value}` : ''}`);+ }+ }++ // Entity ids on detail pages+ if (ctx.ids?.profileId) chips.push('Profile');+ if (ctx.ids?.sessionId) chips.push('Session');+ if (ctx.ids?.groupId) chips.push('Group');+ if (ctx.ids?.reportId) chips.push('Report');++ return (+ <div className="mx-3 mt-3 mb-1 rounded-lg border bg-card/95 px-3 py-2">+ <div className="flex items-start gap-2">+ <Icon className="size-3.5 mt-0.5 text-muted-foreground shrink-0" />+ <div className="min-w-0 flex-1 col gap-1">+ <div className="text-sm text-muted-foreground">+ Assistant context+ </div>+ <div className="text-sm font-medium text-foreground/90">+ {pageLabel}+ </div>+ {chips.length > 0 && (+ <div className="mt-1.5 flex flex-wrap gap-1">+ {chips.map((chip) => (+ <ContextChip key={chip}>{chip}</ContextChip>+ ))}+ </div>+ )}+ </div>+ </div>+ </div>+ );+}++function ContextChip({ children }: { children: React.ReactNode }) {+ return (+ <span+ className={cn(+ 'inline-flex items-center rounded-md border bg-muted/40 px-1.5 py-0.5',+ 'text-[11px] leading-none text-muted-foreground',+ )}+ >+ {children}+ </span>+ );+}++const PAGE_META: Record<+ string,+ { label: string; icon: LucideIcon }+> = {+ overview: { label: 'Overview', icon: WallpaperIcon },+ insights: { label: 'Insights', icon: TrendingUpDownIcon },+ pages: { label: 'Pages', icon: LayersIcon },+ seo: { label: 'SEO', icon: SearchIcon },+ events: { label: 'Events', icon: GanttChartIcon },+ sessionDetail: { label: 'Session detail', icon: UsersIcon },+ profileDetail: { label: 'Profile detail', icon: UserCircleIcon },+ groupDetail: { label: 'Group detail', icon: Building2Icon },+ reportEditor: { label: 'Report editor', icon: LayoutPanelTopIcon },+};++function formatRange(range: string): string {+ switch (range) {+ case '30min':+ return 'Last 30 min';+ case 'lastHour':+ return 'Last hour';+ case 'today':+ return 'Today';+ case 'yesterday':+ return 'Yesterday';+ case '7d':+ return 'Last 7 days';+ case '30d':+ return 'Last 30 days';+ case '6m':+ return 'Last 6 months';+ case '12m':+ return 'Last 12 months';+ case 'monthToDate':+ return 'Month to date';+ case 'lastMonth':+ return 'Last month';+ case 'yearToDate':+ return 'Year to date';+ case 'lastYear':+ return 'Last year';+ default:+ return range;+ }+}diff --git a/apps/start/src/components/chat/chat-context.tsx b/apps/start/src/components/chat/chat-context.tsxnew file mode 100644index 000000000..bc22e5990--- /dev/null+++ b/apps/start/src/components/chat/chat-context.tsx@@ -0,0 +1,219 @@+import {+ CHAT_MODELS,+ type ChatModelOption,+ DEFAULT_MODEL_ID,+ isValidModelId,+ MODEL_STORAGE_KEY,+} from '@/agents/models';+import {+ createContext,+ type ReactNode,+ useCallback,+ useContext,+ useEffect,+ useMemo,+ useState,+} from 'react';+import { newConversationId, useChatUrlState } from './use-chat-open';++/**+ * Thin global context for chat identifiers. The active conversation+ * id and the drawer's open/closed state both live in the URL (`?chat`)+ * so conversations are linkable and survive navigation. Everything+ * else transient — the selected model, streaming title, pending+ * message for the sidebar composer — stays in React state here.+ *+ * No `useChat` or `useAgent` runs in this provider. The actual chat+ * runtime (`<ChatRuntimeProvider>`) lives inside the drawer and is+ * scoped to it.+ */++type ChatStateValue = {+ /**+ * Active conversation id. Mirrors `?chat` in the URL. When the+ * drawer is closed this is still populated (the next open uses it),+ * but `isOpen` will be false.+ */+ conversationId: string;+ /** True when the `?chat` param is present in the URL. */+ isOpen: boolean;++ /**+ * Open the drawer with a fresh conversation. This is the default+ * "Ask AI" / ⌘J behavior — previously this resumed a per-page+ * conversation from localStorage, but that added a second source of+ * truth next to the URL and was removed. The header's conversation+ * dropdown is the way to resume a prior conversation.+ */+ openChatForContext: () => void;+ /**+ * Start a brand-new conversation in the open drawer. Alias for+ * openChatForContext — kept because several call sites use the+ * name "newChat" for clarity.+ */+ openNewChat: () => void;+ /** Open the drawer on a specific existing conversation id. */+ openChat: (id: string) => void;+ /** Close the drawer (clears `?chat`). */+ closeChat: () => void;+ /** Switch the active conversation (leaves the drawer open). */+ switchConversation: (id: string) => void;+ /**+ * Start a fresh conversation inside the open drawer. Alias for+ * openNewChat — kept for clarity at call sites.+ */+ newConversation: () => void;++ /** Active agent name = model id from the whitelist. */+ agentName: string;+ models: readonly ChatModelOption[];+ setAgent: (agentName: string) => void;++ /**+ * Title being streamed for the active conversation, if any. Flips+ * from null → accumulating deltas → null when either the stream+ * finishes (persisted title takes over) or the conversation+ * switches. The header renders this when non-null, falling back+ * to the persisted title otherwise.+ */+ streamingTitle: string | null;+ setStreamingTitle: (value: string | null) => void;+ /**+ * Message text the user wants to send the next time the chat+ * runtime mounts. The sidebar composer sets this and opens the+ * drawer; the runtime drains it once the agent is ready.+ */+ pendingMessage: string | null;+ setPendingMessage: (text: string | null) => void;+};++const ChatContext = createContext<ChatStateValue | null>(null);++function readStoredAgent(): string {+ if (typeof window === 'undefined') return DEFAULT_MODEL_ID;+ const raw = window.localStorage.getItem(MODEL_STORAGE_KEY);+ return isValidModelId(raw) ? raw : DEFAULT_MODEL_ID;+}++export function ChatStateProvider({ children }: { children: ReactNode }) {+ // URL is the source of truth for the active conversation + drawer+ // open state. `chatParam`:+ // - null → drawer closed+ // - non-empty id → drawer open, on that conversation+ // - '' (empty) → drawer open, needs a new id (we auto-fill below)+ const [chatParam, setChatParam] = useChatUrlState();++ // Fallback local id for first render / SSR when `chatParam` is+ // null. Keeps `conversationId` stable as a non-empty string so+ // `<ChatRuntimeProvider key={conversationId}>` never sees empty.+ // Replaced the moment the user opens the drawer.+ const [ghostId] = useState(() => newConversationId());+ const conversationId = chatParam && chatParam.length > 0 ? chatParam : ghostId;+ const isOpen = chatParam !== null;++ // If the URL says "open with empty id" (e.g. ?chat= from a stale+ // link or legacy boolean param), materialize a fresh conversation.+ useEffect(() => {+ if (chatParam === '') {+ void setChatParam(newConversationId());+ }+ }, [chatParam, setChatParam]);++ const openChatForContext = useCallback(() => {+ void setChatParam(newConversationId());+ }, [setChatParam]);++ const openNewChat = openChatForContext;++ const openChat = useCallback(+ (id: string) => {+ void setChatParam(id);+ },+ [setChatParam],+ );++ const closeChat = useCallback(() => {+ void setChatParam(null);+ }, [setChatParam]);++ const switchConversation = useCallback(+ (id: string) => {+ void setChatParam(id);+ },+ [setChatParam],+ );++ const newConversation = openNewChat;++ // Model selection — persisted to localStorage.+ const [agentName, setAgentNameState] = useState<string>(() =>+ readStoredAgent(),+ );+ const setAgent = useCallback((id: string) => {+ if (!isValidModelId(id)) return;+ setAgentNameState(id);+ if (typeof window !== 'undefined') {+ window.localStorage.setItem(MODEL_STORAGE_KEY, id);+ }+ }, []);++ // Transient session state.+ const [streamingTitle, setStreamingTitle] = useState<string | null>(null);+ const [pendingMessage, setPendingMessage] = useState<string | null>(null);++ // Clear `streamingTitle` when the conversation changes — the title+ // belongs to the prior convo, not the new one.+ //+ // NB: we do NOT clear `pendingMessage` here. The sidebar composer+ // deliberately sets it *before* calling `openNewChat()`, which+ // changes `conversationId`. Clearing here would nuke the pending+ // message between set-and-drain and the new chat would open empty.+ // The runtime drains it as soon as the new `useAgent` is `ready`.+ useEffect(() => {+ setStreamingTitle(null);+ }, [conversationId]);++ const value = useMemo<ChatStateValue>(+ () => ({+ conversationId,+ isOpen,+ openChatForContext,+ openNewChat,+ openChat,+ closeChat,+ switchConversation,+ newConversation,+ agentName,+ models: CHAT_MODELS,+ setAgent,+ streamingTitle,+ setStreamingTitle,+ pendingMessage,+ setPendingMessage,+ }),+ [+ conversationId,+ isOpen,+ openChatForContext,+ openNewChat,+ openChat,+ closeChat,+ switchConversation,+ newConversation,+ agentName,+ setAgent,+ streamingTitle,+ pendingMessage,+ ],+ );++ return <ChatContext.Provider value={value}>{children}</ChatContext.Provider>;+}++export function useChatState(): ChatStateValue {+ const value = useContext(ChatContext);+ if (!value) {+ throw new Error('useChatState must be used inside <ChatStateProvider>');+ }+ return value;+}diff --git a/apps/start/src/components/chat/chat-drawer-body.tsx b/apps/start/src/components/chat/chat-drawer-body.tsxnew file mode 100644index 000000000..2debadf76--- /dev/null+++ b/apps/start/src/components/chat/chat-drawer-body.tsx@@ -0,0 +1,83 @@+import { Button } from '@/components/ui/button';+import { usePageContextValue } from '@/contexts/page-context';+import { cn } from '@/utils/cn';+import { ArrowDownIcon } from 'lucide-react';+import {+ StickToBottom,+ useStickToBottomContext,+} from 'use-stick-to-bottom';+import { ChatContextWidget } from './chat-context-widget';+import { ChatDrawerEmpty } from './chat-drawer-empty';+import { ChatMessage } from './chat-message';+import { useChatRuntime } from './chat-runtime';++/**+ * Message list. Reads `messages`, `status`, `isLoading`, `isStreaming`+ * from `useChatRuntime()` (the Better Agent `useAgent` hook+ * indirected through the runtime provider so the footer can share it).+ *+ * Auto-scrolls to bottom on new content, but stops if the user scrolls+ * up — courtesy of `use-stick-to-bottom`. Zero refs, zero effects.+ */+export function ChatDrawerBody() {+ const { messages, isLoading, isStreaming } = useChatRuntime();++ const hasContext = usePageContextValue();++ if (messages.length === 0) {+ return (+ <div className="flex-1 flex flex-col">+ <ChatContextWidget />+ <ChatDrawerEmpty />+ </div>+ );+ }++ return (+ <div className="flex-1 flex flex-col min-h-0 relative">+ <div className="absolute top-0 left-0 right-0 z-20 backdrop-blur-sm">+ <ChatContextWidget />+ </div>+ <StickToBottom+ className="flex-1 relative overflow-hidden"+ initial="instant"+ resize="smooth"+ >+ <StickToBottom.Content+ className={cn(+ 'flex flex-col gap-4 px-3 py-4',+ hasContext && 'pt-24',+ )}+ >+ {messages.map((message) => (+ <ChatMessage key={message.localId} message={message} />+ ))}+ {isLoading && !isStreaming && (+ <div className="flex items-center gap-2 text-sm">+ <span className="op-shimmer font-medium">Thinking…</span>+ </div>+ )}+ </StickToBottom.Content>+ <ScrollToBottomButton />+ </StickToBottom>+ </div>+ );+}++function ScrollToBottomButton() {+ const { isAtBottom, scrollToBottom } = useStickToBottomContext();+ if (isAtBottom) return null;+ return (+ <Button+ type="button"+ size="sm"+ variant="secondary"+ className="absolute bottom-3 left-1/2 -translate-x-1/2 h-7 px-2 shadow-md gap-1"+ onClick={() => scrollToBottom()}+ aria-label="Scroll to bottom"+ >+ <ArrowDownIcon className="size-3" />+ <span className="text-sm">Latest</span>+ </Button>+ );+}diff --git a/apps/start/src/components/chat/chat-drawer-empty.tsx b/apps/start/src/components/chat/chat-drawer-empty.tsxnew file mode 100644index 000000000..4ff1b130d--- /dev/null+++ b/apps/start/src/components/chat/chat-drawer-empty.tsx@@ -0,0 +1,196 @@+import { usePageContextValue } from '@/contexts/page-context';+import { SparklesIcon } from 'lucide-react';+import { useChatRuntime } from './chat-runtime';++/**+ * Empty-state panel shown when a chat has no messages yet. Headline,+ * description, and example prompts are tailored to the current page+ * so the user gets ideas relevant to what they're looking at. The+ * prompts are clickable — they fire the same `send()` as typing and+ * pressing Enter, so the user can kick off the conversation in one+ * tap.+ */+export function ChatDrawerEmpty() {+ const ctx = usePageContextValue();+ const { send } = useChatRuntime();+ const suggestions = getSuggestionsForContext(ctx);++ return (+ <div className="flex flex-1 flex-col items-center justify-center gap-5 px-6 py-8 text-center">+ <div className="flex size-10 items-center justify-center rounded-full bg-primary/10 text-primary">+ <SparklesIcon className="size-5" />+ </div>+ <div className="max-w-xs">+ <h3 className="font-semibold text-xl mb-2">{suggestions.headline}</h3>+ <p className="mt-1.5 text-muted-foreground leading-[1.5]">+ {suggestions.description}+ </p>+ </div>+ <div className="flex w-full max-w-xs flex-col gap-2 items-center">+ {suggestions.prompts.map((prompt) => (+ <button+ key={prompt}+ type="button"+ onClick={() => send(prompt)}+ className="rounded-md border bg-muted/30 px-3 py-2 text-left text-sm text-foreground/80 transition-colors hover:bg-muted/60 hover:text-foreground"+ >+ {prompt}+ </button>+ ))}+ </div>+ </div>+ );+}++type Suggestions = {+ headline: string;+ description: string;+ prompts: string[];+};++function getSuggestionsForContext(+ ctx: ReturnType<typeof usePageContextValue>,+): Suggestions {+ if (!ctx) {+ return {+ headline: 'Ask about your data',+ description:+ 'I can answer questions about your analytics, generate reports, and dig into users, sessions, or pages.',+ prompts: [+ 'What happened yesterday?',+ 'Show me last 7 days of traffic',+ 'Which pages have the highest bounce rate?',+ ],+ };+ }++ switch (ctx.page) {+ case 'overview':+ return {+ headline: 'Ask about this overview',+ description:+ 'I can explain trends, compare periods, or filter the page. Try a question or pick a starter.',+ prompts: [+ 'What changed compared to the previous period?',+ 'Filter to mobile only',+ 'Show me last 7 days of traffic',+ 'Which referrers drove the most sessions?',+ ],+ };++ case 'insights':+ return {+ headline: 'Explore your insights',+ description:+ 'I can explain why an insight fired, find related ones, or walk you through the most important.',+ prompts: [+ 'What are the most important insights right now?',+ 'Explain the biggest anomaly this week',+ 'Any insights related to device trends?',+ ],+ };++ case 'pages':+ return {+ headline: 'Ask about your pages',+ description:+ 'I can rank pages by performance, find declining ones, or identify entry/exit patterns.',+ prompts: [+ 'Which pages are declining vs last month?',+ 'Show pages with the highest bounce rate',+ 'Top entry pages in the last 7 days',+ 'Find pages with underperforming SEO',+ ],+ };++ case 'seo':+ return {+ headline: 'Dig into your SEO',+ description:+ 'I can surface high-opportunity queries, check for cannibalization, and correlate SEO with on-site engagement.',+ prompts: [+ 'Queries on page 2 with high impressions (easy wins)',+ 'Any query cannibalization I should fix?',+ 'Which pages bring GSC clicks but bounce hard?',+ 'Top SEO queries last 30 days',+ ],+ };++ case 'events':+ return {+ headline: 'Analyze your events',+ description:+ 'I can analyze distribution, correlate events, and drill into properties.',+ prompts: [+ 'Which events often happen together?',+ 'Analyze event distribution by country',+ 'Filter to signup events only',+ 'What are the most common event properties?',+ ],+ };++ case 'profileDetail':+ return {+ headline: 'Ask about this user',+ description:+ 'I can summarize this profile, build a journey, or compare them to the average user.',+ prompts: [+ "Tell me about this user's journey",+ 'How does this user compare to average?',+ 'What was their last session?',+ 'Do they have unusual behavior?',+ ],+ };++ case 'sessionDetail':+ return {+ headline: 'Ask about this session',+ description:+ 'I can walk through the path, compare to typical sessions, or explain the referrer context.',+ prompts: [+ 'Walk me through this session',+ 'How does this compare to typical sessions?',+ 'Where did this traffic come from?',+ 'Are there similar sessions today?',+ ],+ };++ case 'groupDetail':+ return {+ headline: 'Ask about this group',+ description:+ 'I can show metrics, list members, and compare to peer groups.',+ prompts: [+ "Summarize this group's activity",+ 'Compare to other groups',+ 'Who are the most active members?',+ "What's this group's engagement trend?",+ ],+ };++ case 'reportEditor':+ return {+ headline: 'Edit this report with me',+ description:+ 'I can preview changes, suggest breakdowns, or compare to the previous period.',+ prompts: [+ 'Suggest useful breakdowns for this report',+ 'Compare to the previous period',+ 'Find anomalies in the current data',+ 'Add a country breakdown',+ ],+ };++ default:+ return {+ headline: 'Ask about your data',+ description:+ 'I can answer questions about the page you\'re viewing, generate reports, and dig into specific users, sessions, or pages.',+ prompts: [+ "What's our visitor count this week?",+ 'Top traffic sources right now',+ 'Show me top pages by bounce rate',+ ],+ };+ }+}diff --git a/apps/start/src/components/chat/chat-drawer-footer.tsx b/apps/start/src/components/chat/chat-drawer-footer.tsxnew file mode 100644index 000000000..0c59260b4--- /dev/null+++ b/apps/start/src/components/chat/chat-drawer-footer.tsx@@ -0,0 +1,109 @@+import { Button } from '@/components/ui/button';+import { cn } from '@/utils/cn';+import { ArrowUpIcon, StopCircleIcon } from 'lucide-react';+import { useEffect, useRef, useState } from 'react';+import { useChatRuntime } from './chat-runtime';+import { ModelPicker } from './model-picker';++/**+ * Composer card.+ *+ * Layout mirrors the modern "single-card" pattern: textarea on top,+ * model picker bottom-left, send button bottom-right. Owns its own+ * input state — `useChat` v5+ doesn't manage input.+ */+export function ChatDrawerFooter() {+ const { send, stop, status } = useChatRuntime();+ const [text, setText] = useState('');+ const isStreaming = status === 'streaming' || status === 'submitted';++ // Auto-focus the textarea on mount. Because the footer sits inside+ // `<ChatRuntimeProvider key={conversationId}>`, the provider (and+ // therefore this footer) remounts whenever the drawer opens or the+ // active conversation changes — so this runs on every "open"+ // without us needing to track the event explicitly.+ const textareaRef = useRef<HTMLTextAreaElement | null>(null);+ useEffect(() => {+ textareaRef.current?.focus();+ }, []);++ const submit = (e?: React.FormEvent) => {+ e?.preventDefault();+ const value = text.trim();+ if (!value || isStreaming) return;+ send(value);+ setText('');+ };++ return (+ <form onSubmit={submit} className="px-3 pb-3 pt-2">+ <div+ className={cn(+ 'rounded-xl border bg-card transition-shadow',+ 'focus-within:ring-1 focus-within:ring-ring focus-within:border-ring',+ )}+ >+ {/*+ Plain `<textarea>` here — the shadcn `<Textarea>` ships with+ its own `border-input` + `focus-visible:ring-2 + ring-offset-2`,+ which stack on top of the parent card's focus-within ring and+ produce a double-outline (see prior screenshot). Keep things+ unstyled at the element level so the parent card owns the+ focus boundary.+ */}+ {/*+ Input stays editable while a reply streams — the user can+ draft the next message in parallel. Enter is a no-op during+ streaming (blocked inside `submit`); once the run ends the+ drafted text sends on the next Enter press.+ */}+ <textarea+ ref={textareaRef}+ value={text}+ onChange={(e) => setText(e.target.value)}+ placeholder="Ask anything about your data…"+ rows={2}+ className={cn(+ 'block w-full bg-transparent text-sm leading-[1.5] text-foreground',+ 'placeholder:text-muted-foreground/70',+ 'resize-none border-0 outline-none ring-0 shadow-none',+ 'focus:outline-none focus:ring-0 focus-visible:outline-none focus-visible:ring-0',+ 'min-h-[48px] max-h-[200px] px-3 pt-3 pb-1',+ )}+ onKeyDown={(e) => {+ if (e.key === 'Enter' && !e.shiftKey) {+ e.preventDefault();+ submit();+ }+ }}+ />+ <div className="flex items-center justify-between gap-2 px-2 pb-2">+ <ModelPicker />+ {isStreaming ? (+ <Button+ type="button"+ size="icon"+ variant="secondary"+ className="size-7 rounded-md shrink-0"+ onClick={stop}+ aria-label="Stop generating"+ >+ <StopCircleIcon className="size-3.5" />+ </Button>+ ) : (+ <Button+ type="submit"+ size="icon"+ variant="default"+ className="size-7 rounded-md shrink-0"+ disabled={!text.trim()}+ aria-label="Send message"+ >+ <ArrowUpIcon className="size-3.5" />+ </Button>+ )}+ </div>+ </div>+ </form>+ );+}diff --git a/apps/start/src/components/chat/chat-drawer-header.tsx b/apps/start/src/components/chat/chat-drawer-header.tsxnew file mode 100644index 000000000..73cbeeb26--- /dev/null+++ b/apps/start/src/components/chat/chat-drawer-header.tsx@@ -0,0 +1,180 @@+import { Button } from '@/components/ui/button';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';+import { useTRPC } from '@/integrations/trpc/react';+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';+import { MessageSquarePlusIcon, Trash2Icon, XIcon } from 'lucide-react';+import { useEffect, useRef, useState } from 'react';+import { useChatState } from './chat-context';++/**+ * Header — conversation picker, model picker, new chat, close.+ *+ * Reads the global `useChatState()` for the current conversation and+ * agent. Conversation list still uses TRPC; switching a conversation+ * just sets the id — Better Agent's `hydrateFromServer` loads the+ * messages on the next render of the body.+ */+export function ChatDrawerHeader({+ projectId,+ onClose,+}: {+ projectId: string;+ onClose: () => void;+}) {+ const trpc = useTRPC();+ const queryClient = useQueryClient();+ const { conversationId, switchConversation, newConversation, streamingTitle } =+ useChatState();++ const { data: conversations } = useQuery(+ trpc.conversation.list.queryOptions({ projectId, limit: 50 }),+ );++ const deleteMutation = useMutation(+ trpc.conversation.delete.mutationOptions({+ onSuccess: (_data, variables) => {+ queryClient.invalidateQueries(trpc.conversation.list.pathFilter());+ if (variables.id === conversationId) {+ newConversation();+ }+ },+ }),+ );++ // Header title priority:+ // 1. In-session streaming title (either mid-stream or finalized+ // after the title finished generating)+ // 2. Persisted title from the conversation list query+ // 3. "New chat" fallback when nothing is known yet+ const persistedTitle =+ conversations?.find((c) => c.id === conversationId)?.title ?? null;+ const activeTitle = streamingTitle ?? persistedTitle ?? 'New chat';++ return (+ <header className="flex items-center justify-between gap-2 border-b px-3 py-2">+ <div className="flex items-center gap-2 min-w-0 flex-1">+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ size="sm"+ className="font-medium text-sm truncate max-w-[200px]"+ >+ {activeTitle}+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="start"+ className="w-72 max-h-96 overflow-y-auto"+ >+ <DropdownMenuLabel>Conversations</DropdownMenuLabel>+ <DropdownMenuSeparator />+ {(!conversations || conversations.length === 0) && (+ <div className="px-2 py-3 text-sm text-muted-foreground">+ No conversations yet. Start typing to create one.+ </div>+ )}+ {conversations?.map((c) => (+ <DropdownMenuItem+ key={c.id}+ className="flex items-center justify-between gap-2"+ onSelect={() => switchConversation(c.id)}+ >+ <span className="truncate">{c.title ?? 'Untitled chat'}</span>+ <InlineDeleteButton+ onConfirm={() => deleteMutation.mutate({ id: c.id })}+ />+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ <div className="flex items-center gap-1 shrink-0">+ <Button+ variant="ghost"+ size="sm"+ onClick={() => newConversation()}+ aria-label="New conversation"+ title="New conversation"+ >+ <MessageSquarePlusIcon className="size-4" />+ </Button>+ <Button+ variant="ghost"+ size="sm"+ onClick={onClose}+ aria-label="Close chat"+ >+ <XIcon className="size-4" />+ </Button>+ </div>+ </header>+ );+}++/**+ * Two-step inline delete. First click swaps the X icon for a red+ * check; second click within the arm window fires `onConfirm`.+ * Auto-reverts after 4s of inactivity. Moving the mouse away doesn't+ * disarm — that was too aggressive (the dropdown re-layouts between+ * hovers and the button briefly loses hover state). Only the+ * time-based auto-revert applies.+ */+function InlineDeleteButton({ onConfirm }: { onConfirm: () => void }) {+ const [armed, setArmed] = useState(false);+ const timerRef = useRef<number | null>(null);++ const clearTimer = () => {+ if (timerRef.current !== null) {+ window.clearTimeout(timerRef.current);+ timerRef.current = null;+ }+ };++ // Cleanup on unmount.+ useEffect(() => clearTimer, []);++ const handleClick = (e: React.MouseEvent) => {+ e.preventDefault();+ e.stopPropagation();+ if (armed) {+ clearTimer();+ setArmed(false);+ onConfirm();+ return;+ }+ setArmed(true);+ clearTimer();+ timerRef.current = window.setTimeout(() => {+ setArmed(false);+ timerRef.current = null;+ }, 4000);+ };++ return (+ <button+ type="button"+ onClick={handleClick}+ className={+ armed+ ? 'shrink-0 rounded bg-destructive p-1 text-white hover:bg-destructive/90 transition-colors'+ : 'shrink-0 rounded p-0.5 text-muted-foreground hover:text-destructive transition-colors'+ }+ aria-label={armed ? 'Confirm delete' : 'Delete conversation'}+ title={armed ? 'Click again to confirm' : 'Delete'}+ >+ {armed ? (+ <Trash2Icon className="size-3" />+ ) : (+ <XIcon className="size-3" />+ )}+ </button>+ );+}diff --git a/apps/start/src/components/chat/chat-drawer-slot.tsx b/apps/start/src/components/chat/chat-drawer-slot.tsxnew file mode 100644index 000000000..1050fa6b4--- /dev/null+++ b/apps/start/src/components/chat/chat-drawer-slot.tsx@@ -0,0 +1,38 @@+import { lazy, Suspense, useEffect, useState } from 'react';++/**+ * Client-only mount wrapper for the chat drawer.+ *+ * `@better-agent/client` uses Ajv for JSON schema validation which+ * compiles validators via `new Function()`. The Cloudflare Workers+ * SSR environment (workerd) disallows runtime code generation, so the+ * client module can't be evaluated during SSR.+ *+ * This slot:+ * - Returns null on the server and during initial hydration (no+ * mismatch: the server HTML has no drawer, the client's first+ * render matches)+ * - After `useEffect` fires on the client, triggers the lazy import+ * which loads `@better-agent/client` for the first time+ * - Suspense keeps the tree stable while the chunk loads+ *+ * The drawer is gated by `?chat=<id>` anyway, so it's never visible+ * on the first paint — there's no UX cost to this wrapping.+ */+const ChatDrawer = lazy(() =>+ import('./chat-drawer').then((m) => ({ default: m.ChatDrawer })),+);++export function ChatDrawerSlot() {+ const [mounted, setMounted] = useState(false);+ useEffect(() => {+ setMounted(true);+ }, []);++ if (!mounted) return null;+ return (+ <Suspense fallback={null}>+ <ChatDrawer />+ </Suspense>+ );+}diff --git a/apps/start/src/components/chat/chat-drawer.tsx b/apps/start/src/components/chat/chat-drawer.tsxnew file mode 100644index 000000000..1c18380bd--- /dev/null+++ b/apps/start/src/components/chat/chat-drawer.tsx@@ -0,0 +1,96 @@+import { useAppParams } from '@/hooks/use-app-params';+import { useResizableDrawer } from '@/hooks/use-resizable-drawer';+import { useEffect } from 'react';+import { useChatState } from './chat-context';+import { ChatDrawerBody } from './chat-drawer-body';+import { ChatDrawerFooter } from './chat-drawer-footer';+import { ChatDrawerHeader } from './chat-drawer-header';+import { ChatRuntimeProvider } from './chat-runtime';++const WIDTH_STORAGE_KEY = 'op-chat-drawer-width';+const DEFAULT_WIDTH = 440;+const MIN_WIDTH = 360;+const MAX_WIDTH = 720;++/**+ * Persistent right-side drawer for the context-aware AI chat. Mounts+ * once inside `_app.tsx` (so it can flex-shrink the main content on+ * `lg+`). Renders nothing when `?chat` is absent from the URL or+ * there's no project in scope.+ *+ * The drawer wraps body + footer in `<ChatRuntimeProvider>`, which+ * owns the single `useAgent()` instance for the active agent ++ * conversation. Header sits outside the runtime and only reads the+ * thin `useChatState()` context (conversation list, new chat button).+ */+export function ChatDrawer() {+ const { projectId } = useAppParams();+ const { conversationId, isOpen, closeChat, openChatForContext } =+ useChatState();+ const { width, dragHandleProps } = useResizableDrawer({+ defaultWidth: DEFAULT_WIDTH,+ minWidth: MIN_WIDTH,+ maxWidth: MAX_WIDTH,+ storageKey: WIDTH_STORAGE_KEY,+ });++ // Cmd+J / Ctrl+J shortcut — toggles the drawer. Opening resumes+ // the last conversation for the current context (same page ++ // same entity); closing just clears `?chat`.+ useEffect(() => {+ if (!projectId) return;+ const handler = (e: KeyboardEvent) => {+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'j') {+ e.preventDefault();+ if (isOpen) {+ closeChat();+ } else {+ openChatForContext();+ }+ }+ };+ window.addEventListener('keydown', handler);+ return () => window.removeEventListener('keydown', handler);+ }, [projectId, isOpen, closeChat, openChatForContext]);++ if (!projectId || !isOpen) return null;++ return (+ <>+ {/*+ Spacer in the flex layout — the aside is `fixed` so the main+ content would otherwise render under it. This empty div takes+ the drawer's width on `lg+` so the page naturally shrinks.+ Hidden on mobile where the drawer overlays as a modal-style+ panel (standard behavior for narrow viewports).+ */}+ <div+ className="hidden lg:block shrink-0"+ style={{ width }}+ aria-hidden+ />+ <aside+ className="fixed top-0 right-0 z-40 h-screen flex flex-col bg-background border-l shadow-2xl"+ style={{ width }}+ >+ <div+ className="absolute top-0 left-0 z-10 w-1 h-full cursor-ew-resize hover:bg-border transition-colors"+ aria-label="Resize chat drawer"+ {...dragHandleProps}+ />+ <ChatDrawerHeader projectId={projectId} onClose={closeChat} />+ {/*+ Remount the runtime provider (and the `useAgent` controller+ inside it) whenever `conversationId` changes. The controller+ caches the id in a ref and only loads from the server on+ `init()`, so without this key a switch wouldn't trigger the+ hydrate fetch.+ */}+ <ChatRuntimeProvider key={conversationId}>+ <ChatDrawerBody />+ <ChatDrawerFooter />+ </ChatRuntimeProvider>+ </aside>+ </>+ );+}diff --git a/apps/start/src/components/chat/chat-form.tsx b/apps/start/src/components/chat/chat-form.tsxdeleted file mode 100644index 88ff294ed..000000000--- a/apps/start/src/components/chat/chat-form.tsx+++ /dev/null@@ -1,70 +0,0 @@-import { cn } from '@/utils/cn';-import type { useChat } from '@ai-sdk/react';-import { useLocalStorage } from 'usehooks-ts';-import { Button } from '../ui/button';-import { ScrollArea } from '../ui/scroll-area';--type Props = Pick<- ReturnType<typeof useChat>,- 'handleSubmit' | 'handleInputChange' | 'input' | 'append'-> & {- projectId: string;- isLimited: boolean;-};--export function ChatForm({- handleSubmit: handleSubmitProp,- input,- handleInputChange,- append,- projectId,- isLimited,-}: Props) {- const [quickActions, setQuickActions] = useLocalStorage<string[]>(- `chat-quick-actions:${projectId}`,- [],- );-- const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {- handleSubmitProp(e);- setQuickActions([input, ...quickActions].slice(0, 5));- };-- return (- <div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-def-100 to-def-100/50 backdrop-blur-sm z-20">- <ScrollArea orientation="horizontal">- <div className="row gap-2 px-4">- {quickActions.map((q) => (- <Button- disabled={isLimited}- key={q}- type="button"- variant="outline"- size="sm"- onClick={() => {- append({- role: 'user',- content: q,- });- }}- >- {q}- </Button>- ))}- </div>- </ScrollArea>- <form onSubmit={handleSubmit} className="p-4 pt-2">- <input- disabled={isLimited}- className={cn(- 'w-full h-12 px-4 outline-none border border-border text-foreground rounded-md font-mono placeholder:text-foreground/50 bg-background/50',- isLimited && 'opacity-50 cursor-not-allowed',- )}- value={input}- placeholder="Ask me anything..."- onChange={handleInputChange}- />- </form>- </div>- );-}diff --git a/apps/start/src/components/chat/chat-markdown.tsx b/apps/start/src/components/chat/chat-markdown.tsxnew file mode 100644index 000000000..ac2fcf690--- /dev/null+++ b/apps/start/src/components/chat/chat-markdown.tsx@@ -0,0 +1,76 @@+import { cn } from '@/utils/cn';+import { memo } from 'react';+import ReactMarkdown from 'react-markdown';+import remarkGfm from 'remark-gfm';++/**+ * Markdown renderer used for assistant text parts in the chat. Tight+ * scope: bullets, ordered lists, headings, code, links, tables.+ *+ * Memoized so repeated streaming re-renders of the same chunk skip+ * the markdown parse when the content hasn't changed.+ */+function ChatMarkdownInner({+ text,+ className,+}: {+ text: string;+ className?: string;+}) {+ return (+ <div+ className={cn(+ // Reasonable readable defaults for a chat surface: 14px body,+ // 1.6 line height, list/heading rhythm.+ 'leading-[1.6] text-foreground',+ // Element styling via descendant selectors keeps the API tiny+ // (no per-element override props for callers).+ '[&>*+*]:mt-2',+ '[&_p]:my-0',+ '[&_p+p]:mt-2',+ '[&_ul]:list-disc [&_ul]:pl-5 [&_ul]:my-2',+ '[&_ol]:list-decimal [&_ol]:pl-5 [&_ol]:my-2',+ '[&_li]:my-0.5',+ '[&_li>p]:my-0',+ '[&_h1]:font-semibold [&_h1]:mt-3 [&_h1]:mb-1',+ '[&_h2]:font-semibold [&_h2]:mt-3 [&_h2]:mb-1',+ '[&_h3]:font-medium [&_h3]:mt-2 [&_h3]:mb-1',+ '[&_strong]:font-semibold',+ '[&_em]:italic',+ '[&_a]:text-primary [&_a]:underline [&_a]:underline-offset-2 hover:[&_a]:no-underline',+ '[&_code]:rounded [&_code]:bg-muted [&_code]:px-1 [&_code]:py-0.5 [&_code]:text-[12.5px] [&_code]:font-mono',+ '[&_pre]:rounded-md [&_pre]:bg-muted [&_pre]:p-3 [&_pre]:text-[12.5px] [&_pre]:overflow-x-auto',+ '[&_pre>code]:bg-transparent [&_pre>code]:p-0',+ '[&_blockquote]:border-l-2 [&_blockquote]:border-muted-foreground/30 [&_blockquote]:pl-3 [&_blockquote]:text-muted-foreground',+ '[&_table]:w-full [&_table]:text-sm [&_table]:my-2',+ '[&_th]:text-left [&_th]:font-medium [&_th]:px-2 [&_th]:py-1 [&_th]:border-b',+ '[&_td]:px-2 [&_td]:py-1 [&_td]:border-b [&_td]:border-border/40',+ '[&_hr]:my-3 [&_hr]:border-border',+ className,+ )}+ >+ <ReactMarkdown+ remarkPlugins={[remarkGfm]}+ components={{+ // Open external links in a new tab; safe defaults.+ a: ({ href, children, ...rest }) => (+ <a+ {...rest}+ href={href}+ target={href?.startsWith('http') ? '_blank' : undefined}+ rel={+ href?.startsWith('http') ? 'noopener noreferrer' : undefined+ }+ >+ {children}+ </a>+ ),+ }}+ >+ {text}+ </ReactMarkdown>+ </div>+ );+}++export const ChatMarkdown = memo(ChatMarkdownInner);diff --git a/apps/start/src/components/chat/chat-message.tsx b/apps/start/src/components/chat/chat-message.tsxindex e380c2472..de811de84 100644--- a/apps/start/src/components/chat/chat-message.tsx+++ b/apps/start/src/components/chat/chat-message.tsx@@ -1,148 +1,200 @@-import { Markdown } from '@/components/markdown';import { cn } from '@/utils/cn';-import { zReport } from '@openpanel/validation';-import { z } from 'zod';-import type { UIMessage } from 'ai';-import { Loader2Icon, UserIcon } from 'lucide-react';-import { Fragment, memo } from 'react';-import { Card } from '../card';-import { LogoSquare } from '../logo';-import { Skeleton } from '../skeleton';-import Syntax from '../syntax';-import {- Accordion,- AccordionContent,- AccordionItem,- AccordionTrigger,-} from '../ui/accordion';-import { ChatReport } from './chat-report';+import type { UIMessage } from '@better-agent/client';+import { ChevronRightIcon } from 'lucide-react';+import { useState } from 'react';+import { ChatMarkdown } from './chat-markdown';+import { chatToolRenderers, DefaultToolResult } from './tool-results/registry';+import type { ToolResultPart } from './tool-results/types';-export const ChatMessage = memo(- ({- message,- isLast,- isStreaming,- debug,- }: {- message: UIMessage;- isLast: boolean;- isStreaming: boolean;- debug: boolean;- }) => {- const showIsStreaming = isLast && isStreaming;- return (- <div className="max-w-xl w-full">- <div className="row">- <div className="w-8 shrink-0">- <div className="size-6 relative">- {message.role === 'assistant' ? (- <LogoSquare className="size-full rounded-full" />- ) : (- <div className="size-full bg-black text-white rounded-full center-center">- <UserIcon className="size-4" />- </div>- )}+/**+ * Renders a single message by switching over `message.parts[i].type`.+ *+ * Better Agent's part model splits tool calls and results into TWO+ * separate parts (`tool-call` and `tool-result`) keyed by `callId`.+ * We pair them up before rendering so the UI sees one logical "tool+ * invocation" per call.+ *+ * Assistant text supports markdown via `<ChatMarkdown>`. User text+ * stays plain (no markdown injection from user input).+ */+export function ChatMessage({ message }: { message: UIMessage }) {+ const isUser = message.role === 'user';++ // Index tool results by callId so we can attach them to their call.+ const resultByCallId = new Map<string, { result?: unknown; status: string }>();+ for (const part of message.parts) {+ if (part.type === 'tool-result') {+ resultByCallId.set(part.callId, {+ result: part.result,+ status: part.status,+ });+ }+ }+ return (+ <div+ className={cn(+ 'flex flex-col gap-2',+ isUser ? 'items-end' : 'items-start',+ )}+ >+ {message.parts.map((part, idx) => {+ switch (part.type) {+ case 'text':+ if (isUser) {+ return (+ <div+ key={`${message.localId}-text-${idx}`}+ className="rounded-lg px-3 py-2 text leading-[1.5] whitespace-pre-wrap break-words max-w-[90%] bg-primary text-primary-foreground"+ >+ {part.text}+ </div>+ );+ }+ return (<div- className={cn(- 'absolute inset-0 bg-background rounded-full center-center opacity-0',- showIsStreaming && 'opacity-100',- )}+ key={`${message.localId}-text-${idx}`}+ className="max-w-full w-full">- <Loader2Icon className="size-4 animate-spin text-foreground" />+ <ChatMarkdown text={part.text} /></div>- </div>- </div>- <div className="col gap-4 flex-1">- {message.parts.map((p, index) => {- const key = index.toString() + p.type;- const isToolInvocation = p.type === 'tool-invocation';-- if (p.type === 'step-start') {- return null;- }+ );- if (!isToolInvocation && p.type !== 'text') {- return <Debug enabled={debug} json={p} />;- }+ case 'reasoning':+ return (+ <ReasoningBlock+ key={`${message.localId}-reasoning-${idx}`}+ text={part.text}+ complete={(part as { state?: string }).state === 'complete'}+ />+ );- if (p.type === 'text') {- return (- <div className="prose dark:prose-invert prose-sm" key={key}>- <Markdown>{p.text}</Markdown>- </div>- );- }+ case 'tool-call': {+ const matched = resultByCallId.get(part.callId);+ const toolName = part.name;+ // If the tool's name hasn't streamed in yet (intermediate+ // state between TOOL_CALL_START and the args event), show+ // a neutral "Thinking…" shimmer instead of "Running+ // unknown…". Once the name arrives, the part re-renders+ // with the real tool + its renderer.+ if (!toolName) {+ return (+ <div+ key={part.callId}+ className="flex items-center gap-2 py-1.5 text-sm"+ >+ <span className="op-shimmer font-medium">Thinking…</span>+ </div>+ );+ }+ const Renderer =+ chatToolRenderers[`tool-${toolName}` as keyof typeof chatToolRenderers] ??+ DefaultToolResult;+ const toolPart: ToolResultPart = {+ type: `tool-${toolName}`,+ toolCallId: part.callId,+ state: derivePartState(part.state, matched?.status),+ input: part.args ? safeParse(part.args) : undefined,+ output: matched?.result,+ errorText:+ matched?.status === 'error' ? 'Tool failed' : undefined,+ };+ return (+ <div key={part.callId} className="w-full max-w-full">+ <Renderer part={toolPart} />+ </div>+ );+ }- if (isToolInvocation && p.toolInvocation.state === 'result') {- const { result } = p.toolInvocation;+ case 'tool-result':+ // Already rendered above as part of the matching tool-call.+ return null;- if (result.type === 'report') {- const report = zReport.extend({- startDate: z.string(),- endDate: z.string(),- }).safeParse(result.report);- if (report.success) {- return (- <Fragment key={key}>- <Debug json={result} enabled={debug} />- <ChatReport report={report.data} lazy={!isLast} />- </Fragment>- );- }- }+ default:+ return null;+ }+ })}+ </div>+ );+}- return (- <Debug- key={key}- json={p.toolInvocation.result}- enabled={debug}- />- );- }+/**+ * Reasoning trace from the model. While streaming, shows a shimmer+ * "Thinking…" header with the latest line as a one-line preview.+ * When complete, becomes a click-to-expand "Thought" disclosure.+ */+function ReasoningBlock({+ text,+ complete,+}: {+ text: string;+ complete: boolean;+}) {+ const [open, setOpen] = useState(false);+ const trimmed = text.trim();+ // Latest non-empty line for the live preview.+ const latestLine =+ trimmed+ .split('\n')+ .map((l) => l.trim())+ .filter(Boolean)+ .pop() ?? '';- return null;- })}- {showIsStreaming && (- <div className="w-full col gap-2">- <Skeleton className="w-3/5 h-4" />- <Skeleton className="w-4/5 h-4" />- <Skeleton className="w-2/5 h-4" />- </div>- )}- </div>+ if (!complete) {+ return (+ <div className="w-full max-w-full">+ <div className="flex items-center gap-2 text-sm">+ <span className="op-shimmer font-medium">Thinking…</span></div>- {!isLast && (- <div className="w-full shrink-0 pl-8 mt-4">- <div className="h-px bg-border" />+ {latestLine && (+ <div className="mt-1 text-sm text-muted-foreground/80 italic line-clamp-1">+ {latestLine}</div>)}</div>);- },-);--function Debug({ enabled, json }: { enabled?: boolean; json?: any }) {- if (!enabled) {- return null;}return (- <Accordion type="single" collapsible>- <Card>- <AccordionItem value={'json'}>- <AccordionTrigger className="text-left p-4 py-2 w-full font-medium font-mono row items-center">- <span className="flex-1">Show JSON result</span>- </AccordionTrigger>- <AccordionContent className="p-2">- <Syntax- wrapLines- language="json"- code={JSON.stringify(json, null, 2)}- />- </AccordionContent>- </AccordionItem>- </Card>- </Accordion>+ <div className="w-full max-w-full">+ <button+ type="button"+ onClick={() => setOpen((v) => !v)}+ className="flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors"+ >+ <ChevronRightIcon+ className={cn('size-3 transition-transform', open && 'rotate-90')}+ />+ <span>Thought</span>+ </button>+ {open && (+ <div className="mt-1 ml-4 border-l-2 border-muted-foreground/20 pl-3">+ <ChatMarkdown+ text={trimmed}+ className="text-sm text-muted-foreground"+ />+ </div>+ )}+ </div>);}++function derivePartState(+ callState: string | undefined,+ resultStatus: string | undefined,+): string {+ if (resultStatus === 'success') return 'output-available';+ if (resultStatus === 'error') return 'output-error';+ if (resultStatus === 'pending') return 'input-available';+ if (callState === 'input-streaming') return 'input-streaming';+ if (callState === 'input-complete') return 'input-available';+ return 'input-streaming';+}++function safeParse(json: string): unknown {+ try {+ return JSON.parse(json);+ } catch {+ return undefined;+ }+}diff --git a/apps/start/src/components/chat/chat-messages.tsx b/apps/start/src/components/chat/chat-messages.tsxdeleted file mode 100644index 957b90bad..000000000--- a/apps/start/src/components/chat/chat-messages.tsx+++ /dev/null@@ -1,86 +0,0 @@-import { useAppParams } from '@/hooks/use-app-params';-import { useScrollAnchor } from '@/hooks/use-scroll-anchor';-import { Link } from '@tanstack/react-router';-import type { UIMessage } from 'ai';-import { Loader2Icon } from 'lucide-react';-import { useEffect } from 'react';-import { ProjectLink } from '../links';-import { Alert, AlertDescription, AlertTitle } from '../ui/alert';-import { ScrollArea } from '../ui/scroll-area';-import { ChatMessage } from './chat-message';--export function ChatMessages({- messages,- debug,- status,- isLimited,-}: {- messages: UIMessage[];- debug: boolean;- status: 'submitted' | 'streaming' | 'ready' | 'error';- isLimited: boolean;-}) {- const { organizationId } = useAppParams();- const { messagesRef, scrollRef, visibilityRef, scrollToBottom } =- useScrollAnchor();-- useEffect(() => {- scrollToBottom();- }, []);-- useEffect(() => {- const lastMessage = messages[messages.length - 1];- if (lastMessage?.role === 'user') {- scrollToBottom();- }- }, [messages]);-- return (- <ScrollArea className="h-full" ref={scrollRef}>- <div ref={messagesRef} className="p-8 col gap-2">- {messages.map((m, index) => {- return (- <ChatMessage- key={m.id}- message={m}- isStreaming={status === 'streaming'}- isLast={index === messages.length - 1}- debug={debug}- />- );- })}- {status === 'submitted' && (- <div className="card p-4 center-center max-w-xl pl-8">- <Loader2Icon className="w-4 h-4 animate-spin" />- </div>- )}- {isLimited && (- <div className="max-w-xl pl-8 mt-8">- <Alert variant={'warning'}>- <AlertTitle>Upgrade your account</AlertTitle>- <AlertDescription>- <p>- To keep using this feature you need to upgrade your account.- </p>- <p>- <Link- to="/$organizationId/billing"- params={{- organizationId,- }}- className="font-medium underline"- >- Visit Billing- </Link>{' '}- to upgrade.- </p>- </AlertDescription>- </Alert>- </div>- )}- <div className="h-20 p-4 w-full" />- <div className="w-full h-px" ref={visibilityRef} />- </div>- </ScrollArea>- );-}diff --git a/apps/start/src/components/chat/chat-report.tsx b/apps/start/src/components/chat/chat-report.tsxdeleted file mode 100644index 745f674b3..000000000--- a/apps/start/src/components/chat/chat-report.tsx+++ /dev/null@@ -1,89 +0,0 @@-import type {- IChartRange,- IChartType,- IInterval,- IReport,-} from '@openpanel/validation';-import { SaveIcon } from 'lucide-react';-import { useState } from 'react';-import { ReportChartType } from '../report/ReportChartType';-import { ReportInterval } from '../report/ReportInterval';-import { ReportChart } from '../report-chart';-import { TimeWindowPicker } from '../time-window-picker';-import { Button } from '../ui/button';-import { pushModal } from '@/modals';--export function ChatReport({- lazy,- ...props-}: {- report: IReport & { startDate: string; endDate: string };- lazy: boolean;-}) {- const [chartType, setChartType] = useState<IChartType>(- props.report.chartType- );- const [startDate, setStartDate] = useState<string>(props.report.startDate);- const [endDate, setEndDate] = useState<string>(props.report.endDate);- const [range, setRange] = useState<IChartRange>(props.report.range);- const [interval, setInterval] = useState<IInterval>(props.report.interval);- const report = {- ...props.report,- lineType: 'linear' as const,- chartType,- startDate: range === 'custom' ? startDate : null,- endDate: range === 'custom' ? endDate : null,- range,- interval,- };- return (- <div className="card">- <div className="pt-4 text-center font-medium font-mono text-sm">- {props.report.name}- </div>- <div className="p-4">- <ReportChart lazy={lazy} report={report} />- </div>- <div className="row justify-between gap-1 border-border border-t p-2">- <div className="col md:row gap-1">- <TimeWindowPicker- className="min-w-0"- endDate={report.endDate}- onChange={setRange}- onEndDateChange={setEndDate}- onIntervalChange={setInterval}- onStartDateChange={setStartDate}- startDate={report.startDate}- value={report.range}- />- <ReportInterval- chartType={chartType}- className="min-w-0"- interval={interval}- onChange={setInterval}- range={range}- />- <ReportChartType- onChange={(type) => {- setChartType(type);- }}- value={chartType}- />- </div>- <Button- icon={SaveIcon}- onClick={() => {- pushModal('SaveReport', {- report,- disableRedirect: true,- });- }}- size="sm"- variant="outline"- >- Save report- </Button>- </div>- </div>- );-}diff --git a/apps/start/src/components/chat/chat-runtime.tsx b/apps/start/src/components/chat/chat-runtime.tsxnew file mode 100644index 000000000..6d81d6a9b--- /dev/null+++ b/apps/start/src/components/chat/chat-runtime.tsx@@ -0,0 +1,237 @@+import { getChatClient } from '@/agents/client';+import { usePageContextValue } from '@/contexts/page-context';+import { useAppContext } from '@/hooks/use-app-context';+import { useAppParams } from '@/hooks/use-app-params';+import { useTRPC } from '@/integrations/trpc/react';+import { useAgent } from '@better-agent/client/react';+import { useMutation, useQueryClient } from '@tanstack/react-query';+import {+ createContext,+ type ReactNode,+ useContext,+ useEffect,+ useMemo,+ useRef,+ useState,+} from 'react';+import { useChatState } from './chat-context';+import { chatToolHandlers } from './tool-handlers';+import { streamTitle } from './title-stream';++/**+ * Drawer-scoped runtime that owns the `useAgent()` instance and exposes+ * `messages`, `status`, `sendMessage`, `stop` to body + footer via a+ * tiny context. Mounts inside the drawer, between the header and the+ * body/footer pair.+ *+ * Why this is here and not in a global provider:+ * - The `useAgent()` call itself is a hook — it can't move without+ * mounting. Putting it on the drawer means the chat client is+ * only active when the drawer is open.+ * - Page context is read here so every send carries the user's+ * current view (project, page, filters). Re-evaluates on each+ * send via the closure — no refs needed.+ * - When `agentName` or `conversationId` changes, the controller+ * rebuilds. Better Agent handles hydration via `hydrateFromServer`.+ */++type ChatRuntimeValue = ReturnType<typeof useAgent> & {+ /** Send a plain-text message with the current page context attached. */+ send: (text: string) => void;+};++const ChatRuntimeContext = createContext<ChatRuntimeValue | null>(null);++export function ChatRuntimeProvider({ children }: { children: ReactNode }) {+ const { apiUrl } = useAppContext();+ const { projectId, organizationId } = useAppParams();+ const {+ agentName,+ conversationId,+ setStreamingTitle,+ pendingMessage,+ setPendingMessage,+ } = useChatState();+ const pageContext = usePageContextValue();+ const trpc = useTRPC();+ const queryClient = useQueryClient();++ const client = useMemo(() => getChatClient(apiUrl), [apiUrl]);++ const renameConversation = useMutation(+ trpc.conversation.rename.mutationOptions(),+ );++ // Title streams run fire-and-forget. If the user switches or closes+ // the conversation before the stream finishes, we abort so:+ // - the stream stops pulling from the network+ // - stale `setStreamingTitle(partial)` calls don't flash the old+ // title into the header of the new conversation (global state)+ // The ref is cleared on unmount; the provider remounts on+ // conversation switch (via `key={conversationId}`) which triggers+ // the cleanup.+ const titleAbortRef = useRef<AbortController | null>(null);+ useEffect(+ () => () => {+ titleAbortRef.current?.abort();+ titleAbortRef.current = null;+ },+ [],+ );++ const agent = useAgent(client, {+ agent: agentName,+ conversationId,+ hydrateFromServer: true,+ optimisticUserMessage: true,+ // Better Agent forwards tool calls for any tool declared via+ // `.client()` on the server (see `apps/api/src/agents/tools/ui.ts`)+ // to the matching entry here. Typed via `ToolHandlers<ChatApp>`+ // on the map itself, so this line stays cast-free.+ toolHandlers: chatToolHandlers,+ onFinish: () => {+ // Refresh the conversation list so the new row appears in the+ // header dropdown.+ queryClient.invalidateQueries(trpc.conversation.list.pathFilter());+ },+ });++ const value = useMemo<ChatRuntimeValue>(+ () => ({+ ...agent,+ send: (text: string) => {+ const trimmed = text.trim();+ if (!trimmed) return;+ if (agent.status === 'submitted' || agent.status === 'streaming') {+ return;+ }+ const isFirstTurn = agent.messages.length === 0;++ void agent.sendMessage({+ input: text,+ // The `agentName` is a runtime-resolved string so TypeScript+ // can't narrow `useAgent`'s context type — we know the shape+ // from `chatContextSchema` on the server.+ // biome-ignore lint/suspicious/noExplicitAny: see comment above+ context: {+ projectId,+ organizationId,+ pageContext: pageContext ?? undefined,+ } as any,+ });++ // On the first turn, kick off a parallel title stream. Deltas+ // flow into `streamingTitle` so the header renders the title+ // word-by-word. When the stream finishes we persist via TRPC+ // so the title survives a reload, but we leave `streamingTitle`+ // set — it's the in-memory source of truth for this session.+ // It gets cleared on `newConversation()` / `switchConversation()`.+ if (isFirstTurn) {+ // Cancel any previously in-flight title (shouldn't exist on+ // a first turn, but defensive) and start a fresh controller+ // bound to this runtime's lifecycle.+ titleAbortRef.current?.abort();+ const controller = new AbortController();+ titleAbortRef.current = controller;+ const idAtSend = conversationId;+ setStreamingTitle('');+ void (async () => {+ const finalTitle = await streamTitle(+ client,+ trimmed,+ (partial) => {+ if (controller.signal.aborted) return;+ setStreamingTitle(partial);+ },+ controller.signal,+ );+ if (controller.signal.aborted || !finalTitle) return;+ try {+ await renameConversation.mutateAsync({+ id: idAtSend,+ title: finalTitle,+ projectId,+ });+ queryClient.invalidateQueries(+ trpc.conversation.list.pathFilter(),+ );+ } catch (err) {+ console.error('[chat] conversation rename failed', err);+ }+ })();+ }+ },+ }),+ [+ agent,+ client,+ conversationId,+ projectId,+ organizationId,+ pageContext,+ renameConversation,+ setStreamingTitle,+ ],+ );++ // Drain the pending message left by the sidebar composer.+ //+ // Timing is tricky because of `hydrateFromServer: true`:+ // useAgent's initial snapshot reports status="ready", then its+ // init() effect flips it to "hydrating", and finally back to+ // "ready" once hydration completes. If we send on the very first+ // "ready", init() aborts the run moments later.+ //+ // We model this as an explicit state machine:+ // 'init' — mount frame before init() has run+ // 'hydrating' — saw a non-ready status at least once+ // 'settled' — hydration finished, safe to send+ //+ // For brand-new conversations Better Agent may never leave 'ready'+ // (nothing to load). A single setTimeout(0) on mount flips 'init'+ // to 'settled' after the current task queue drains, which lets the+ // drain effect fire for that case too.+ type HydrationPhase = 'init' | 'hydrating' | 'settled';+ const [hydrationPhase, setHydrationPhase] = useState<HydrationPhase>('init');++ useEffect(() => {+ setHydrationPhase((prev) => {+ if (agent.status !== 'ready') return 'hydrating';+ if (prev === 'hydrating') return 'settled';+ return prev;+ });+ }, [agent.status]);++ useEffect(() => {+ const id = window.setTimeout(() => {+ setHydrationPhase((prev) => (prev === 'init' ? 'settled' : prev));+ }, 0);+ return () => window.clearTimeout(id);+ }, []);++ useEffect(() => {+ if (hydrationPhase !== 'settled') return;+ if (agent.status !== 'ready') return;+ if (!pendingMessage) return;+ const text = pendingMessage;+ // Clear first to prevent re-entry: the effect re-runs when `value`+ // rebuilds (it depends on agent state), and without the early null+ // guard we'd send twice.+ setPendingMessage(null);+ value.send(text);+ }, [hydrationPhase, agent.status, pendingMessage, setPendingMessage, value]);++ return (+ <ChatRuntimeContext.Provider value={value}>+ {children}+ </ChatRuntimeContext.Provider>+ );+}++export function useChatRuntime(): ChatRuntimeValue {+ const value = useContext(ChatRuntimeContext);+ if (!value) {+ throw new Error('useChatRuntime must be used inside <ChatRuntimeProvider>');+ }+ return value;+}diff --git a/apps/start/src/components/chat/chat.tsx b/apps/start/src/components/chat/chat.tsxdeleted file mode 100644index 3aab01d1d..000000000--- a/apps/start/src/components/chat/chat.tsx+++ /dev/null@@ -1,74 +0,0 @@-import { ChatForm } from '@/components/chat/chat-form';-import { ChatMessages } from '@/components/chat/chat-messages';-import { useAppContext } from '@/hooks/use-app-context';-import { useChat } from '@ai-sdk/react';-import type { IServiceOrganization } from '@openpanel/db';-import type { UIMessage } from 'ai';-import { parseAsBoolean, useQueryState } from 'nuqs';-import { toast } from 'sonner';--const getErrorMessage = (error: Error) => {- try {- const parsed = JSON.parse(error.message);- return parsed.message || error.message;- } catch (e) {- return error.message;- }-};-export default function Chat({- initialMessages,- projectId,- organization,-}: {- initialMessages?: UIMessage[];- projectId: string;- organization: IServiceOrganization;-}) {- const context = useAppContext();-- const { messages, input, handleInputChange, handleSubmit, status, append } =- useChat({- onError(error) {- const message = getErrorMessage(error);- toast.error(message);- },- api: `${context.apiUrl}/ai/chat?projectId=${projectId}`,- initialMessages: (initialMessages ?? []) as any,- fetch: (url, options) => {- return fetch(url, {- ...options,- credentials: 'include',- mode: 'cors',- });- },- });-- const [debug] = useQueryState('debug', parseAsBoolean.withDefault(false));- const isLimited = Boolean(- messages.length > 5 &&- (organization.isCanceled ||- organization.isTrial ||- organization.isWillBeCanceled ||- organization.isExceeded ||- organization.isExpired),- );-- return (- <div className="h-screen w-full col relative">- <ChatMessages- messages={messages}- debug={debug}- status={status}- isLimited={isLimited}- />- <ChatForm- handleSubmit={handleSubmit}- input={input}- handleInputChange={handleInputChange}- append={append}- projectId={projectId}- isLimited={isLimited}- />- </div>- );-}diff --git a/apps/start/src/components/chat/model-picker.tsx b/apps/start/src/components/chat/model-picker.tsxnew file mode 100644index 000000000..f880ec629--- /dev/null+++ b/apps/start/src/components/chat/model-picker.tsx@@ -0,0 +1,70 @@+import { Button } from '@/components/ui/button';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';+import { type ChatModelOption, getModelLabel } from '@/agents/models';+import { CheckIcon, ChevronDownIcon } from 'lucide-react';+import { useChatState } from './chat-context';++/**+ * Model (= agent) picker for the chat header. Each entry corresponds+ * to one Better Agent definition; selecting a model swaps to a+ * different agent name on the next render.+ */+export function ModelPicker() {+ const { agentName, setAgent, models } = useChatState();++ const grouped = models.reduce<Record<string, ChatModelOption[]>>(+ (acc, m) => {+ (acc[m.group] ??= []).push(m);+ return acc;+ },+ {},+ );++ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ size="sm"+ className="h-7 px-2 text-xs gap-1 text-muted-foreground"+ aria-label="Select model"+ title="Select model"+ >+ <span className="truncate max-w-[140px]">+ {getModelLabel(agentName)}+ </span>+ <ChevronDownIcon className="size-3" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-56">+ {Object.entries(grouped).map(([group, items], idx) => (+ <div key={group}>+ {idx > 0 && <DropdownMenuSeparator />}+ <DropdownMenuLabel className="text-[11px] uppercase tracking-wide text-muted-foreground">+ {group}+ </DropdownMenuLabel>+ {items.map((m) => (+ <DropdownMenuItem+ key={m.id}+ onSelect={() => setAgent(m.id)}+ className="flex items-center justify-between gap-2"+ >+ <span className="truncate">{m.label}</span>+ {agentName === m.id && (+ <CheckIcon className="size-3 shrink-0 text-foreground" />+ )}+ </DropdownMenuItem>+ ))}+ </div>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/apps/start/src/components/chat/sidebar-chat-composer.tsx b/apps/start/src/components/chat/sidebar-chat-composer.tsxnew file mode 100644index 000000000..ea2eb4bce--- /dev/null+++ b/apps/start/src/components/chat/sidebar-chat-composer.tsx@@ -0,0 +1,83 @@+import { Button } from '@/components/ui/button';+import { cn } from '@/utils/cn';+import { ArrowUpIcon, SparklesIcon } from 'lucide-react';+import { useState } from 'react';+import { useChatState } from './chat-context';++/**+ * Compact "Ask AI" composer for the sidebar.+ *+ * Single-row layout:+ * [✨] Ask AI anything… [⌘J] | [↑ send]+ *+ * The trailing slot shows the keyboard-shortcut hint while the input+ * is empty and swaps to a send button the moment the user starts+ * typing. Submitting stashes the draft on `chatState.pendingMessage`+ * and opens a fresh conversation — the drawer's runtime drains the+ * pending message once `useAgent` is ready.+ */+export function SidebarChatComposer() {+ const { setPendingMessage, openNewChat } = useChatState();+ const [text, setText] = useState('');+ const hasText = text.trim().length > 0;++ const submit = (e?: React.FormEvent) => {+ e?.preventDefault();+ const value = text.trim();+ if (!value) return;+ setPendingMessage(value);+ openNewChat();+ setText('');+ };++ return (+ <form+ onSubmit={submit}+ className={cn(+ 'mb-4 flex items-center gap-1.5 rounded-md border bg-card pl-2 pr-1',+ 'focus-within:ring-1 focus-within:ring-ring transition-shadow',+ )}+ >+ <SparklesIcon className="size-4 text-muted-foreground shrink-0" />+ <input+ type="text"+ value={text}+ onChange={(e) => setText(e.target.value)}+ placeholder="Ask AI anything…"+ className={cn(+ 'flex-1 min-w-0 bg-transparent text-sm py-2 text-foreground',+ 'placeholder:text-muted-foreground/70',+ 'border-0 outline-none ring-0 shadow-none',+ 'focus:outline-none focus:ring-0 focus-visible:outline-none focus-visible:ring-0',+ )}+ onKeyDown={(e) => {+ if (e.key === 'Enter') {+ e.preventDefault();+ submit();+ }+ }}+ />+ {hasText ? (+ <Button+ type="submit"+ size="icon"+ variant="default"+ className="size-6 rounded-sm shrink-0"+ aria-label="Send to AI"+ >+ <ArrowUpIcon className="size-3" />+ </Button>+ ) : (+ <kbd+ className={cn(+ 'shrink-0 rounded border bg-muted px-1.5 py-0.5 font-mono text-[11px]',+ 'text-muted-foreground',+ )}+ aria-label="Keyboard shortcut: Cmd+J"+ >+ ⌘J+ </kbd>+ )}+ </form>+ );+}diff --git a/apps/start/src/components/chat/title-stream.tsx b/apps/start/src/components/chat/title-stream.tsxnew file mode 100644index 000000000..de0be5072--- /dev/null+++ b/apps/start/src/components/chat/title-stream.tsx@@ -0,0 +1,49 @@+import type { AppClient } from '@/agents/client';++/**+ * Stream a conversation title from the backend `__titler` agent.+ *+ * Calls `onDelta(fullText)` after every text event so the caller can+ * render the title as it's generated. Returns the final accumulated+ * title string (trimmed), or null if nothing useful was produced.+ *+ * Pass an `AbortSignal` to cancel an in-flight stream (e.g. when the+ * user switches or closes the conversation before the title finishes).+ * Once aborted the function returns null and stops calling `onDelta`.+ *+ * Fails silently — titles are non-critical; the header just falls+ * back to "Untitled chat" or the persisted DB value.+ */+export async function streamTitle(+ client: AppClient,+ firstUserText: string,+ onDelta: (text: string) => void,+ signal?: AbortSignal,+): Promise<string | null> {+ const trimmed = firstUserText.trim().slice(0, 400);+ if (!trimmed) return null;+ if (signal?.aborted) return null;++ let accumulated = '';+ try {+ const iterable = client.stream('__titler', {+ input: `Generate a 3-5 word title for a chat that started with: "${trimmed}"`,+ // biome-ignore lint/suspicious/noExplicitAny: titler agent has no typed context; its run-input shape is generic+ } as any);+ for await (const event of iterable) {+ if (signal?.aborted) return null;+ // Better Agent emits `TEXT_MESSAGE_CONTENT` with a `delta` field+ // for each streamed chunk of assistant text.+ const maybe = event as { type?: string; delta?: string };+ if (maybe.type === 'TEXT_MESSAGE_CONTENT' && typeof maybe.delta === 'string') {+ accumulated += maybe.delta;+ onDelta(accumulated.trim().slice(0, 80));+ }+ }+ if (signal?.aborted) return null;+ return accumulated.trim().slice(0, 80) || null;+ } catch (err) {+ console.error('[chat] title stream failed', err);+ return null;+ }+}diff --git a/apps/start/src/components/chat/tool-handlers.ts b/apps/start/src/components/chat/tool-handlers.tsnew file mode 100644index 000000000..e5fc6aea6--- /dev/null+++ b/apps/start/src/components/chat/tool-handlers.ts@@ -0,0 +1,120 @@+import type {+ ApplyFiltersInput,+ ChatClientToolHandlers,+ SetEventNamesFilterInput,+ SetPropertyFiltersInput,+} from '@openpanel/validation';++/**+ * Client-side handlers for tools the LLM can invoke to mutate page+ * state. Better Agent emits these as `tool-call` parts with no server+ * execution; the controller forwards each call to the matching entry+ * here, and the return value is sent back as the tool's `output`.+ *+ * Keep handlers tiny and side-effect-only — they shouldn't render UI+ * or maintain state of their own.+ *+ * URL params we mutate map 1:1 to what the dashboard hooks read:+ * - `range`, `start`, `end`, `overrideInterval` ← `useOverviewOptions`+ * - `events` ← `useEventQueryNamesFilter`+ * - `f` ← `useEventQueryFilters`+ *+ * After mutating the URL we dispatch a `popstate` event so nuqs picks+ * up the change without a hook subscription on our side.+ *+ * Handler types come from `@openpanel/validation` (shared with the+ * server's tool schemas) so the map stays in sync with the Zod inputs+ * without crossing the app boundary for its type.+ */++type PropertyFilter = SetPropertyFiltersInput['filters'][number];++function pushUrl(url: URL): void {+ window.history.pushState(null, '', url.toString());+ window.dispatchEvent(new PopStateEvent('popstate'));+}++function applyFilters(input: ApplyFiltersInput): {+ applied: boolean;+ applied_filters: ApplyFiltersInput;+} {+ if (typeof window === 'undefined') {+ return { applied: false, applied_filters: input };+ }+ const url = new URL(window.location.href);++ if (input.startDate && input.endDate) {+ url.searchParams.set('range', 'custom');+ url.searchParams.set('start', input.startDate);+ url.searchParams.set('end', input.endDate);+ } else if (input.range) {+ url.searchParams.set('range', input.range);+ url.searchParams.delete('start');+ url.searchParams.delete('end');+ }++ if (input.interval) {+ url.searchParams.set('overrideInterval', input.interval);+ }++ pushUrl(url);+ return { applied: true, applied_filters: input };+}++/**+ * Mirrors the serializer in `useEventQueryFilters` — each filter is+ * `name,operator,value1|value2`, joined by `;`. We URL-encode the+ * values to match the parser.+ */+function serializePropertyFilters(filters: PropertyFilter[]): string {+ return filters+ .map((f) => {+ const op = f.operator ?? 'is';+ const values = f.value.map((v) => encodeURIComponent(v.trim())).join('|');+ return `${f.name},${op},${values}`;+ })+ .join(';');+}++function setPropertyFilters(input: SetPropertyFiltersInput): {+ applied: boolean;+ count: number;+} {+ if (typeof window === 'undefined') {+ return { applied: false, count: 0 };+ }+ const url = new URL(window.location.href);+ if (input.filters.length === 0) {+ url.searchParams.delete('f');+ } else {+ url.searchParams.set('f', serializePropertyFilters(input.filters));+ }+ pushUrl(url);+ return { applied: true, count: input.filters.length };+}++function setEventNamesFilter(input: SetEventNamesFilterInput): {+ applied: boolean;+ count: number;+} {+ if (typeof window === 'undefined') {+ return { applied: false, count: 0 };+ }+ const url = new URL(window.location.href);+ if (input.eventNames.length === 0) {+ url.searchParams.delete('events');+ } else {+ // nuqs `parseAsArrayOf(parseAsString)` defaults to comma-separated.+ url.searchParams.set('events', input.eventNames.join(','));+ }+ pushUrl(url);+ return { applied: true, count: input.eventNames.length };+}++export const chatToolHandlers: ChatClientToolHandlers = {+ apply_filters: async (input) => applyFilters(input as ApplyFiltersInput),+ set_property_filters: async (input) =>+ setPropertyFilters(input as SetPropertyFiltersInput),+ set_event_names_filter: async (input) =>+ setEventNamesFilter(input as SetEventNamesFilterInput),+};diff --git a/apps/start/src/components/chat/tool-results/chat-metrics-result.tsx b/apps/start/src/components/chat/tool-results/chat-metrics-result.tsxnew file mode 100644index 000000000..cfbd8a3ed--- /dev/null+++ b/apps/start/src/components/chat/tool-results/chat-metrics-result.tsx@@ -0,0 +1,62 @@+import { isMetricsLike } from './output-types';+import { ResultCard, ToolStateGuard } from './shared';+import type { ToolResultProps } from './types';++/**+ * Renders simple metric grids for tools like `get_analytics_overview`+ * and `get_profile_metrics`. Tools return a flat object of named values;+ * we render up to 6 of them as labelled tiles.+ */+export function ChatMetricsResult({ part }: ToolResultProps) {+ return (+ <ToolStateGuard+ state={part.state}+ errorText={part.errorText}+ toolName={part.type.replace(/^tool-/, '')}+ >+ <ChatMetricsInner output={part.output} />+ </ToolStateGuard>+ );+}++function ChatMetricsInner({ output }: { output: unknown }) {+ if (!isMetricsLike(output)) return null;++ const entries = Object.entries(output).filter(+ (entry): entry is [string, number | string] =>+ typeof entry[1] === 'number' || typeof entry[1] === 'string',+ );+ if (entries.length === 0) return null;++ return (+ <ResultCard>+ <div className="grid grid-cols-2 sm:grid-cols-3 divide-x divide-y">+ {entries.slice(0, 6).map(([key, value]) => (+ <div key={key} className="p-3">+ <div className="text-[11px] uppercase tracking-wide text-muted-foreground">+ {humanize(key)}+ </div>+ <div className="text-sm font-semibold font-mono tabular-nums mt-0.5">+ {formatValue(value)}+ </div>+ </div>+ ))}+ </div>+ </ResultCard>+ );+}++function humanize(key: string): string {+ return key+ .replace(/_/g, ' ')+ .replace(/([a-z])([A-Z])/g, '$1 $2')+ .replace(/^\w/, (c) => c.toUpperCase());+}++function formatValue(v: number | string): string {+ if (typeof v === 'number') {+ if (Number.isInteger(v)) return v.toLocaleString();+ return v.toFixed(2);+ }+ return v;+}diff --git a/apps/start/src/components/chat/tool-results/chat-profile-result.tsx b/apps/start/src/components/chat/tool-results/chat-profile-result.tsxnew file mode 100644index 000000000..f775f9354--- /dev/null+++ b/apps/start/src/components/chat/tool-results/chat-profile-result.tsx@@ -0,0 +1,116 @@+import {+ asProfileFullOutput,+ isProfileFullError,+ type ProfileFullSuccess,+} from './output-types';+import {+ ResultCard,+ ResultLabel,+ ResultRow,+ ResultValue,+ ToolStateGuard,+} from './shared';+import type { ToolResultProps } from './types';++/**+ * Renders the result of `get_profile_full` — profile + metrics + recent+ * sessions. Card-with-rows layout so it stays narrow-friendly.+ */+export function ChatProfileFullResult({ part }: ToolResultProps) {+ return (+ <ToolStateGuard+ state={part.state}+ errorText={part.errorText}+ toolName={part.type.replace(/^tool-/, '')}+ >+ <Inner output={part.output} />+ </ToolStateGuard>+ );+}++function Inner({ output }: { output: unknown }) {+ const value = asProfileFullOutput(output);+ if (!value) {+ return (+ <ResultCard>+ <div className="px-3 py-2 text-sm text-muted-foreground">+ No profile+ </div>+ </ResultCard>+ );+ }++ if (isProfileFullError(value)) {+ return (+ <ResultCard>+ <div className="px-3 py-2 text-sm text-muted-foreground">+ {value.error}+ </div>+ </ResultCard>+ );+ }++ return <SuccessCard value={value} />;+}++function SuccessCard({ value }: { value: ProfileFullSuccess }) {+ const { profile, metrics, dashboard_url } = value;+ const title =+ profile &&+ (`${profile.firstName ?? ''} ${profile.lastName ?? ''}`.trim() ||+ profile.email ||+ profile.id);++ return (+ <ResultCard title={title || 'Profile'}>+ {metrics && (+ <div className="border-b">+ {typeof metrics.sessions === 'number' && (+ <ResultRow>+ <ResultLabel>Sessions</ResultLabel>+ <ResultValue>{metrics.sessions}</ResultValue>+ </ResultRow>+ )}+ {typeof metrics.totalEvents === 'number' && (+ <ResultRow>+ <ResultLabel>Total events</ResultLabel>+ <ResultValue>{metrics.totalEvents}</ResultValue>+ </ResultRow>+ )}+ {typeof metrics.avgSessionDurationMin === 'number' && (+ <ResultRow>+ <ResultLabel>Avg session</ResultLabel>+ <ResultValue>+ {metrics.avgSessionDurationMin.toFixed(1)} min+ </ResultValue>+ </ResultRow>+ )}+ {typeof metrics.bounceRate === 'number' && (+ <ResultRow>+ <ResultLabel>Bounce rate</ResultLabel>+ <ResultValue>+ {(metrics.bounceRate * 100).toFixed(0)}%+ </ResultValue>+ </ResultRow>+ )}+ {typeof metrics.revenue === 'number' && metrics.revenue > 0 && (+ <ResultRow>+ <ResultLabel>Revenue</ResultLabel>+ <ResultValue>${metrics.revenue.toFixed(2)}</ResultValue>+ </ResultRow>+ )}+ </div>+ )}+ {dashboard_url && (+ <a+ href={dashboard_url}+ target="_blank"+ rel="noopener noreferrer"+ className="block px-3 py-1.5 text-sm text-muted-foreground hover:underline"+ >+ Open profile →+ </a>+ )}+ </ResultCard>+ );+}diff --git a/apps/start/src/components/chat/tool-results/chat-report-result.tsx b/apps/start/src/components/chat/tool-results/chat-report-result.tsxnew file mode 100644index 000000000..8d119f70e--- /dev/null+++ b/apps/start/src/components/chat/tool-results/chat-report-result.tsx@@ -0,0 +1,196 @@+import { ReportChart } from '@/components/report-chart';+import { Button } from '@/components/ui/button';+import { pushModal } from '@/modals';+import type { IReport, IReportInput } from '@openpanel/validation';+import { SaveIcon } from 'lucide-react';+import { asReportOutput } from './output-types';+import { ResultCard, ToolStateGuard } from './shared';+import type { ToolResultProps } from './types';++/**+ * Renders the result of `get_report_data` / `generate_report` /+ * `preview_report_with_changes` / `get_funnel` / `get_rolling_active_users` —+ * all return `{ report, data }` we can plug into `<ReportChart>`.+ *+ * Title priority (first match wins):+ * 1. `output.name` if the tool returned one (e.g. a saved report's name)+ * 2. A nice derived title from the tool's INPUT args (funnel → "Funnel: A → B", etc.)+ * 3. `"<CHART_TYPE> chart"` fallback+ */+export function ChatReportResult({ part }: ToolResultProps) {+ return (+ <ToolStateGuard+ state={part.state}+ errorText={part.errorText}+ toolName={part.type.replace(/^tool-/, '')}+ >+ <ChatReportInner+ output={part.output}+ input={part.input}+ toolType={part.type}+ />+ </ToolStateGuard>+ );+}++function ChatReportInner({+ output,+ input,+ toolType,+}: {+ output: unknown;+ input: unknown;+ toolType: string;+}) {+ const value = asReportOutput(output);+ if (!value || value.error) {+ return (+ <ResultCard>+ <div className="px-3 py-2 text-sm text-muted-foreground">+ {value?.error ?? 'No data'}+ </div>+ </ResultCard>+ );+ }++ const report = value.report;+ if (!report || !report.chartType) {+ return (+ <ResultCard title={value.name ?? 'Report'}>+ <div className="px-3 py-2 text-sm text-muted-foreground">+ Report data returned but no renderable config.+ </div>+ </ResultCard>+ );+ }++ const title =+ value.name ??+ deriveTitleFromInput(toolType, input) ??+ `${humanizeChartType(String(report.chartType))} report`;++ return (+ <ResultCard title={title}>+ <div className="p-2">+ <ReportChart+ report={report as unknown as IReportInput}+ lazy={false}+ options={{+ hideLegend: false,+ hideXAxis: false,+ minHeight: 180,+ maxHeight: 260,+ }}+ />+ </div>+ {value.dashboard_url && (+ <div className="border-t px-3 py-1.5 flex items-center justify-between gap-2">+ <a+ href={value.dashboard_url}+ target="_blank"+ rel="noopener noreferrer"+ className="text-sm text-muted-foreground hover:underline"+ >+ Open in dashboard →+ </a>+ {!report.id && (+ <Button+ size="sm"+ variant="ghost"+ className="h-6 text-sm"+ onClick={() =>+ pushModal('SaveReport', {+ report: report as unknown as IReport,+ disableRedirect: true,+ })+ }+ >+ <SaveIcon className="size-3 mr-1" />+ Save+ </Button>+ )}+ </div>+ )}+ </ResultCard>+ );+}++/**+ * Build a human title from the tool call's input args. The model+ * often calls chart tools without setting `output.name` explicitly+ * — we can do better than `"LINEAR chart"` by reading what the+ * user actually asked for.+ */+function deriveTitleFromInput(toolType: string, input: unknown): string | null {+ if (!input || typeof input !== 'object') return null;+ const args = input as {+ steps?: unknown;+ series?: Array<{ name?: string; displayName?: string }>;+ chartType?: string;+ windowDays?: number;+ days?: number;+ };++ switch (toolType) {+ case 'tool-get_funnel': {+ if (Array.isArray(args.steps) && args.steps.length > 0) {+ const names = args.steps.filter((s): s is string => typeof s === 'string');+ if (names.length > 0) return `Funnel: ${names.join(' → ')}`;+ }+ return 'Funnel';+ }++ case 'tool-get_rolling_active_users': {+ const w = args.windowDays ?? 1;+ const label = w === 1 ? 'DAU' : w === 7 ? 'WAU' : w === 30 ? 'MAU' : `${w}-day active users`;+ const days = args.days ?? 30;+ return `${label} — last ${days} days`;+ }++ case 'tool-generate_report': {+ const events = Array.isArray(args.series)+ ? args.series+ .map((s) => s?.displayName || s?.name)+ .filter((n): n is string => typeof n === 'string' && n.length > 0)+ : [];+ const kind = args.chartType+ ? humanizeChartType(args.chartType)+ : 'Report';+ if (events.length === 0) return kind;+ if (events.length === 1) return `${kind}: ${events[0]}`;+ return `${kind}: ${events.join(', ')}`;+ }++ default:+ return null;+ }+}++function humanizeChartType(type: string): string {+ switch (type) {+ case 'linear':+ return 'Line chart';+ case 'bar':+ return 'Bar chart';+ case 'area':+ return 'Area chart';+ case 'pie':+ return 'Pie chart';+ case 'funnel':+ return 'Funnel';+ case 'metric':+ return 'Metric';+ case 'retention':+ return 'Retention';+ case 'histogram':+ return 'Histogram';+ case 'sankey':+ return 'Sankey';+ case 'map':+ return 'Map';+ case 'conversion':+ return 'Conversion';+ default:+ return type.charAt(0).toUpperCase() + type.slice(1);+ }+}diff --git a/apps/start/src/components/chat/tool-results/chat-table-result.tsx b/apps/start/src/components/chat/tool-results/chat-table-result.tsxnew file mode 100644index 000000000..2895c1036--- /dev/null+++ b/apps/start/src/components/chat/tool-results/chat-table-result.tsx@@ -0,0 +1,179 @@+import { DefaultToolResult } from './default-tool-result';+import { normalizeTableOutput, type TableRow } from './output-types';+import { ResultCard, ToolStateGuard } from './shared';+import type { ToolResultProps } from './types';++/**+ * Generic compact table for top-pages / top-referrers / breakdowns / etc.+ * The shape varies across tools (some return arrays, some `{ rows }`,+ * some `{ data }`); `normalizeTableOutput` is the single shape boundary.+ */+export function ChatTableResult(props: ToolResultProps) {+ const { part } = props;+ // When we can't shape this as a table (output isn't array-like OR the+ // array has 0 rows), fall through to the default "done chip" renderer+ // instead of showing a bare "No rows" card — which looks like an+ // error but usually just means the tool's output shape isn't what+ // we expected (or the user genuinely has no data yet). The chip is+ // tidy, has the real tool label, and lets the user expand to see+ // the raw output if they're curious.+ if (part.state === 'output-available') {+ const { rows } = normalizeTableOutput(part.output);+ if (rows.length === 0) {+ return <DefaultToolResult part={part} />;+ }+ }++ return (+ <ToolStateGuard+ state={part.state}+ errorText={part.errorText}+ toolName={part.type.replace(/^tool-/, '')}+ >+ <ChatTableInner output={part.output} />+ </ToolStateGuard>+ );+}++function ChatTableInner({ output }: { output: unknown }) {+ const { rows, total, truncated } = normalizeTableOutput(output);+ // Empty case is handled at the wrapper level (falls through to+ // DefaultToolResult) — this function only runs with rows present.+ if (rows.length === 0) return null;+ const { labelKey, valueKeys } = inferColumns(rows[0]!);++ return (+ <ResultCard>+ <table className="w-full text-sm">+ <thead className="bg-muted/30">+ <tr>+ <th className="text-left px-3 py-1.5 font-medium text-muted-foreground">+ {humanize(labelKey)}+ </th>+ {valueKeys.map((k) => (+ <th+ key={k}+ className="text-right px-3 py-1.5 font-medium text-muted-foreground"+ >+ {humanize(k)}+ </th>+ ))}+ </tr>+ </thead>+ <tbody>+ {rows.slice(0, 15).map((row, idx) => (+ <tr+ key={typeof row.id === 'string' ? row.id : idx}+ className="border-t"+ >+ <td+ className="px-3 py-1.5 truncate max-w-[200px]"+ title={String(row[labelKey] ?? '')}+ >+ {String(row[labelKey] ?? '')}+ </td>+ {valueKeys.map((k) => (+ <td+ key={k}+ className="text-right px-3 py-1.5 font-mono tabular-nums"+ >+ {formatValue(row[k])}+ </td>+ ))}+ </tr>+ ))}+ </tbody>+ </table>+ {rows.length > 15 && (+ <div className="border-t px-3 py-1 text-[11px] text-muted-foreground">+ Showing 15 of {total ?? rows.length}+ {truncated && ' (truncated)'}+ </div>+ )}+ </ResultCard>+ );+}++// Preferred label columns, in order. The table renderer picks the+// first one present on the row over the file-order default — so a row+// with both `id` and `title` shows the title as the label, not the+// UUID. Add anything else that's a common "this is the human-readable+// name" field below.+const PREFERRED_LABEL_KEYS = [+ 'title',+ 'name',+ 'label',+ 'displayName',+ 'display_name',+ 'event_name',+ 'eventName',+ 'page',+ 'path',+ 'query',+ 'referrer',+ 'referrer_name',+ 'country',+ 'city',+ 'device',+ 'browser',+ 'os',+ 'summary',+] as const;++// Keys we never want as the label column even if they happen to be the+// first string field. UUIDs / opaque ids are unhelpful in the table —+// the model can still reference them in prose.+const UNINTERESTING_LABEL_KEYS = new Set([+ 'id',+ 'projectId',+ 'organizationId',+ 'userId',+ 'profileId',+ 'sessionId',+ 'reportId',+ 'groupId',+ 'dashboardId',+ 'insightId',+ 'threadId',+]);++function inferColumns(first: TableRow): {+ labelKey: string;+ valueKeys: string[];+} {+ const numericKeys: string[] = [];+ const stringKeys: string[] = [];+ for (const [key, value] of Object.entries(first)) {+ if (typeof value === 'number') {+ numericKeys.push(key);+ } else if (typeof value === 'string') {+ stringKeys.push(key);+ }+ }++ // 1. Prefer one of our known descriptive keys.+ const preferred = PREFERRED_LABEL_KEYS.find((k) => k in first);+ // 2. Otherwise the first string key that isn't an opaque id.+ const firstNonId = stringKeys.find((k) => !UNINTERESTING_LABEL_KEYS.has(k));+ // 3. Last resort: the first string (or any) key.+ const labelKey =+ preferred ?? firstNonId ?? stringKeys[0] ?? Object.keys(first)[0]!;++ const valueKeys = numericKeys.slice(0, 3);+ return { labelKey, valueKeys };+}++function humanize(key: string): string {+ return key+ .replace(/_/g, ' ')+ .replace(/([a-z])([A-Z])/g, '$1 $2')+ .replace(/^\w/, (c) => c.toUpperCase());+}++function formatValue(v: unknown): string {+ if (typeof v === 'number') {+ if (Number.isInteger(v)) return v.toLocaleString();+ return v.toFixed(2);+ }+ return v != null ? String(v) : '—';+}diff --git a/apps/start/src/components/chat/tool-results/chat-ui-apply-result.tsx b/apps/start/src/components/chat/tool-results/chat-ui-apply-result.tsxnew file mode 100644index 000000000..1f221cb46--- /dev/null+++ b/apps/start/src/components/chat/tool-results/chat-ui-apply-result.tsx@@ -0,0 +1,113 @@+import { CheckIcon } from 'lucide-react';+import type { ReactNode } from 'react';+import type { ToolResultProps } from './types';++/**+ * Renderers for the client-side UI-mutator tools:+ * - apply_filters (date range / interval)+ * - set_property_filters (country, device, referrer_name, …)+ * - set_event_names_filter (event-name whitelist)+ *+ * These tools run instantly on the client (they just push URL params),+ * so there's nothing to shimmer for. We bypass `ToolStateGuard` and+ * always render a tidy confirmation chip with a summary parsed from+ * the tool's INPUT args — even on the `input-complete` intermediate+ * state the chip looks "done" because the action has already landed.+ */++export function ApplyFiltersResult({ part }: ToolResultProps) {+ const input = (part.input ?? {}) as {+ range?: string;+ startDate?: string;+ endDate?: string;+ interval?: string;+ };+ const parts: string[] = [];+ if (input.startDate && input.endDate) {+ parts.push(`date range: ${input.startDate} → ${input.endDate}`);+ } else if (input.range) {+ parts.push(`date range: ${formatRange(input.range)}`);+ }+ if (input.interval) {+ parts.push(`interval: ${input.interval}`);+ }+ const summary = parts.length > 0 ? parts.join(' · ') : 'filters';+ return <AppliedChip>Applied {summary}</AppliedChip>;+}++export function SetPropertyFiltersResult({ part }: ToolResultProps) {+ const input = (part.input ?? {}) as {+ filters?: Array<{+ name?: string;+ operator?: string;+ value?: string[];+ }>;+ };+ const filters = Array.isArray(input.filters) ? input.filters : [];+ if (filters.length === 0) {+ return <AppliedChip>Cleared property filters</AppliedChip>;+ }+ const summary = filters+ .map((f) => {+ const op = f.operator && f.operator !== 'is' ? ` ${f.operator}` : '';+ const value = Array.isArray(f.value) ? f.value.join(', ') : '';+ return `${f.name}${op}${value ? ` = ${value}` : ''}`;+ })+ .join(' · ');+ return <AppliedChip>Applied filters: {summary}</AppliedChip>;+}++export function SetEventNamesFilterResult({ part }: ToolResultProps) {+ const input = (part.input ?? {}) as { eventNames?: string[] };+ const names = Array.isArray(input.eventNames) ? input.eventNames : [];+ if (names.length === 0) {+ return <AppliedChip>Cleared event-name filter</AppliedChip>;+ }+ return (+ <AppliedChip>+ Filtered to {names.length === 1 ? 'event' : 'events'}: {names.join(', ')}+ </AppliedChip>+ );+}++function AppliedChip({ children }: { children: ReactNode }) {+ return (+ <div className="inline-flex items-center gap-1.5 rounded-md border bg-card px-2.5 py-1 text-sm text-foreground/80">+ <CheckIcon className="size-3.5 text-emerald-500 shrink-0" />+ <span className="truncate">{children}</span>+ </div>+ );+}++function formatRange(range: string): string {+ switch (range) {+ case '30min':+ return 'Last 30 min';+ case 'lastHour':+ return 'Last hour';+ case 'today':+ return 'Today';+ case 'yesterday':+ return 'Yesterday';+ case '7d':+ return 'Last 7 days';+ case '30d':+ return 'Last 30 days';+ case '6m':+ return 'Last 6 months';+ case '12m':+ return 'Last 12 months';+ case 'monthToDate':+ return 'Month to date';+ case 'lastMonth':+ return 'Last month';+ case 'yearToDate':+ return 'Year to date';+ case 'lastYear':+ return 'Last year';+ case 'custom':+ return 'Custom range';+ default:+ return range;+ }+}diff --git a/apps/start/src/components/chat/tool-results/default-tool-result.tsx b/apps/start/src/components/chat/tool-results/default-tool-result.tsxnew file mode 100644index 000000000..df79311c0--- /dev/null+++ b/apps/start/src/components/chat/tool-results/default-tool-result.tsx@@ -0,0 +1,78 @@+import { ChevronRightIcon } from 'lucide-react';+import { useState } from 'react';+import { ResultCard, ToolDoneBadge, ToolStateGuard } from './shared';+import { getToolPhrase } from './tool-labels';+import type { ToolResultProps } from './types';++/**+ * Auto-fallback for tools that don't have a custom UI in the registry.+ * Shows a friendly "Done — <Tool>" chip with click-to-expand JSON.+ */+export function DefaultToolResult({ part }: ToolResultProps) {+ const toolName = part.type.replace(/^tool-/, '');++ return (+ <ToolStateGuard+ state={part.state}+ errorText={part.errorText}+ toolName={toolName}+ >+ <DefaultInner toolName={toolName} output={part.output} />+ </ToolStateGuard>+ );+}++function DefaultInner({+ toolName,+ output,+}: {+ toolName: string;+ output: unknown;+}) {+ const [expanded, setExpanded] = useState(false);++ if (output == null) {+ return (+ <ResultCard title={getToolPhrase(toolName, 'done')}>+ <div className="px-3 py-2 text-sm text-muted-foreground">+ No result.+ </div>+ </ResultCard>+ );+ }++ if (typeof output === 'string') {+ return (+ <ResultCard title={getToolPhrase(toolName, 'done')}>+ <div className="px-3 py-2 text-sm whitespace-pre-wrap">{output}</div>+ </ResultCard>+ );+ }++ // Most "data" tools: render the friendly Done chip with optional+ // JSON drill-down. Tools we want as full cards have their own+ // entry in the registry.+ return (+ <ToolDoneBadge toolName={toolName}>+ <button+ type="button"+ onClick={() => setExpanded((e) => !e)}+ className="flex items-center gap-1 -mx-2.5 -my-2 px-2.5 py-1.5 text-sm text-muted-foreground hover:bg-muted/40 w-[calc(100%+1.25rem)] text-left"+ >+ <ChevronRightIcon+ className={`size-3 transition-transform ${expanded ? 'rotate-90' : ''}`}+ />+ <span className="truncate">+ {Array.isArray(output)+ ? `${output.length} item${output.length === 1 ? '' : 's'}`+ : 'View raw output'}+ </span>+ </button>+ {expanded && (+ <pre className="mt-2 -mx-2.5 -mb-2 px-2.5 py-2 border-t text-[11px] font-mono whitespace-pre-wrap break-all max-h-64 overflow-y-auto bg-muted/20">+ {JSON.stringify(output, null, 2)}+ </pre>+ )}+ </ToolDoneBadge>+ );+}diff --git a/apps/start/src/components/chat/tool-results/output-types.ts b/apps/start/src/components/chat/tool-results/output-types.tsnew file mode 100644index 000000000..0972cead0--- /dev/null+++ b/apps/start/src/components/chat/tool-results/output-types.ts@@ -0,0 +1,127 @@+/**+ * Frontend-side TypeScript types for the chat tool outputs we render+ * with custom UIs. These mirror what the matching backend tool returns+ * — see `apps/api/src/chat/tools/*.ts`. The renderers narrow `unknown`+ * via the type guards below before reading any field.+ *+ * If the backend changes a tool's return shape, the matching renderer+ * will fall back to a "no data" card rather than crashing — that's why+ * we narrow with predicates rather than `as any`.+ */++// ────────────────────────────────────────────────────────────────────+// Metrics (get_analytics_overview, get_profile_metrics)+// ────────────────────────────────────────────────────────────────────++export type MetricsLike = Record<string, unknown>;++export function isMetricsLike(value: unknown): value is MetricsLike {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}++// ────────────────────────────────────────────────────────────────────+// Profile full (get_profile_full)+// ────────────────────────────────────────────────────────────────────++export type ProfileMetrics = {+ sessions?: number;+ totalEvents?: number;+ screenViews?: number;+ avgSessionDurationMin?: number;+ bounceRate?: number;+ revenue?: number;+};++export type ProfileFullSuccess = {+ profile?: {+ id: string;+ firstName?: string | null;+ lastName?: string | null;+ email?: string | null;+ };+ metrics?: ProfileMetrics | null;+ recent_sessions?: unknown[];+ recent_events?: unknown[];+ dashboard_url?: string;+};++export type ProfileFullError = {+ error: string;+ profileId?: string;+};++export type ProfileFullOutput = ProfileFullSuccess | ProfileFullError;++export function isProfileFullError(+ value: ProfileFullOutput,+): value is ProfileFullError {+ return 'error' in value && typeof value.error === 'string';+}++export function asProfileFullOutput(value: unknown): ProfileFullOutput | null {+ if (!value || typeof value !== 'object') return null;+ return value as ProfileFullOutput;+}++// ────────────────────────────────────────────────────────────────────+// Report (get_report_data, generate_report, preview_report_with_changes)+// ────────────────────────────────────────────────────────────────────++export type ReportOutput = {+ data?: unknown;+ report?: {+ id?: string;+ chartType?: string;+ [key: string]: unknown;+ };+ name?: string;+ dashboard_url?: string;+ error?: string;+};++export function asReportOutput(value: unknown): ReportOutput | null {+ if (!value || typeof value !== 'object') return null;+ return value as ReportOutput;+}++// ────────────────────────────────────────────────────────────────────+// Tables (top_pages, top_referrers, country_breakdown, etc.)+// ────────────────────────────────────────────────────────────────────++export type TableRow = Record<string, unknown>;++export type TableNormalized = {+ rows: TableRow[];+ total: number | undefined;+ truncated: boolean;+};++/**+ * Several tools return either an array directly or wrap it in `{ rows }`,+ * `{ data }`, or `{ opportunities }`. This is the one place where we+ * resolve that — every renderer downstream gets a clean `TableRow[]`.+ */+export function normalizeTableOutput(value: unknown): TableNormalized {+ if (Array.isArray(value)) {+ return {+ rows: value as TableRow[],+ total: undefined,+ truncated: false,+ };+ }+ if (value && typeof value === 'object') {+ const o = value as Record<string, unknown>;+ const total = typeof o.total === 'number' ? o.total : undefined;+ const truncated = o._truncated === true;+ if (Array.isArray(o.rows)) {+ return { rows: o.rows as TableRow[], total, truncated };+ }+ if (Array.isArray(o.data)) {+ return { rows: o.data as TableRow[], total, truncated };+ }+ if (Array.isArray(o.opportunities)) {+ return { rows: o.opportunities as TableRow[], total, truncated };+ }+ }+ return { rows: [], total: undefined, truncated: false };+}diff --git a/apps/start/src/components/chat/tool-results/registry.tsx b/apps/start/src/components/chat/tool-results/registry.tsxnew file mode 100644index 000000000..becb556d1--- /dev/null+++ b/apps/start/src/components/chat/tool-results/registry.tsx@@ -0,0 +1,65 @@+import type { FC } from 'react';+import { ChatMetricsResult } from './chat-metrics-result';+import { ChatProfileFullResult } from './chat-profile-result';+import { ChatReportResult } from './chat-report-result';+import { ChatTableResult } from './chat-table-result';+import {+ ApplyFiltersResult,+ SetEventNamesFilterResult,+ SetPropertyFiltersResult,+} from './chat-ui-apply-result';+import { DefaultToolResult } from './default-tool-result';+import type { ToolResultProps } from './types';++/**+ * Map of tool-${toolName} → renderer. Anything not in this map falls+ * through to `DefaultToolResult` which renders an auto-inferred summary.+ *+ * Adding a new backend tool does NOT require touching this map — it'll+ * still render usefully via the default. Only add an entry here if you+ * want a custom UI.+ */+export const chatToolRenderers: Record<string, FC<ToolResultProps>> = {+ // Reports — these all return { chartType, report, data, ... }+ 'tool-get_report_data': ChatReportResult,+ 'tool-generate_report': ChatReportResult,+ 'tool-preview_report_with_changes': ChatReportResult,+ 'tool-get_rolling_active_users': ChatReportResult,+ 'tool-get_funnel': ChatReportResult,++ // Metric cards+ 'tool-get_analytics_overview': ChatMetricsResult,+ 'tool-get_profile_metrics': ChatMetricsResult,++ // Compact tables for breakdowns / lists+ 'tool-get_top_pages': ChatTableResult,+ 'tool-get_top_referrers': ChatTableResult,+ 'tool-get_country_breakdown': ChatTableResult,+ 'tool-get_device_breakdown': ChatTableResult,+ 'tool-get_entry_exit_pages': ChatTableResult,+ 'tool-find_declining_pages': ChatTableResult,+ 'tool-find_profiles': ChatTableResult,+ 'tool-query_events': ChatTableResult,+ 'tool-query_sessions': ChatTableResult,+ 'tool-list_event_names': ChatTableResult,+ 'tool-list_event_properties': ChatTableResult,+ 'tool-list_dashboards': ChatTableResult,+ 'tool-list_reports': ChatTableResult,+ 'tool-list_insights': ChatTableResult,+ 'tool-gsc_get_top_queries': ChatTableResult,+ 'tool-gsc_get_top_pages': ChatTableResult,+ 'tool-gsc_get_query_opportunities': ChatTableResult,+ 'tool-correlate_seo_with_traffic': ChatTableResult,+ 'tool-list_references': ChatTableResult,++ // Profile detail+ 'tool-get_profile_full': ChatProfileFullResult,++ // Client-side UI mutators — render a "done" chip regardless of+ // state (no async work to shimmer for).+ 'tool-apply_filters': ApplyFiltersResult,+ 'tool-set_property_filters': SetPropertyFiltersResult,+ 'tool-set_event_names_filter': SetEventNamesFilterResult,+};++export { DefaultToolResult } from './default-tool-result';diff --git a/apps/start/src/components/chat/tool-results/shared.tsx b/apps/start/src/components/chat/tool-results/shared.tsxnew file mode 100644index 000000000..b85c77717--- /dev/null+++ b/apps/start/src/components/chat/tool-results/shared.tsx@@ -0,0 +1,121 @@+import { Skeleton } from '@/components/skeleton';+import { cn } from '@/utils/cn';+import { AlertCircleIcon, CheckIcon, SparklesIcon } from 'lucide-react';+import type { ReactNode } from 'react';+import { getToolPhrase } from './tool-labels';++/**+ * Wrapper that handles the tool-part state machine. Shows a shimmer+ * activity row while the tool is running, an error card on failure,+ * and the renderer's children on success.+ */+export function ToolStateGuard({+ state,+ errorText,+ toolName,+ pending,+ children,+}: {+ state: string;+ errorText?: string;+ /** Used for the friendly action label on in-progress / completed badges. */+ toolName?: string;+ pending?: ReactNode;+ children: ReactNode;+}) {+ if (state === 'input-streaming' || state === 'input-available') {+ return pending ?? <ToolActivityBadge toolName={toolName} />;+ }+ if (state === 'output-error') {+ return (+ <div className="flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive">+ <AlertCircleIcon className="size-3.5 mt-0.5 shrink-0" />+ <span>{errorText ?? 'Tool failed'}</span>+ </div>+ );+ }+ if (state === 'output-available') {+ return <>{children}</>;+ }+ return null;+}++/**+ * Compact "the AI is working on this" badge with shimmer text. Shown+ * while a tool's input is streaming or it's executing on the server.+ */+export function ToolActivityBadge({ toolName }: { toolName?: string }) {+ const label = toolName ? getToolPhrase(toolName, 'active') : 'Working';+ return (+ <div className="flex items-center gap-2 py-1.5 text-sm">+ <SparklesIcon className="size-3.5 text-muted-foreground shrink-0" />+ <span className="op-shimmer font-medium">{label}…</span>+ </div>+ );+}++/**+ * Compact "done" badge for tools whose output we don't surface as a+ * full card (the model already wrote prose with the result). Renders+ * a small chip you can click to expand into details.+ */+export function ToolDoneBadge({+ toolName,+ children,+}: {+ toolName: string;+ children?: ReactNode;+}) {+ return (+ <details className="group rounded-md border bg-card text-sm">+ <summary className="flex cursor-pointer items-center gap-2 px-2.5 py-1.5 list-none [&::-webkit-details-marker]:hidden">+ <CheckIcon className="size-3 text-emerald-500 shrink-0" />+ <span className="font-medium text-foreground/80">+ {getToolPhrase(toolName, 'done')}+ </span>+ </summary>+ {children && <div className="border-t px-2.5 py-2">{children}</div>}+ </details>+ );+}++export function ResultCard({+ title,+ children,+ className,+}: {+ title?: string;+ children: ReactNode;+ className?: string;+}) {+ return (+ <div className={cn('rounded-md border bg-card overflow-hidden', className)}>+ {title && (+ <div className="border-b px-3 py-1.5 text-sm font-medium text-muted-foreground">+ {title}+ </div>+ )}+ {children}+ </div>+ );+}++export function ResultRow({ children, className }: { children: ReactNode; className?: string }) {+ return (+ <div className={cn('flex items-center justify-between gap-2 px-3 py-1.5 text-sm', className)}>+ {children}+ </div>+ );+}++export function ResultLabel({ children }: { children: ReactNode }) {+ return <span className="text-muted-foreground truncate">{children}</span>;+}++export function ResultValue({ children, mono = true }: { children: ReactNode; mono?: boolean }) {+ return (+ <span className={cn('font-medium tabular-nums shrink-0', mono && 'font-mono')}>{children}</span>+ );+}++export { Skeleton };diff --git a/apps/start/src/components/chat/tool-results/tool-labels.ts b/apps/start/src/components/chat/tool-results/tool-labels.tsnew file mode 100644index 000000000..be70cd4a3--- /dev/null+++ b/apps/start/src/components/chat/tool-results/tool-labels.ts@@ -0,0 +1,278 @@+/**+ * Humanizes raw tool names into action-phrase labels for the UI.+ *+ * Each tool gets a tuple: (verb-form for in-progress, noun-form for+ * completed). E.g.+ * list_event_names → ["Looking up event names", "Event names"]+ *+ * Falls back to a generic transformation when a tool isn't in the+ * map: snake_case → "Snake case", with verb-prefix heuristics+ * ("get_" → "Loading", "list_" → "Looking up", "find_" → "Finding").+ */++const VERB_PREFIXES: Array<[string, string]> = [+ ['list_', 'Looking up'],+ ['get_', 'Loading'],+ ['find_', 'Finding'],+ ['query_', 'Querying'],+ ['analyze_', 'Analyzing'],+ ['compare_', 'Comparing'],+ ['correlate_', 'Correlating'],+ ['explain_', 'Explaining'],+ ['suggest_', 'Suggesting'],+ ['preview_', 'Previewing'],+ ['generate_', 'Generating'],+ ['apply_', 'Applying'],+ ['set_', 'Updating'],+ ['gsc_', 'Loading SEO'],+];++const PHRASES: Record<+ string,+ { active: string; done: string }+> = {+ // Discovery+ list_event_names: { active: 'Looking up event names', done: 'Event names' },+ list_event_properties: {+ active: 'Looking up properties',+ done: 'Event properties',+ },+ get_event_property_values: {+ active: 'Loading property values',+ done: 'Property values',+ },++ // Saved reports & dashboards+ list_dashboards: { active: 'Loading dashboards', done: 'Dashboards' },+ list_reports: { active: 'Loading reports', done: 'Reports' },+ get_report_data: { active: 'Running report', done: 'Report' },+ generate_report: { active: 'Building report', done: 'Report' },++ // Aggregate analytics+ get_analytics_overview: { active: 'Loading overview', done: 'Overview' },+ get_top_pages: { active: 'Loading top pages', done: 'Top pages' },+ get_top_referrers: {+ active: 'Loading top referrers',+ done: 'Top referrers',+ },+ get_country_breakdown: {+ active: 'Loading geo breakdown',+ done: 'Geo breakdown',+ },+ get_device_breakdown: {+ active: 'Loading device breakdown',+ done: 'Device breakdown',+ },+ get_rolling_active_users: {+ active: 'Loading active users',+ done: 'Active users',+ },+ get_funnel: { active: 'Building funnel', done: 'Funnel' },+ get_retention_cohort: {+ active: 'Building retention cohort',+ done: 'Retention',+ },+ get_user_flow: { active: 'Building user flow', done: 'User flow' },++ // Free-form+ query_events: { active: 'Querying events', done: 'Events' },+ query_sessions: { active: 'Querying sessions', done: 'Sessions' },+ find_profiles: { active: 'Finding profiles', done: 'Profiles' },++ // Profile+ get_profile_full: { active: 'Loading profile', done: 'Profile' },+ get_profile_events: {+ active: 'Loading profile events',+ done: 'Profile events',+ },+ get_profile_sessions: {+ active: 'Loading profile sessions',+ done: 'Profile sessions',+ },+ get_profile_metrics: {+ active: 'Loading profile metrics',+ done: 'Profile metrics',+ },+ get_profile_journey: {+ active: 'Loading user journey',+ done: 'User journey',+ },+ get_profile_groups: {+ active: 'Loading profile groups',+ done: 'Profile groups',+ },+ compare_profile_to_average: {+ active: 'Comparing to average',+ done: 'Profile comparison',+ },++ // Session+ get_session_full: { active: 'Loading session', done: 'Session' },+ get_session_path: { active: 'Loading session path', done: 'Session path' },+ get_session_events: {+ active: 'Loading session events',+ done: 'Session events',+ },+ get_similar_sessions: {+ active: 'Finding similar sessions',+ done: 'Similar sessions',+ },+ compare_session_to_typical: {+ active: 'Comparing to typical',+ done: 'Session comparison',+ },+ get_session_referrer_context: {+ active: 'Loading referrer context',+ done: 'Referrer context',+ },+ get_session_replay_summary: {+ active: 'Loading session replay',+ done: 'Session replay',+ },++ // Pages+ get_page_performance: {+ active: 'Loading page performance',+ done: 'Page performance',+ },+ get_page_conversions: {+ active: 'Loading page conversions',+ done: 'Page conversions',+ },+ get_entry_exit_pages: {+ active: 'Loading entry/exit pages',+ done: 'Entry/exit pages',+ },+ find_declining_pages: {+ active: 'Finding declining pages',+ done: 'Declining pages',+ },++ // SEO / GSC+ gsc_get_overview: { active: 'Loading SEO overview', done: 'SEO overview' },+ gsc_get_top_queries: { active: 'Loading top queries', done: 'Top queries' },+ gsc_get_top_pages: {+ active: 'Loading top SEO pages',+ done: 'Top SEO pages',+ },+ gsc_get_query_details: {+ active: 'Loading query details',+ done: 'Query details',+ },+ gsc_get_page_details: {+ active: 'Loading page details',+ done: 'Page details',+ },+ gsc_get_query_opportunities: {+ active: 'Finding query opportunities',+ done: 'Query opportunities',+ },+ gsc_get_cannibalization: {+ active: 'Checking cannibalization',+ done: 'Cannibalization',+ },+ correlate_seo_with_traffic: {+ active: 'Correlating SEO with traffic',+ done: 'SEO/traffic correlation',+ },++ // Events+ analyze_event_distribution: {+ active: 'Analyzing event distribution',+ done: 'Event distribution',+ },+ correlate_events: { active: 'Correlating events', done: 'Event correlation' },+ get_event_property_distribution: {+ active: 'Loading property distribution',+ done: 'Property distribution',+ },+ list_properties_for_event: {+ active: 'Loading properties',+ done: 'Event properties',+ },++ // Insights+ list_insights: { active: 'Loading insights', done: 'Insights' },+ explain_insight: { active: 'Loading insight', done: 'Insight' },+ find_related_insights: {+ active: 'Finding related insights',+ done: 'Related insights',+ },++ // Group+ get_group_full: { active: 'Loading group', done: 'Group' },+ get_group_members: { active: 'Loading group members', done: 'Group members' },+ get_group_events: { active: 'Loading group events', done: 'Group events' },+ get_group_metrics: {+ active: 'Loading group metrics',+ done: 'Group metrics',+ },+ compare_groups: { active: 'Comparing groups', done: 'Group comparison' },++ // Report editor+ preview_report_with_changes: {+ active: 'Previewing changes',+ done: 'Report preview',+ },+ suggest_breakdowns: {+ active: 'Suggesting breakdowns',+ done: 'Breakdown suggestions',+ },+ compare_to_previous_period: {+ active: 'Comparing to previous period',+ done: 'Period comparison',+ },+ find_anomalies_in_current_report: {+ active: 'Finding anomalies',+ done: 'Anomalies',+ },+ explain_filter_impact: {+ active: 'Analyzing filter impact',+ done: 'Filter impact',+ },++ // UI mutators (client-side)+ apply_filters: {+ active: 'Applying date range',+ done: 'Date range updated',+ },+ set_property_filters: {+ active: 'Applying filters',+ done: 'Filters updated',+ },+ set_event_names_filter: {+ active: 'Applying event filter',+ done: 'Event filter updated',+ },++ // References+ list_references: {+ active: 'Loading references',+ done: 'References',+ },+ get_references_around: {+ active: 'Checking references around this date',+ done: 'Nearby references',+ },+};++export type ToolPhrasePhase = 'active' | 'done';++export function getToolPhrase(toolName: string, phase: ToolPhrasePhase): string {+ const explicit = PHRASES[toolName];+ if (explicit) return explicit[phase];++ const matchedPrefix = VERB_PREFIXES.find(([p]) => toolName.startsWith(p));+ const verb = matchedPrefix?.[0] ?? '';+ const verbLabel = matchedPrefix?.[1] ?? 'Running';++ const noun = humanizeNoun(toolName.slice(verb.length) || toolName);+ return phase === 'active' ? `${verbLabel} ${noun.toLowerCase()}` : noun;+}++function humanizeNoun(s: string): string {+ return s+ .replace(/_/g, ' ')+ .replace(/^\w/, (c) => c.toUpperCase())+ .trim();+}diff --git a/apps/start/src/components/chat/tool-results/types.ts b/apps/start/src/components/chat/tool-results/types.tsnew file mode 100644index 000000000..89c0e6b4d--- /dev/null+++ b/apps/start/src/components/chat/tool-results/types.ts@@ -0,0 +1,21 @@+/**+ * Minimal shape for a tool UI part that all renderers consume. We keep+ * this looser than `ToolUIPart` from the AI SDK so the registry can+ * dispatch generically without `any` casts.+ *+ * `output` is `unknown` on purpose: the registry hands the part to a+ * renderer that knows the shape, and the renderer narrows it via the+ * type guards in `output-types.ts`.+ */+export type ToolResultPart = {+ type: string;+ toolCallId: string;+ state: string;+ input?: unknown;+ output?: unknown;+ errorText?: string;+};++export type ToolResultProps = {+ part: ToolResultPart;+};diff --git a/apps/start/src/components/chat/use-chat-open.ts b/apps/start/src/components/chat/use-chat-open.tsnew file mode 100644index 000000000..bf4dade7c--- /dev/null+++ b/apps/start/src/components/chat/use-chat-open.ts@@ -0,0 +1,33 @@+import { parseAsString, useQueryState } from 'nuqs';++/**+ * The `?chat` URL param is the single source of truth for the chat+ * drawer. Possible states:+ * - param absent (null) → drawer closed+ * - param is a string → drawer open, the value is the active+ * conversation id+ *+ * Opening a brand-new conversation = push a freshly generated UUID.+ * Switching to an existing conversation = push its id. Closing =+ * clear the param.+ *+ * This makes conversations linkable (paste a URL, land on that chat)+ * and keeps chat state in the browser history.+ */+export function useChatUrlState() {+ return useQueryState(+ 'chat',+ parseAsString.withOptions({ history: 'push' }),+ );+}++/**+ * Generate a new conversation id. Browser-native UUID when available,+ * fallback to a timestamp+random combo for very old browsers.+ */+export function newConversationId(): string {+ if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) {+ return crypto.randomUUID();+ }+ return `conv_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;+}diff --git a/apps/start/src/components/providers.tsx b/apps/start/src/components/providers.tsxindex 5de3e8ff8..d75cf1cfd 100644--- a/apps/start/src/components/providers.tsx+++ b/apps/start/src/components/providers.tsx@@ -1,5 +1,7 @@+import { ChatStateProvider } from '@/components/chat/chat-context';import { NotificationProvider } from '@/components/notifications/notification-provider';import { TooltipProvider } from '@/components/ui/tooltip';+import { PageContextProvider } from '@/contexts/page-context';import { ModalProvider } from '@/modals';import type { AppStore } from '@/redux';import makeStore from '@/redux';@@ -20,10 +22,14 @@ export function Providers({ children }: { children: React.ReactNode }) {<ThemeProvider><ReduxProvider store={storeRef.current}><TooltipProvider delayDuration={200}>- {children}- <NotificationProvider />- <Toaster />- <ModalProvider />+ <PageContextProvider>+ <ChatStateProvider>+ {children}+ <NotificationProvider />+ <Toaster />+ <ModalProvider />+ </ChatStateProvider>+ </PageContextProvider></TooltipProvider></ReduxProvider></ThemeProvider>diff --git a/apps/start/src/components/sidebar-project-menu.tsx b/apps/start/src/components/sidebar-project-menu.tsxindex 1f381605e..364fb9144 100644--- a/apps/start/src/components/sidebar-project-menu.tsx+++ b/apps/start/src/components/sidebar-project-menu.tsx@@ -32,6 +32,8 @@ import {DropdownMenuTrigger,} from './ui/dropdown-menu';import { Button } from '@/components/ui/button';+import { useChatState } from '@/components/chat/chat-context';+import { SidebarChatComposer } from '@/components/chat/sidebar-chat-composer';import { pushModal } from '@/modals';interface SidebarProjectMenuProps {@@ -43,6 +45,7 @@ export default function SidebarProjectMenu({}: SidebarProjectMenuProps) {return (<>+ <SidebarChatComposer /><div className="mb-2 font-medium text-muted-foreground text-sm">Analytics</div>@@ -87,6 +90,7 @@ export default function SidebarProjectMenu({export function ActionCTAButton() {const navigate = useNavigate();+ const { openChatForContext } = useChatState();const ACTIONS = [{@@ -106,11 +110,7 @@ export function ActionCTAButton() {{label: 'Ask AI',icon: SparklesIcon,- onClick: () =>- navigate({- to: '/$organizationId/$projectId/chat',- from: '/$organizationId/$projectId',- }),+ onClick: () => openChatForContext(),},{label: 'Create dashboard',diff --git a/apps/start/src/components/sidebar.tsx b/apps/start/src/components/sidebar.tsxindex 2649bd915..114796f63 100644--- a/apps/start/src/components/sidebar.tsx+++ b/apps/start/src/components/sidebar.tsx@@ -1,8 +1,9 @@import type { IServiceOrganization } from '@openpanel/db';import { useQuery } from '@tanstack/react-query';import { Link, useLocation, useParams } from '@tanstack/react-router';-import { MenuIcon, XIcon } from 'lucide-react';+import { MenuIcon, SparklesIcon, XIcon } from 'lucide-react';import { useEffect, useState } from 'react';+import { useChatState } from './chat/chat-context';import { FeedbackButton } from './feedback-button';import { LogoSquare } from './logo';import { ProfileToggle } from './profile-toggle';@@ -78,6 +79,8 @@ export function SidebarContainer({const [active, setActive] = useState(false);const location = useLocation();const { isSelfHosted } = useAppContext();+ const { projectId } = useParams({ strict: false });+ const { isOpen: chatOpen, openChatForContext, closeChat } = useChatState();useEffect(() => {setActive(false);@@ -142,6 +145,19 @@ export function SidebarContainer({>Docs</a>+ {projectId && (+ <button+ type="button"+ onClick={() =>+ chatOpen ? closeChat() : openChatForContext()+ }+ className="flex h-12 w-12 items-center justify-center border-border border-r font-medium text-muted-foreground text-sm transition-colors hover:bg-accent hover:text-accent-foreground"+ title="Open AI chat (⌘J)"+ aria-label="Open AI chat"+ >+ <SparklesIcon size={16} />+ </button>+ )}<ProfileToggle className="h-12 flex-1 rounded-none hover:bg-accent hover:text-accent-foreground" /></div>{isSelfHosted && (diff --git a/apps/start/src/contexts/page-context.tsx b/apps/start/src/contexts/page-context.tsxnew file mode 100644index 000000000..00a173b9c--- /dev/null+++ b/apps/start/src/contexts/page-context.tsx@@ -0,0 +1,130 @@+import {+ type MutableRefObject,+ type ReactNode,+ createContext,+ useCallback,+ useContext,+ useEffect,+ useMemo,+ useRef,+ useState,+} from 'react';+import type {+ IChartEventFilter,+ IChartRange,+ IInterval,+ IReportInput,+} from '@openpanel/validation';++/**+ * What the chat backend needs to know about "what the user is currently+ * looking at". Mirrors apps/api/src/chat/types.ts.+ *+ * Each target page calls `usePageContext({...})` in an effect; the+ * provider stores the latest value. The chat drawer reads it via a ref so+ * it always sends the *current* page's context with each request, even on+ * an old conversation.+ */+export type PageContextPage =+ | 'overview'+ | 'insights'+ | 'pages'+ | 'seo'+ | 'sessionDetail'+ | 'profileDetail'+ | 'reportEditor'+ | 'events'+ | 'groupDetail';++export type PageContext = {+ page: PageContextPage;+ route: { projectId: string; organizationId: string };+ ids?: {+ sessionId?: string;+ profileId?: string;+ reportId?: string;+ groupId?: string;+ };+ filters?: {+ range?: IChartRange;+ startDate?: string;+ endDate?: string;+ interval?: IInterval;+ eventNames?: string[];+ eventFilters?: IChartEventFilter[];+ search?: string;+ };+ reportDraft?: IReportInput;+ primer?: Record<string, unknown>;+};++type PageContextValue = {+ context: PageContext | null;+ setContext: (ctx: PageContext | null) => void;+ ref: MutableRefObject<PageContext | null>;+};++const PageContextContext = createContext<PageContextValue | null>(null);++export function PageContextProvider({ children }: { children: ReactNode }) {+ const [context, setContextState] = useState<PageContext | null>(null);+ const ref = useRef<PageContext | null>(null);++ const setContext = useCallback((ctx: PageContext | null) => {+ ref.current = ctx;+ setContextState(ctx);+ }, []);++ const value = useMemo(+ () => ({ context, setContext, ref }),+ [context, setContext],+ );++ return (+ <PageContextContext.Provider value={value}>+ {children}+ </PageContextContext.Provider>+ );+}++function useInternalPageContext(): PageContextValue {+ const value = useContext(PageContextContext);+ if (!value) {+ throw new Error('usePageContext must be used inside <PageContextProvider>');+ }+ return value;+}++/** Read the current page context from React state (causes re-renders). */+export function usePageContextValue(): PageContext | null {+ return useInternalPageContext().context;+}++/**+ * Read the current page context via ref. Use inside `useChat`'s+ * `prepareSendMessagesRequest` so the chat always sends the *latest*+ * page's context without forcing a hook re-run on every keystroke.+ */+export function usePageContextRef(): MutableRefObject<PageContext | null> {+ return useInternalPageContext().ref;+}++/**+ * Register a page context. The current page calls this in an effect; the+ * provider keeps the latest value. Cleanup clears it when the page+ * unmounts so a stale context doesn't leak between routes.+ *+ * The context is JSON-serialized for the dependency list to avoid+ * referential-equality re-renders on identical-but-new objects.+ */+export function usePageContext(context: PageContext): void {+ const { setContext } = useInternalPageContext();+ const serialized = JSON.stringify(context);++ // biome-ignore lint/correctness/useExhaustiveDependencies: serialized is the stable dep+ useEffect(() => {+ setContext(context);+ return () => setContext(null);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [serialized]);+}diff --git a/apps/start/src/hooks/use-page-context-helpers.ts b/apps/start/src/hooks/use-page-context-helpers.tsnew file mode 100644index 000000000..926a90459--- /dev/null+++ b/apps/start/src/hooks/use-page-context-helpers.ts@@ -0,0 +1,81 @@+import { useOverviewOptions } from '@/components/overview/useOverviewOptions';+import {+ type PageContext,+ type PageContextPage,+ usePageContext,+} from '@/contexts/page-context';+import {+ useEventQueryFilters,+ useEventQueryNamesFilter,+} from './use-event-query-filters';+import { useAppParams } from './use-app-params';+import type { IReportInput } from '@openpanel/validation';++/**+ * For pages that share the standard date-range / interval filters+ * (Overview, Insights, Pages, SEO, Events, etc.). Reads the current+ * range + interval from `useOverviewOptions` and registers the page+ * context.+ */+export function useRangePageContext(page: PageContextPage) {+ const { projectId, organizationId } = useAppParams();+ const { range, startDate, endDate, interval } = useOverviewOptions();+ const [eventNames] = useEventQueryNamesFilter();+ const [eventFilters] = useEventQueryFilters();++ usePageContext({+ page,+ route: { projectId, organizationId },+ filters: {+ range,+ startDate: startDate ?? undefined,+ endDate: endDate ?? undefined,+ interval: interval ?? undefined,+ // Send the active event-name + property filters so the chat+ // assistant can reason about the current view (e.g. "you're+ // already filtering to mobile") and produce diff-style+ // updates via the apply_filters tool.+ ...(eventNames.length > 0 ? { eventNames } : {}),+ ...(eventFilters.length > 0 ? { eventFilters } : {}),+ },+ });+}++/**+ * For entity-detail pages (session detail, profile detail, group detail).+ * Takes the primary IDs + an optional primer object (small structured+ * snapshot of what's visible — country, device, duration, etc.) so the+ * model can answer trivial follow-ups without a tool call.+ */+export function useEntityPageContext(+ page: 'sessionDetail' | 'profileDetail' | 'groupDetail',+ ids: PageContext['ids'],+ primer?: Record<string, unknown>,+) {+ const { projectId, organizationId } = useAppParams();++ usePageContext({+ page,+ route: { projectId, organizationId },+ ids,+ primer,+ });+}++/**+ * For the Report Editor page. Sends the full live report draft so the+ * model can propose concrete edits via `preview_report_with_changes`.+ */+export function useReportEditorContext(reportDraft: IReportInput | null) {+ const { projectId, organizationId } = useAppParams();++ // The draft can be null while the report loads — the cleanup handler+ // in usePageContext clears it on unmount, so passing null on every+ // render before the data arrives is safe (we just register a context+ // without a draft until the first render with a real draft).+ usePageContext({+ page: 'reportEditor',+ route: { projectId, organizationId },+ ...(reportDraft ? { reportDraft } : {}),+ });+}diff --git a/apps/start/src/hooks/use-resizable-drawer.ts b/apps/start/src/hooks/use-resizable-drawer.tsnew file mode 100644index 000000000..3717622d3--- /dev/null+++ b/apps/start/src/hooks/use-resizable-drawer.ts@@ -0,0 +1,104 @@+import { useCallback, useEffect, useRef, useState } from 'react';++type Options = {+ /** Default width if nothing is stored. */+ defaultWidth: number;+ minWidth: number;+ maxWidth: number;+ /** localStorage key for width persistence. */+ storageKey: string;+ /** Which edge has the handle. Default 'left' (right-anchored drawer). */+ edge?: 'left' | 'right';+};++type Result = {+ width: number;+ /** Spread on the resize handle div. */+ dragHandleProps: {+ onMouseDown: (e: React.MouseEvent) => void;+ role: 'separator';+ 'aria-orientation': 'vertical';+ };+};++/**+ * Drag-to-resize state for a side drawer. Owns width state, handles the+ * mousemove/mouseup listeners, and persists the result to localStorage+ * 300ms after the user stops dragging.+ *+ * Replaces ~30 lines of inline `useRef` + `addEventListener` + manual+ * cursor/userSelect tweaks in the consumer.+ */+export function useResizableDrawer({+ defaultWidth,+ minWidth,+ maxWidth,+ storageKey,+ edge = 'left',+}: Options): Result {+ const [width, setWidth] = useState(defaultWidth);++ // Hydrate from localStorage on mount (avoids SSR mismatch).+ useEffect(() => {+ if (typeof window === 'undefined') return;+ const raw = window.localStorage.getItem(storageKey);+ if (!raw) return;+ const n = Number(raw);+ if (Number.isNaN(n)) return;+ setWidth(Math.min(maxWidth, Math.max(minWidth, n)));+ }, [storageKey, minWidth, maxWidth]);++ // Persist on idle (debounced).+ useEffect(() => {+ if (typeof window === 'undefined') return;+ const t = window.setTimeout(() => {+ window.localStorage.setItem(storageKey, String(width));+ }, 300);+ return () => window.clearTimeout(t);+ }, [width, storageKey]);++ const dragRef = useRef<{ startX: number; startWidth: number } | null>(null);++ const onMouseDown = useCallback(+ (e: React.MouseEvent) => {+ e.preventDefault();+ dragRef.current = { startX: e.clientX, startWidth: width };++ const onMove = (ev: MouseEvent) => {+ if (!dragRef.current) return;+ const dx =+ edge === 'left'+ ? dragRef.current.startX - ev.clientX+ : ev.clientX - dragRef.current.startX;+ const next = Math.min(+ maxWidth,+ Math.max(minWidth, dragRef.current.startWidth + dx),+ );+ setWidth(next);+ };++ const onUp = () => {+ dragRef.current = null;+ document.body.style.cursor = '';+ document.body.style.userSelect = '';+ window.removeEventListener('mousemove', onMove);+ window.removeEventListener('mouseup', onUp);+ };++ document.body.style.cursor = 'ew-resize';+ document.body.style.userSelect = 'none';+ window.addEventListener('mousemove', onMove);+ window.addEventListener('mouseup', onUp);+ },+ [width, minWidth, maxWidth, edge],+ );++ return {+ width,+ dragHandleProps: {+ onMouseDown,+ role: 'separator',+ 'aria-orientation': 'vertical',+ },+ };+}diff --git a/apps/start/src/modals/event-details.tsx b/apps/start/src/modals/event-details.tsxindex dc344fc0f..5b0833096 100644--- a/apps/start/src/modals/event-details.tsx+++ b/apps/start/src/modals/event-details.tsx@@ -23,6 +23,7 @@ import { fancyMinutes } from '@/hooks/use-numer-formatter';import { useTRPC } from '@/integrations/trpc/react';import { cn } from '@/utils/cn';import { getProfileName } from '@/utils/getters';+import Syntax from '@/components/syntax';interface Props {id: string;@@ -77,6 +78,7 @@ function EventDetailsContent({ id, createdAt, projectId }: Props) {},};const [widget, setWidget] = useState(TABS.essentials);+ const [propertiesMode, setPropertiesMode] = useState<'table' | 'json'>('table');const trpc = useTRPC();const query = useSuspenseQuery(trpc.event.details.queryOptions({@@ -271,7 +273,17 @@ function EventDetailsContent({ id, createdAt, projectId }: Props) {<section><div className="mb-2 flex justify-between font-medium"><div>Properties</div>+ <button+ type="button"+ onClick={() =>+ setPropertiesMode((p) => (p === 'table' ? 'json' : 'table'))+ }+ className="text-muted-foreground hover:text-foreground transition-colors"+ >+ {propertiesMode === 'table' ? 'View JSON' : 'View Table'}+ </button></div>+ {propertiesMode === 'table' && (<KeyValueGridcolumns={1}data={properties}@@ -286,6 +298,10 @@ function EventDetailsContent({ id, createdAt, projectId }: Props) {</div>)}/>+ )}+ {propertiesMode === 'json' && (+ <Syntax code={JSON.stringify(properties, null, 2)} language="json" />+ )}</section>)}<section>diff --git a/apps/start/src/routeTree.gen.ts b/apps/start/src/routeTree.gen.tsindex c24e8b729..f706c68f4 100644--- a/apps/start/src/routeTree.gen.ts+++ b/apps/start/src/routeTree.gen.ts@@ -50,7 +50,6 @@ import { Route as AppOrganizationIdProjectIdPagesRouteImport } from './routes/_aimport { Route as AppOrganizationIdProjectIdInsightsRouteImport } from './routes/_app.$organizationId.$projectId.insights'import { Route as AppOrganizationIdProjectIdGroupsRouteImport } from './routes/_app.$organizationId.$projectId.groups'import { Route as AppOrganizationIdProjectIdDashboardsRouteImport } from './routes/_app.$organizationId.$projectId.dashboards'-import { Route as AppOrganizationIdProjectIdChatRouteImport } from './routes/_app.$organizationId.$projectId.chat'import { Route as AppOrganizationIdProfileTabsIndexRouteImport } from './routes/_app.$organizationId.profile._tabs.index'import { Route as AppOrganizationIdMembersTabsIndexRouteImport } from './routes/_app.$organizationId.members._tabs.index'import { Route as AppOrganizationIdIntegrationsTabsIndexRouteImport } from './routes/_app.$organizationId.integrations._tabs.index'@@ -371,12 +370,6 @@ const AppOrganizationIdProjectIdDashboardsRoute =path: '/dashboards',getParentRoute: () => AppOrganizationIdProjectIdRoute,} as any)-const AppOrganizationIdProjectIdChatRoute =- AppOrganizationIdProjectIdChatRouteImport.update({- id: '/chat',- path: '/chat',- getParentRoute: () => AppOrganizationIdProjectIdRoute,- } as any)const AppOrganizationIdProjectIdProfilesProfileIdRoute =AppOrganizationIdProjectIdProfilesProfileIdRouteImport.update({id: '/$profileId',@@ -663,7 +656,6 @@ export interface FileRoutesByFullPath {'/share/overview/$shareId': typeof ShareOverviewShareIdRoute'/share/report/$shareId': typeof ShareReportShareIdRoute'/$organizationId/': typeof AppOrganizationIdIndexRoute- '/$organizationId/$projectId/chat': typeof AppOrganizationIdProjectIdChatRoute'/$organizationId/$projectId/dashboards': typeof AppOrganizationIdProjectIdDashboardsRoute'/$organizationId/$projectId/groups': typeof AppOrganizationIdProjectIdGroupsRoute'/$organizationId/$projectId/insights': typeof AppOrganizationIdProjectIdInsightsRoute@@ -742,7 +734,6 @@ export interface FileRoutesByTo {'/share/overview/$shareId': typeof ShareOverviewShareIdRoute'/share/report/$shareId': typeof ShareReportShareIdRoute'/$organizationId': typeof AppOrganizationIdIndexRoute- '/$organizationId/$projectId/chat': typeof AppOrganizationIdProjectIdChatRoute'/$organizationId/$projectId/dashboards': typeof AppOrganizationIdProjectIdDashboardsRoute'/$organizationId/$projectId/groups': typeof AppOrganizationIdProjectIdGroupsRoute'/$organizationId/$projectId/insights': typeof AppOrganizationIdProjectIdInsightsRoute@@ -819,7 +810,6 @@ export interface FileRoutesById {'/share/overview/$shareId': typeof ShareOverviewShareIdRoute'/share/report/$shareId': typeof ShareReportShareIdRoute'/_app/$organizationId/': typeof AppOrganizationIdIndexRoute- '/_app/$organizationId/$projectId/chat': typeof AppOrganizationIdProjectIdChatRoute'/_app/$organizationId/$projectId/dashboards': typeof AppOrganizationIdProjectIdDashboardsRoute'/_app/$organizationId/$projectId/groups': typeof AppOrganizationIdProjectIdGroupsRoute'/_app/$organizationId/$projectId/insights': typeof AppOrganizationIdProjectIdInsightsRoute@@ -911,7 +901,6 @@ export interface FileRouteTypes {| '/share/overview/$shareId'| '/share/report/$shareId'| '/$organizationId/'- | '/$organizationId/$projectId/chat'| '/$organizationId/$projectId/dashboards'| '/$organizationId/$projectId/groups'| '/$organizationId/$projectId/insights'@@ -990,7 +979,6 @@ export interface FileRouteTypes {| '/share/overview/$shareId'| '/share/report/$shareId'| '/$organizationId'- | '/$organizationId/$projectId/chat'| '/$organizationId/$projectId/dashboards'| '/$organizationId/$projectId/groups'| '/$organizationId/$projectId/insights'@@ -1066,7 +1054,6 @@ export interface FileRouteTypes {| '/share/overview/$shareId'| '/share/report/$shareId'| '/_app/$organizationId/'- | '/_app/$organizationId/$projectId/chat'| '/_app/$organizationId/$projectId/dashboards'| '/_app/$organizationId/$projectId/groups'| '/_app/$organizationId/$projectId/insights'@@ -1478,13 +1465,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof AppOrganizationIdProjectIdDashboardsRouteImportparentRoute: typeof AppOrganizationIdProjectIdRoute}- '/_app/$organizationId/$projectId/chat': {- id: '/_app/$organizationId/$projectId/chat'- path: '/chat'- fullPath: '/$organizationId/$projectId/chat'- preLoaderRoute: typeof AppOrganizationIdProjectIdChatRouteImport- parentRoute: typeof AppOrganizationIdProjectIdRoute- }'/_app/$organizationId/$projectId/profiles/$profileId': {id: '/_app/$organizationId/$projectId/profiles/$profileId'path: '/$profileId'@@ -2047,7 +2027,6 @@ const AppOrganizationIdProjectIdGroupsGroupIdRouteWithChildren =)interface AppOrganizationIdProjectIdRouteChildren {- AppOrganizationIdProjectIdChatRoute: typeof AppOrganizationIdProjectIdChatRouteAppOrganizationIdProjectIdDashboardsRoute: typeof AppOrganizationIdProjectIdDashboardsRouteAppOrganizationIdProjectIdGroupsRoute: typeof AppOrganizationIdProjectIdGroupsRouteAppOrganizationIdProjectIdInsightsRoute: typeof AppOrganizationIdProjectIdInsightsRoute@@ -2070,7 +2049,6 @@ interface AppOrganizationIdProjectIdRouteChildren {const AppOrganizationIdProjectIdRouteChildren: AppOrganizationIdProjectIdRouteChildren ={- AppOrganizationIdProjectIdChatRoute: AppOrganizationIdProjectIdChatRoute,AppOrganizationIdProjectIdDashboardsRoute:AppOrganizationIdProjectIdDashboardsRoute,AppOrganizationIdProjectIdGroupsRoute:diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.chat.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.chat.tsxdeleted file mode 100644index b63e2cbe9..000000000--- a/apps/start/src/routes/_app.$organizationId.$projectId.chat.tsx+++ /dev/null@@ -1,54 +0,0 @@-import Chat from '@/components/chat/chat';-import FullPageLoadingState from '@/components/full-page-loading-state';-import { useTRPC } from '@/integrations/trpc/react';-import { PAGE_TITLES, createProjectTitle } from '@/utils/title';-import { keepPreviousData, useSuspenseQuery } from '@tanstack/react-query';-import { createFileRoute } from '@tanstack/react-router';-import type { UIMessage } from 'ai';--export const Route = createFileRoute('/_app/$organizationId/$projectId/chat')({- component: Component,- pendingComponent: FullPageLoadingState,- head: () => {- return {- meta: [- {- title: createProjectTitle(PAGE_TITLES.CHAT),- },- ],- };- },-});--function Component() {- const { organizationId, projectId } = Route.useParams();- const trpc = useTRPC();- const { data } = useSuspenseQuery(- trpc.chat.get.queryOptions(- {- projectId,- },- {- placeholderData: keepPreviousData,- },- ),- );-- const { data: organization } = useSuspenseQuery(- trpc.organization.get.queryOptions({- organizationId,- }),- );-- const messages = ((data?.messages as unknown as UIMessage[]) || []).slice(- -10,- );-- return (- <Chat- projectId={projectId}- initialMessages={messages}- organization={organization}- />- );-}diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.events._tabs.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.events._tabs.tsxindex 206e4cbd2..9069ea50c 100644--- a/apps/start/src/routes/_app.$organizationId.$projectId.events._tabs.tsx+++ b/apps/start/src/routes/_app.$organizationId.$projectId.events._tabs.tsx@@ -1,6 +1,7 @@import { PageHeader } from '@/components/page-header';import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';import { usePageTabs } from '@/hooks/use-page-tabs';+import { useRangePageContext } from '@/hooks/use-page-context-helpers';import { PAGE_TITLES, createProjectTitle } from '@/utils/title';import { Outlet, createFileRoute, useRouter } from '@tanstack/react-router';@@ -21,6 +22,7 @@ export const Route = createFileRoute(function Component() {const router = useRouter();+ useRangePageContext('events');const { activeTab, tabs } = usePageTabs([{ id: 'events', label: 'Events' },diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.groups_.$groupId._tabs.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.groups_.$groupId._tabs.tsxindex 3ba26ac44..6036097b5 100644--- a/apps/start/src/routes/_app.$organizationId.$projectId.groups_.$groupId._tabs.tsx+++ b/apps/start/src/routes/_app.$organizationId.$projectId.groups_.$groupId._tabs.tsx@@ -15,6 +15,7 @@ import { PageContainer } from '@/components/page-container';import { PageHeader } from '@/components/page-header';import { Button } from '@/components/ui/button';import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';+import { useEntityPageContext } from '@/hooks/use-page-context-helpers';import { usePageTabs } from '@/hooks/use-page-tabs';import { handleError, useTRPC } from '@/integrations/trpc/react';import { pushModal, showConfirm } from '@/modals';@@ -57,6 +58,17 @@ function Component() {trpc.group.byId.queryOptions({ id: groupId, projectId }));+ useEntityPageContext(+ 'groupDetail',+ { groupId },+ group.data+ ? {+ name: group.data.name,+ type: group.data.type,+ }+ : undefined,+ );+const deleteMutation = useMutation(trpc.group.delete.mutationOptions({onSuccess() {diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.index.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.index.tsxindex 834ce162a..7fe6ac7bb 100644--- a/apps/start/src/routes/_app.$organizationId.$projectId.index.tsx+++ b/apps/start/src/routes/_app.$organizationId.$projectId.index.tsx@@ -1,5 +1,6 @@import { createFileRoute } from '@tanstack/react-router';import { LazyComponent } from '@/components/lazy-component';+import { useRangePageContext } from '@/hooks/use-page-context-helpers';import {OverviewFilterButton,OverviewFiltersButtons,@@ -34,6 +35,7 @@ export const Route = createFileRoute('/_app/$organizationId/$projectId/')({function ProjectDashboard() {const { projectId } = Route.useParams();+ useRangePageContext('overview');return (<div><div className="sticky-header -top-px!">diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.insights.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.insights.tsxindex 2ccd0ab8b..a366dfb81 100644--- a/apps/start/src/routes/_app.$organizationId.$projectId.insights.tsx+++ b/apps/start/src/routes/_app.$organizationId.$projectId.insights.tsx@@ -1,4 +1,5 @@import { FullPageEmptyState } from '@/components/full-page-empty-state';+import { useRangePageContext } from '@/hooks/use-page-context-helpers';import { InsightCard } from '@/components/insights/insight-card';import { PageContainer } from '@/components/page-container';import { PageHeader } from '@/components/page-header';@@ -64,6 +65,7 @@ function getModuleDisplayName(moduleKey: string): string {function Component() {const { projectId } = Route.useParams();+ useRangePageContext('insights');const trpc = useTRPC();const { data: insights, isLoading } = useQuery(trpc.insight.listAll.queryOptions({diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.pages.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.pages.tsxindex 0672797eb..984aeb2bc 100644--- a/apps/start/src/routes/_app.$organizationId.$projectId.pages.tsx+++ b/apps/start/src/routes/_app.$organizationId.$projectId.pages.tsx@@ -1,6 +1,7 @@import { PagesTable } from '@/components/pages/table';import { PageContainer } from '@/components/page-container';import { PageHeader } from '@/components/page-header';+import { useRangePageContext } from '@/hooks/use-page-context-helpers';import { PAGE_TITLES, createProjectTitle } from '@/utils/title';import { createFileRoute } from '@tanstack/react-router';@@ -13,6 +14,7 @@ export const Route = createFileRoute('/_app/$organizationId/$projectId/pages')({function Component() {const { projectId } = Route.useParams();+ useRangePageContext('pages');return (<PageContainer><PageHeader title="Pages" description="Access all your pages here" className="mb-8" />diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.profiles.$profileId._tabs.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.profiles.$profileId._tabs.tsxindex 315c80c38..26bf91daf 100644--- a/apps/start/src/routes/_app.$organizationId.$projectId.profiles.$profileId._tabs.tsx+++ b/apps/start/src/routes/_app.$organizationId.$projectId.profiles.$profileId._tabs.tsx@@ -4,6 +4,7 @@ import { PageHeader } from '@/components/page-header';import { ProfileAvatar } from '@/components/profiles/profile-avatar';import { SerieIcon } from '@/components/report-chart/common/serie-icon';import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';+import { useEntityPageContext } from '@/hooks/use-page-context-helpers';import { usePageTabs } from '@/hooks/use-page-tabs';import { useTRPC } from '@/integrations/trpc/react';import { getProfileName } from '@/utils/getters';@@ -37,6 +38,18 @@ function Component() {}),);+ useEntityPageContext(+ 'profileDetail',+ { profileId },+ {+ country: profile.data?.properties.country,+ device: profile.data?.properties.device,+ browser: profile.data?.properties.browser,+ os: profile.data?.properties.os,+ email: profile.data?.email,+ },+ );+const { activeTab, tabs } = usePageTabs([{id: '/$organizationId/$projectId/profiles/$profileId',diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.reports_.$reportId.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.reports_.$reportId.tsxindex c60c92fb8..65c9388c3 100644--- a/apps/start/src/routes/_app.$organizationId.$projectId.reports_.$reportId.tsx+++ b/apps/start/src/routes/_app.$organizationId.$projectId.reports_.$reportId.tsx@@ -1,5 +1,6 @@import FullPageLoadingState from '@/components/full-page-loading-state';import ReportEditor from '@/components/report-chart/report-editor';+import { useReportEditorContext } from '@/hooks/use-page-context-helpers';import { useTRPC } from '@/integrations/trpc/react';import { createProjectTitle } from '@/utils/title';import { useSuspenseQuery } from '@tanstack/react-query';@@ -36,6 +37,6 @@ function Component() {const { reportId } = Route.useParams();const trpc = useTRPC();const query = useSuspenseQuery(trpc.report.get.queryOptions({ reportId }));- console.log(query.data);+ useReportEditorContext(query.data ?? null);return <ReportEditor report={query.data} />;}diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.seo.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.seo.tsxindex 6b8c10f47..73e52e4dc 100644--- a/apps/start/src/routes/_app.$organizationId.$projectId.seo.tsx+++ b/apps/start/src/routes/_app.$organizationId.$projectId.seo.tsx@@ -37,6 +37,7 @@ import { Skeleton } from '@/components/skeleton';import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';import { useAppParams } from '@/hooks/use-app-params';+import { useRangePageContext } from '@/hooks/use-page-context-helpers';import { useTRPC } from '@/integrations/trpc/react';import { pushModal } from '@/modals';import { getChartColor } from '@/utils/theme';@@ -86,6 +87,7 @@ const { TooltipProvider, Tooltip: GscTooltip } = createChartTooltip<function SeoPage() {const { projectId, organizationId } = useAppParams();+ useRangePageContext('seo');const trpc = useTRPC();const navigate = useNavigate();const { range, startDate, endDate, interval } = useOverviewOptions();diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.sessions_.$sessionId.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.sessions_.$sessionId.tsxindex ae1b6dad5..03f880b30 100644--- a/apps/start/src/routes/_app.$organizationId.$projectId.sessions_.$sessionId.tsx+++ b/apps/start/src/routes/_app.$organizationId.$projectId.sessions_.$sessionId.tsx@@ -16,6 +16,7 @@ import {WidgetTitle,} from '@/components/widget';import { useNumber } from '@/hooks/use-numer-formatter';+import { useEntityPageContext } from '@/hooks/use-page-context-helpers';import { useTRPC } from '@/integrations/trpc/react';import { formatDateTime } from '@/utils/date';import { getProfileName } from '@/utils/getters';@@ -144,6 +145,21 @@ function Component() {trpc.session.byId.queryOptions({ sessionId, projectId }));+ useEntityPageContext(+ 'sessionDetail',+ { sessionId },+ {+ duration: session.duration,+ eventCount: session.eventCount,+ screenViewCount: session.screenViewCount,+ country: session.country,+ device: session.device,+ isBounce: session.isBounce,+ entryPath: session.entryPath,+ exitPath: session.exitPath,+ },+ );+const { data: eventsData } = useSuspenseQuery(trpc.event.events.queryOptions({projectId,diff --git a/apps/start/src/routes/_app.tsx b/apps/start/src/routes/_app.tsxindex 678f1cea5..5383b2e7d 100644--- a/apps/start/src/routes/_app.tsx+++ b/apps/start/src/routes/_app.tsx@@ -1,5 +1,6 @@import { createFileRoute, Outlet, redirect } from '@tanstack/react-router';import { ConstructionIcon } from 'lucide-react';+import { ChatDrawerSlot } from '@/components/chat/chat-drawer-slot';import { FullPageEmptyState } from '@/components/full-page-empty-state';import { Sidebar } from '@/components/sidebar';import { buttonVariants } from '@/components/ui/button';@@ -41,11 +42,12 @@ function AppLayout() {return (<div className="flex h-screen w-full"><Sidebar />- <div className="w-full lg:pl-72">+ <div className="w-full lg:pl-72 min-w-0 flex-1"><div className="fixed top-0 z-10 block h-16 w-full border-b bg-background lg:hidden" /><div className="block h-16 lg:hidden" /><Outlet /></div>+ <ChatDrawerSlot /></div>);}diff --git a/apps/start/src/styles.css b/apps/start/src/styles.cssindex 73a93e09f..85a64b470 100644--- a/apps/start/src/styles.css+++ b/apps/start/src/styles.css@@ -307,6 +307,35 @@ button {scrollbar-width: none; /* Firefox */}+/*+ * Shimmer text — used in the chat to signal that an AI step is in+ * flight (tool call running, model thinking). The gradient sweeps+ * left-to-right; `background-clip: text` makes the moving gradient+ * visible only inside the text glyphs.+ */+@keyframes op-shimmer {+ 0% {+ background-position: 200% 0;+ }+ 100% {+ background-position: -200% 0;+ }+}+.op-shimmer {+ background-image: linear-gradient(+ 90deg,+ var(--color-muted-foreground) 0%,+ var(--color-foreground) 50%,+ var(--color-muted-foreground) 100%+ );+ background-size: 200% 100%;+ background-clip: text;+ -webkit-background-clip: text;+ color: transparent;+ -webkit-text-fill-color: transparent;+ animation: op-shimmer 2.2s linear infinite;+}+/* Custom slow pulse animation */@keyframes slow-pulse {0%, 100% {diff --git a/packages/constants/index.ts b/packages/constants/index.tsindex 5d4760bab..48c47618a 100644--- a/packages/constants/index.ts+++ b/packages/constants/index.ts@@ -1,4 +1,4 @@-import { differenceInDays, isSameDay, isSameMonth } from 'date-fns';+import { differenceInDays, isSameDay } from 'date-fns';export const DEFAULT_ASPECT_RATIO = 0.5625;export const NOT_SET_VALUE = '(not set)';@@ -227,6 +227,9 @@ export function getDefaultIntervalByRange() {return 'day';}+ if (range === '6m') {+ return 'week';+ }return 'month';}@@ -238,11 +241,12 @@ export function getDefaultIntervalByDates(if (isSameDay(startDate, endDate)) {return 'hour';}- if (isSameMonth(startDate, endDate)) {+ const days = differenceInDays(endDate, startDate);+ if (days <= 92) {return 'day';}- if (differenceInDays(endDate, startDate) <= 31) {- return 'day';+ if (days <= 186) {+ return 'week';}return 'month';}diff --git a/packages/db/index.ts b/packages/db/index.tsindex 571233fce..c2e6752c5 100644--- a/packages/db/index.ts+++ b/packages/db/index.ts@@ -9,6 +9,7 @@ export * from './src/prisma-client';export * from './src/services/access.service';export * from './src/services/chart.service';export * from './src/services/clients.service';+export * from './src/services/conversation.service';export * from './src/services/conversion.service';export * from './src/services/dashboard.service';export * from './src/services/date.service';diff --git a/packages/db/prisma/migrations/20260410120000_chat_conversations/migration.sql b/packages/db/prisma/migrations/20260410120000_chat_conversations/migration.sqlnew file mode 100644index 000000000..3350962d1--- /dev/null+++ b/packages/db/prisma/migrations/20260410120000_chat_conversations/migration.sql@@ -0,0 +1,50 @@+-- DropForeignKey+ALTER TABLE "public"."chats" DROP CONSTRAINT IF EXISTS "chats_projectId_fkey";++-- DropTable+DROP TABLE IF EXISTS "public"."chats";++-- CreateTable+CREATE TABLE "public"."conversations" (+ "id" TEXT NOT NULL DEFAULT gen_random_uuid(),+ "projectId" TEXT NOT NULL,+ "organizationId" TEXT NOT NULL,+ "userId" TEXT NOT NULL,+ "title" TEXT,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,++ CONSTRAINT "conversations_pkey" PRIMARY KEY ("id")+);++-- CreateTable+CREATE TABLE "public"."chat_messages" (+ "id" TEXT NOT NULL DEFAULT gen_random_uuid(),+ "conversationId" TEXT NOT NULL,+ "role" TEXT NOT NULL,+ "parts" JSONB NOT NULL,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,++ CONSTRAINT "chat_messages_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE INDEX "conversations_projectId_updatedAt_idx" ON "public"."conversations"("projectId", "updatedAt");++-- CreateIndex+CREATE INDEX "conversations_userId_updatedAt_idx" ON "public"."conversations"("userId", "updatedAt");++-- CreateIndex+CREATE INDEX "chat_messages_conversationId_createdAt_idx" ON "public"."chat_messages"("conversationId", "createdAt");++-- AddForeignKey+ALTER TABLE "public"."conversations" ADD CONSTRAINT "conversations_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES "public"."projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "public"."conversations" ADD CONSTRAINT "conversations_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "public"."organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "public"."conversations" ADD CONSTRAINT "conversations_userId_fkey" FOREIGN KEY ("userId") REFERENCES "public"."users"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "public"."chat_messages" ADD CONSTRAINT "chat_messages_conversationId_fkey" FOREIGN KEY ("conversationId") REFERENCES "public"."conversations"("id") ON DELETE CASCADE ON UPDATE CASCADE;diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prismaindex 1af69d321..b428052f9 100644--- a/packages/db/prisma/schema.prisma+++ b/packages/db/prisma/schema.prisma@@ -34,15 +34,35 @@ enum ProjectType {backend}-model Chat {- id String @id @default(dbgenerated("gen_random_uuid()"))- messages Json- projectId String- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)- createdAt DateTime @default(now())- updatedAt DateTime @default(now()) @updatedAt+model Conversation {+ id String @id @default(dbgenerated("gen_random_uuid()"))+ projectId String+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)+ organizationId String+ organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)+ userId String+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)+ title String?+ createdAt DateTime @default(now())+ updatedAt DateTime @default(now()) @updatedAt+ messages ChatMessage[]- @@map("chats")+ @@index([projectId, updatedAt])+ @@index([userId, updatedAt])+ @@map("conversations")+}++model ChatMessage {+ id String @id @default(dbgenerated("gen_random_uuid()"))+ conversationId String+ conversation Conversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)+ role String+ /// [IPrismaUIMessageParts]+ parts Json+ createdAt DateTime @default(now())++ @@index([conversationId, createdAt])+ @@map("chat_messages")}model Organization {@@ -61,6 +81,7 @@ model Organization {ShareWidget ShareWidget[]integrations Integration[]invites Invite[]+ conversations Conversation[]timezone String?onboarding String? @default("completed")@@ -106,6 +127,7 @@ model User {sessions Session[]accounts Account[]invites Invite[]+ conversations Conversation[]@@map("users")}@@ -207,9 +229,9 @@ model Project {// When deleteAt > now(), the project will be deleteddeleteAt DateTime?- createdAt DateTime @default(now())- updatedAt DateTime @default(now()) @updatedAt- Chat Chat[]+ createdAt DateTime @default(now())+ updatedAt DateTime @default(now()) @updatedAt+ conversations Conversation[]@@map("projects")}diff --git a/packages/db/src/services/conversation.service.ts b/packages/db/src/services/conversation.service.tsnew file mode 100644index 000000000..8beff4ada--- /dev/null+++ b/packages/db/src/services/conversation.service.ts@@ -0,0 +1,70 @@+import type { ChatMessage, Conversation, Prisma } from '../prisma-client';+import { db } from '../prisma-client';++export type IServiceConversation = Conversation;+export type IServiceChatMessage = ChatMessage;+export type IServiceConversationWithMessages = Prisma.ConversationGetPayload<{+ include: { messages: true };+}>;++export async function getConversationById(+ id: string,+ options: { withMessages?: boolean } = {},+): Promise<IServiceConversation | IServiceConversationWithMessages | null> {+ if (options.withMessages) {+ return db.conversation.findUnique({+ where: { id },+ include: {+ messages: { orderBy: { createdAt: 'asc' } },+ },+ });+ }+ return db.conversation.findUnique({ where: { id } });+}++export async function listConversations(input: {+ projectId: string;+ userId: string;+ limit?: number;+}): Promise<IServiceConversation[]> {+ return db.conversation.findMany({+ where: {+ projectId: input.projectId,+ userId: input.userId,+ },+ orderBy: { updatedAt: 'desc' },+ take: input.limit ?? 50,+ });+}++/**+ * Set the title on a conversation, creating the row if it doesn't+ * exist yet. Used by the chat titler: on the first turn we stream a+ * title in parallel with the agent run, and the titler may finish+ * before the agent's `ConversationStore.save()` has inserted the row.+ * This upsert makes that race harmless — the row ends up with the+ * right owner + title regardless of which side finishes first.+ */+export async function upsertConversationTitle(input: {+ id: string;+ title: string;+ projectId: string;+ organizationId: string;+ userId: string;+}): Promise<IServiceConversation> {+ return db.conversation.upsert({+ where: { id: input.id },+ create: {+ id: input.id,+ title: input.title,+ projectId: input.projectId,+ organizationId: input.organizationId,+ userId: input.userId,+ },+ update: { title: input.title },+ });+}++export async function deleteConversation(id: string): Promise<void> {+ await db.conversation.delete({ where: { id } });+}diff --git a/packages/db/src/services/date.service.ts b/packages/db/src/services/date.service.tsindex d10a8580b..7bb5433aa 100644--- a/packages/db/src/services/date.service.ts+++ b/packages/db/src/services/date.service.ts@@ -199,6 +199,17 @@ export function getDatesFromRange(range: IChartRange, timezone: string) {};}+const DATE_ONLY_REGEX = /^\d{4}-\d{2}-\d{2}$/;++function normalizeBoundary(value: string, boundary: 'start' | 'end'): string {+ if (DATE_ONLY_REGEX.test(value)) {+ return boundary === 'start'+ ? `${value} 00:00:00`+ : `${value} 23:59:59`;+ }+ return value;+}+export function getChartStartEndDate({startDate,@@ -207,13 +218,18 @@ export function getChartStartEndDate(}: Pick<IReportInput, 'endDate' | 'startDate' | 'range'>,timezone: string) {- if (startDate && endDate) {- return { startDate, endDate };+ const normalizedStart = startDate+ ? normalizeBoundary(startDate, 'start')+ : startDate;+ const normalizedEnd = endDate ? normalizeBoundary(endDate, 'end') : endDate;++ if (normalizedStart && normalizedEnd) {+ return { startDate: normalizedStart, endDate: normalizedEnd };}const ranges = getDatesFromRange(range, timezone);- if (!startDate && endDate) {- return { startDate: ranges.startDate, endDate };+ if (!normalizedStart && normalizedEnd) {+ return { startDate: ranges.startDate, endDate: normalizedEnd };}return ranges;diff --git a/packages/db/src/services/event.service.ts b/packages/db/src/services/event.service.tsindex e57ac9b59..50c29f831 100644--- a/packages/db/src/services/event.service.ts+++ b/packages/db/src/services/event.service.ts@@ -1218,7 +1218,9 @@ export interface QueryEventsInput {referrer?: string;referrerName?: string;referrerType?: string;+ sessionId?: string;profileId?: string;+ profileIds?: string[];properties?: Record<string, string>;limit?: number;}@@ -1231,10 +1233,18 @@ export async function queryEventsCore(.from(TABLE_NAMES.events).where('project_id', '=', input.projectId);+ if (input.sessionId) {+ builder.where('session_id', '=', input.sessionId);+ }+if (input.profileId) {builder.where('profile_id', '=', input.profileId);}+ if (input.profileIds?.length) {+ builder.where('profile_id', 'IN', input.profileIds);+ }+if (input.eventNames?.length) {builder.where('name', 'IN', input.eventNames);}@@ -1281,12 +1291,29 @@ export async function queryEventsCore(}}- const { startDate: start, endDate: end } = resolveDateRange(input.startDate, input.endDate);-- builder.where('created_at', 'BETWEEN', [- clix.datetime(start),- clix.datetime(end),- ]);+ // Skip the default 30-day date filter when sessionId is set — a+ // session id is unique and narrow enough to query directly. Without+ // this, an older session's events would be silently excluded.+ if (!input.sessionId) {+ const { startDate: start, endDate: end } = resolveDateRange(+ input.startDate,+ input.endDate,+ );+ builder.where('created_at', 'BETWEEN', [+ clix.datetime(start),+ clix.datetime(end),+ ]);+ } else if (input.startDate || input.endDate) {+ // If caller still wants to scope by date, honor it.+ const { startDate: start, endDate: end } = resolveDateRange(+ input.startDate,+ input.endDate,+ );+ builder.where('created_at', 'BETWEEN', [+ clix.datetime(start),+ clix.datetime(end),+ ]);+ }return builder.limit(input.limit ?? 20).execute();}diff --git a/packages/db/src/services/overview.service.ts b/packages/db/src/services/overview.service.tsindex 1254c56f3..527ded9a6 100644--- a/packages/db/src/services/overview.service.ts+++ b/packages/db/src/services/overview.service.ts@@ -31,6 +31,24 @@ const COLUMN_PREFIX_MAP: Record<string, string> = {os_version: 'os',};+const WHITELISTED_FILTERS = [+ 'os',+ 'path',+ 'city',+ 'brand',+ 'model',+ 'origin',+ 'region',+ 'device',+ 'revenue',+ 'country',+ 'browser',+ 'referrer',+ 'os_version',+ 'referrer_name',+ 'browser_version',+];+// Typestype MetricsRow = {bounce_rate: number;@@ -592,6 +610,9 @@ export class OverviewService {getRawWhereClause(type: 'events' | 'sessions', filters: IChartEventFilter[]) {const where = getEventFiltersWhereClause(filters.flatMap((item) => {+ if (!WHITELISTED_FILTERS.includes(item.name)) {+ return []+ }if (type === 'sessions') {if (item.name === 'path') {return [{ ...item, name: 'entry_path' }];@@ -744,6 +765,10 @@ export class OverviewService {column,timezone,}: IGetTopGenericInput) {+ if (!WHITELISTED_FILTERS.includes(column)) {+ return [];+ }+const prefixColumn = COLUMN_PREFIX_MAP[column] ?? null;const selectColumns: (string | null | undefined | false)[] = [@@ -1470,11 +1495,12 @@ export async function getTrafficBreakdownCore(input: {startDate: string;endDate: string;column: TrafficColumn;+ filters?: IChartEventFilter[];}) {const { timezone } = await getSettingsForProject(input.projectId);return overviewService.getTopGeneric({projectId: input.projectId,- filters: [],+ filters: input.filters ?? [],startDate: input.startDate,endDate: input.endDate,column: input.column,@@ -1487,6 +1513,7 @@ export interface GetAnalyticsOverviewInput {startDate: string;endDate: string;interval?: 'hour' | 'day' | 'week' | 'month';+ filters?: IChartEventFilter[];}export async function getAnalyticsOverviewCore(@@ -1497,7 +1524,7 @@ export async function getAnalyticsOverviewCore(const result = await overviewService.getMetrics({projectId: input.projectId,- filters: [],+ filters: input.filters ?? [],startDate: input.startDate,endDate: input.endDate,interval,diff --git a/packages/db/src/services/pages.service.ts b/packages/db/src/services/pages.service.tsindex 663aaa9db..c8a0796da 100644--- a/packages/db/src/services/pages.service.ts+++ b/packages/db/src/services/pages.service.ts@@ -1,4 +1,4 @@-import type { IInterval } from '@openpanel/validation';+import type { IChartEventFilter, IInterval } from '@openpanel/validation';import sqlstring from 'sqlstring';import { ch, TABLE_NAMES, chQuery } from '../clickhouse/client';import { clix } from '../clickhouse/query-builder';@@ -184,11 +184,12 @@ export async function getTopPagesCore(input: {startDate: string;endDate: string;limit?: number;+ filters?: IChartEventFilter[];}) {const { timezone } = await getSettingsForProject(input.projectId);return _overviewServiceForPages.getTopPages({projectId: input.projectId,- filters: [],+ filters: input.filters ?? [],startDate: input.startDate,endDate: input.endDate,timezone,@@ -200,11 +201,12 @@ export async function getEntryExitPagesCore(input: {startDate: string;endDate: string;mode: 'entry' | 'exit';+ filters?: IChartEventFilter[];}) {const { timezone } = await getSettingsForProject(input.projectId);return _overviewServiceForPages.getTopEntryExit({projectId: input.projectId,- filters: [],+ filters: input.filters ?? [],startDate: input.startDate,endDate: input.endDate,mode: input.mode,diff --git a/packages/db/src/types.ts b/packages/db/src/types.tsindex f695e68c6..464d707fa 100644--- a/packages/db/src/types.ts+++ b/packages/db/src/types.ts@@ -25,6 +25,12 @@ declare global {type IPrismaClickhouseEvent = IClickhouseEvent;type IPrismaClickhouseProfile = IClickhouseProfile;type IPrismaClickhouseBotEvent = IClickhouseBotEvent;+ // Each ChatMessage row stores one Better Agent `ConversationItem`+ // (message, tool call, or tool result) as JSON. Typed as `unknown[]`+ // here to avoid pulling `@better-agent/core` into @openpanel/db's+ // dependency graph; the real shape is narrowed at the API boundary+ // in apps/api/src/agents/persistence.ts.+ type IPrismaUIMessageParts = unknown[];type IPrismaSubscriptionStatus =| 'incomplete'| 'incomplete_expired'diff --git a/packages/mcp/index.ts b/packages/mcp/index.tsindex 577d576ef..74f3b3572 100644--- a/packages/mcp/index.ts+++ b/packages/mcp/index.ts@@ -3,3 +3,7 @@ export { SessionManager } from './src/session-manager';export { authenticateToken, McpAuthError, extractToken } from './src/auth';export { handleMcpGet, handleMcpPost } from './src/handler';export type { McpAuthContext } from './src/auth';++// Reusable handler logic for the in-app chat (apps/api/src/chat/tools/).+// These are pure functions, transport-agnostic — they don't touch MCP at all.+export { runReport, runReportFromConfig } from './src/tools/analytics/reports';diff --git a/packages/mcp/src/tools/analytics/reports.ts b/packages/mcp/src/tools/analytics/reports.tsindex 97192c9b4..65739d31c 100644--- a/packages/mcp/src/tools/analytics/reports.ts+++ b/packages/mcp/src/tools/analytics/reports.ts@@ -94,44 +94,115 @@ export function registerReportTools(async ({ projectId: inputProjectId, reportId }) =>withErrorHandling(async () => {const projectId = await resolveProjectId(context, inputProjectId);- const report = await getReportById(reportId);+ return runReport({ organizationId: context.organizationId, projectId, reportId });+ }),+ );+}- if (!report) {- return { error: 'Report not found', reportId };- }+/**+ * Execute a saved report by ID. Dispatches on chart type:+ * - funnel → funnelService.getFunnel+ * - metric → AggregateChartEngine.execute+ * - others → ChartEngine.execute+ *+ * Exported so the in-app chat (apps/api/src/chat/tools/base.ts) can reuse the+ * dispatch without going through MCP.+ */+export async function runReport(input: {+ organizationId: string;+ projectId: string;+ reportId: string;+}): Promise<+ | { error: string; reportId: string }+ | {+ id: string;+ name: string;+ chartType: string;+ range: string;+ interval: string;+ startDate: string;+ endDate: string;+ dashboard_url: string;+ data: unknown;+ }+> {+ const report = await getReportById(input.reportId);- if (report.projectId !== projectId) {- return { error: 'Report does not belong to this project', reportId };- }+ if (!report) {+ return { error: 'Report not found', reportId: input.reportId };+ }- const { timezone } = await getSettingsForProject(projectId);- const { startDate, endDate } = getChartStartEndDate(report, timezone);- const chartInput = { ...report, startDate, endDate, timezone };+ if (report.projectId !== input.projectId) {+ return { error: 'Report does not belong to this project', reportId: input.reportId };+ }- const meta = {- id: report.id,- name: report.name,- chartType: report.chartType,- range: report.range,- interval: report.interval,- startDate,- endDate,- dashboard_url: reportUrl(context.organizationId, projectId, reportId),- };+ const { timezone } = await getSettingsForProject(input.projectId);+ const { startDate, endDate } = getChartStartEndDate(report, timezone);+ const chartInput = { ...report, startDate, endDate, timezone };- if (report.chartType === 'funnel') {- const result = await funnelService.getFunnel(chartInput);- return { ...meta, data: result };- }+ const meta = {+ id: report.id,+ name: report.name,+ chartType: report.chartType,+ range: report.range,+ interval: report.interval,+ startDate,+ endDate,+ dashboard_url: reportUrl(input.organizationId, input.projectId, input.reportId),+ };- if (report.chartType === 'metric') {- const result = await AggregateChartEngine.execute(chartInput);- return { ...meta, data: result };- }+ if (report.chartType === 'funnel') {+ return { ...meta, data: await funnelService.getFunnel(chartInput) };+ }+ if (report.chartType === 'metric') {+ return { ...meta, data: await AggregateChartEngine.execute(chartInput) };+ }+ return { ...meta, data: await ChartEngine.execute(chartInput) };+}- // linear, bar, histogram, pie, area, map, etc.- const result = await ChartEngine.execute(chartInput);- return { ...meta, data: result };- }),- );+/**+ * Execute an ad-hoc report config (no DB lookup — config is supplied directly).+ * Used by `generate_report` tool in chat.+ */+export async function runReportFromConfig(input: {+ organizationId: string;+ projectId: string;+ /** Full zReportInput shape, with required startDate/endDate */+ config: {+ chartType: string;+ interval: string;+ startDate: string;+ endDate: string;+ [key: string]: unknown;+ };+}): Promise<{+ chartType: string;+ interval: string;+ startDate: string;+ endDate: string;+ report: typeof input.config & { projectId: string };+ data: unknown;+}> {+ const { timezone } = await getSettingsForProject(input.projectId);+ const chartInput = {+ ...input.config,+ projectId: input.projectId,+ timezone,+ } as unknown as Parameters<typeof ChartEngine.execute>[0];++ const meta = {+ chartType: input.config.chartType,+ interval: input.config.interval,+ startDate: input.config.startDate,+ endDate: input.config.endDate,+ report: { ...input.config, projectId: input.projectId },+ };++ if (input.config.chartType === 'funnel') {+ return { ...meta, data: await funnelService.getFunnel(chartInput as Parameters<typeof funnelService.getFunnel>[0]) };+ }+ if (input.config.chartType === 'metric') {+ return { ...meta, data: await AggregateChartEngine.execute(chartInput) };+ }+ return { ...meta, data: await ChartEngine.execute(chartInput) };}diff --git a/packages/trpc/src/root.ts b/packages/trpc/src/root.tsindex 808de8c68..2579322ad 100644--- a/packages/trpc/src/root.ts+++ b/packages/trpc/src/root.ts@@ -1,7 +1,7 @@import { authRouter } from './routers/auth';import { chartRouter } from './routers/chart';-import { chatRouter } from './routers/chat';import { clientRouter } from './routers/client';+import { conversationRouter } from './routers/conversation';import { dashboardRouter } from './routers/dashboard';import { emailRouter } from './routers/email';import { eventRouter } from './routers/event';@@ -51,7 +51,7 @@ export const appRouter = createTRPCRouter({subscription: subscriptionRouter,overview: overviewRouter,realtime: realtimeRouter,- chat: chatRouter,+ conversation: conversationRouter,insight: insightRouter,widget: widgetRouter,email: emailRouter,diff --git a/packages/trpc/src/routers/chat.ts b/packages/trpc/src/routers/chat.tsdeleted file mode 100644index 2ee348740..000000000--- a/packages/trpc/src/routers/chat.ts+++ /dev/null@@ -1,20 +0,0 @@-import { z } from 'zod';--import { db } from '@openpanel/db';--import { createTRPCRouter, protectedProcedure } from '../trpc';--export const chatRouter = createTRPCRouter({- get: protectedProcedure- .input(z.object({ projectId: z.string() }))- .query(async ({ input }) => {- return db.chat.findFirst({- where: {- projectId: input.projectId,- },- orderBy: {- createdAt: 'desc',- },- });- }),-});diff --git a/packages/trpc/src/routers/conversation.ts b/packages/trpc/src/routers/conversation.tsnew file mode 100644index 000000000..6a1c40d82--- /dev/null+++ b/packages/trpc/src/routers/conversation.ts@@ -0,0 +1,125 @@+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import {+ deleteConversation,+ getConversationById,+ getOrganizationByProjectIdCached,+ listConversations,+ upsertConversationTitle,+} from '@openpanel/db';++import { getProjectAccess } from '../access';+import { TRPCAccessError } from '../errors';+import { createTRPCRouter, protectedProcedure } from '../trpc';++/**+ * Conversation management — listing, fetching, renaming, deleting.+ * Conversation creation is implicit (lazy) on the first message via the+ * /ai/chat controller, so there's no `create` here.+ *+ * All procedures enforce ownership via `userId === session.userId` so a+ * user can never read or mutate another user's conversations.+ */+export const conversationRouter = createTRPCRouter({+ list: protectedProcedure+ .input(+ z.object({+ projectId: z.string(),+ limit: z.number().min(1).max(200).default(50),+ }),+ )+ .query(async ({ input, ctx }) => {+ const access = await getProjectAccess({+ projectId: input.projectId,+ userId: ctx.session.userId,+ });+ if (!access) {+ throw TRPCAccessError('You do not have access to this project');+ }+ return listConversations({+ projectId: input.projectId,+ userId: ctx.session.userId,+ limit: input.limit,+ });+ }),++ get: protectedProcedure+ .input(z.object({ id: z.string() }))+ .query(async ({ input, ctx }) => {+ const conv = await getConversationById(input.id, { withMessages: true });+ if (!conv || conv.userId !== ctx.session.userId) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Conversation not found' });+ }+ return conv;+ }),++ rename: protectedProcedure+ .input(+ z.object({+ id: z.string(),+ title: z.string().min(1).max(80),+ /**+ * Required so we can create the row if the titler finishes+ * before the agent's first persistence save. When the row+ * already exists this is ignored — the ownership check+ * below still applies. `organizationId` is derived from the+ * project, not trusted from the client.+ */+ projectId: z.string(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ // If the conversation already exists, enforce ownership. If it+ // doesn't, verify the caller has access to the project being+ // created under before letting the upsert create a fresh row.+ const conv = await getConversationById(input.id);+ if (conv) {+ if (conv.userId !== ctx.session.userId) {+ throw new TRPCError({+ code: 'NOT_FOUND',+ message: 'Conversation not found',+ });+ }+ } else {+ const access = await getProjectAccess({+ projectId: input.projectId,+ userId: ctx.session.userId,+ });+ if (!access) {+ throw TRPCAccessError('You do not have access to this project');+ }+ }+ // Derive organizationId from the project — we never trust a+ // client-supplied value here, even if the caller has access to+ // the project (they'd still be able to tag the conversation with+ // an unrelated org id).+ const organization = await getOrganizationByProjectIdCached(+ input.projectId,+ );+ if (!organization) {+ throw new TRPCError({+ code: 'NOT_FOUND',+ message: 'Project not found',+ });+ }+ return upsertConversationTitle({+ id: input.id,+ title: input.title,+ projectId: input.projectId,+ organizationId: organization.id,+ userId: ctx.session.userId,+ });+ }),++ delete: protectedProcedure+ .input(z.object({ id: z.string() }))+ .mutation(async ({ input, ctx }) => {+ const conv = await getConversationById(input.id);+ if (!conv || conv.userId !== ctx.session.userId) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Conversation not found' });+ }+ await deleteConversation(input.id);+ return { success: true };+ }),+});diff --git a/packages/validation/src/chat.ts b/packages/validation/src/chat.tsnew file mode 100644index 000000000..9fe6ecb3c--- /dev/null+++ b/packages/validation/src/chat.ts@@ -0,0 +1,255 @@+import { z } from 'zod';++/**+ * Shared chat/agent schemas and the model whitelist.+ *+ * Lives in `@openpanel/validation` so both `apps/api` (which builds+ * the Better Agent app) and `apps/start` (which types the client and+ * the model picker) import from the same module instead of reaching+ * across the app boundary with relative paths.+ *+ * The full `ChatApp` type (Better Agent's inferred app type) still+ * lives in `apps/api/src/agents/app.ts` — it's `typeof chatApp` and+ * inherently bound to the server-side agent definition. The frontend+ * types its client against it via a narrow type-only import; schemas+ * + the model whitelist are what actually duplicated before this+ * move, and they now come from here.+ */++// ────────────────────────────────────────────────────────────────────+// Page context — "what the user is looking at right now"+// ────────────────────────────────────────────────────────────────────++export const pageContextPageSchema = z.enum([+ 'overview',+ 'insights',+ 'pages',+ 'seo',+ 'sessionDetail',+ 'profileDetail',+ 'reportEditor',+ 'events',+ 'groupDetail',+]);++export const pageContextSchema = z.object({+ page: pageContextPageSchema,+ route: z.object({+ projectId: z.string(),+ organizationId: z.string(),+ }),+ ids: z+ .object({+ sessionId: z.string().optional(),+ profileId: z.string().optional(),+ reportId: z.string().optional(),+ groupId: z.string().optional(),+ })+ .optional(),+ filters: z+ .object({+ range: z.string().optional(),+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ interval: z.string().optional(),+ eventNames: z.array(z.string()).optional(),+ eventFilters: z.array(z.record(z.string(), z.unknown())).optional(),+ search: z.string().optional(),+ })+ .optional(),+ reportDraft: z.record(z.string(), z.unknown()).optional(),+ primer: z.record(z.string(), z.unknown()).optional(),+});++export type PageContext = z.infer<typeof pageContextSchema>;+export type PageContextPage = z.infer<typeof pageContextPageSchema>;++/**+ * Agent context shared by every agent. The client sends all three fields,+ * but the auth plugin guard validates that the session user actually has+ * access to (projectId, organizationId) and rejects mismatches before+ * the agent ever runs. Tools may safely trust these values.+ */+export const chatContextSchema = z.object({+ projectId: z.string(),+ organizationId: z.string(),+ pageContext: pageContextSchema.optional(),+});++export type ChatAgentContext = z.infer<typeof chatContextSchema>;++// ────────────────────────────────────────────────────────────────────+// Model whitelist — single source of truth, consumed by:+// - apps/api (builds an agent per entry)+// - apps/start (model picker)+// Adding a new model = add an entry here. No other changes required.+// ────────────────────────────────────────────────────────────────────++export type ChatModelEntry = {+ /** URL-safe agent name (no colons, slashes, or percent-encoding needed). */+ id: string;+ /** Native model id passed to the provider client. */+ modelId: string;+ label: string;+ group: 'OpenAI';+ /**+ * When true, the agent is configured with the provider's `reasoning`+ * options so the model returns reasoning tokens as streamed text+ * events. Only set this on reasoning-capable models (o-series,+ * gpt-5 / gpt-5.x, etc.). Non-reasoning models reject the option.+ */+ reasoning?: boolean;+};++export const CHAT_MODELS = [+ { id: 'gpt-4-1', modelId: 'gpt-4.1', label: 'GPT-4.1', group: 'OpenAI' },+ {+ id: 'gpt-4-1-mini',+ modelId: 'gpt-4.1-mini',+ label: 'GPT-4.1 mini',+ group: 'OpenAI',+ },+ {+ id: 'gpt-5.4-mini',+ modelId: 'gpt-5.4-mini',+ label: 'GPT-5.4 mini',+ group: 'OpenAI',+ reasoning: true,+ },+] as const satisfies readonly ChatModelEntry[];++export type ChatModelId = (typeof CHAT_MODELS)[number]['id'];++export const DEFAULT_MODEL_ID: ChatModelId = CHAT_MODELS[0].id;++export const MODEL_STORAGE_KEY = 'op-chat-model';++export function isValidModelId(id: string | null | undefined): id is ChatModelId {+ return !!id && CHAT_MODELS.some((m) => m.id === id);+}++export function getModelLabel(id: string): string {+ return CHAT_MODELS.find((m) => m.id === id)?.label ?? id;+}++// ────────────────────────────────────────────────────────────────────+// Client-side tool schemas — the three URL-param mutators the LLM can+// call on the page. Defined here because both the server (wraps them+// with `defineTool().client()`) and the client (types handler inputs)+// need the same Zod schema.+// ────────────────────────────────────────────────────────────────────++export const applyFiltersSchema = z.object({+ range: z+ .enum([+ '30min',+ 'lastHour',+ 'today',+ 'yesterday',+ '7d',+ '30d',+ '6m',+ '12m',+ 'monthToDate',+ 'lastMonth',+ 'yearToDate',+ 'lastYear',+ 'custom',+ ])+ .optional()+ .describe(+ 'Preset date range. Use ONE of these exact values; anything else (e.g. "last week", "14d", "Q1 2026") MUST go through startDate + endDate as a custom range.',+ ),+ startDate: z+ .string()+ .optional()+ .describe(+ 'ISO date YYYY-MM-DD. Pair with endDate for custom ranges. Switches range to custom automatically.',+ ),+ endDate: z+ .string()+ .optional()+ .describe('ISO date YYYY-MM-DD. Pair with startDate.'),+ interval: z+ .enum(['minute', 'hour', 'day', 'week', 'month'])+ .optional()+ .describe(+ 'Override the chart interval (otherwise auto-picked from the range).',+ ),+});++export type ApplyFiltersInput = z.infer<typeof applyFiltersSchema>;++export const setPropertyFiltersSchema = z.object({+ filters: z+ .array(+ z.object({+ name: z+ .string()+ .describe(+ [+ 'Property key. Common values:',+ '- Geo: country, region, city',+ '- Device: device, browser, os',+ '- Referrer: PREFER `referrer_name` for filtering by source name (e.g. "GitHub", "Hacker News", "Direct"). Use `referrer_type` only for traffic class (search, social, direct, etc.) and the raw `referrer` URL only when the user asks for an exact URL match.',+ '- Page: path, origin',+ '- UTM: utm_source, utm_medium, utm_campaign, utm_term, utm_content',+ 'Verify with list_event_properties when unsure.',+ ].join('\n'),+ ),+ operator: z+ .enum([+ 'is',+ 'isNot',+ 'contains',+ 'doesNotContain',+ 'startsWith',+ 'endsWith',+ 'regex',+ 'isNull',+ 'isNotNull',+ 'gt',+ 'lt',+ 'gte',+ 'lte',+ ])+ .default('is'),+ value: z+ .array(z.string())+ .describe(+ 'Values to match. Multiple values are OR\'d together within the same filter (e.g. ["SE", "US"] = country is SE or US). Use [] when operator is isNull / isNotNull.',+ ),+ }),+ )+ .describe(+ 'The full new filter set. REPLACES the current filters — to add to the existing set, include the current ones too.',+ ),+});++export type SetPropertyFiltersInput = z.infer<typeof setPropertyFiltersSchema>;++export const setEventNamesFilterSchema = z.object({+ eventNames: z+ .array(z.string())+ .describe('Full list of event names to restrict to. Empty = show all.'),+});++export type SetEventNamesFilterInput = z.infer<typeof setEventNamesFilterSchema>;++/**+ * Handler-map type for the client-side UI-mutator tools.+ *+ * Better Agent's `toolHandlers` expects each value to be+ * `(input: unknown, ctx?: ...) => unknown`, so the input is typed as+ * `unknown` here — the concrete handlers narrow with a cast using the+ * matching `*Input` type exported above. The point of this type is+ * the *key set*: adding a new `.client()` tool on the server surfaces+ * an unused-property error here, forcing us to register a handler+ * rather than silently returning undefined. It avoids the frontend+ * needing to cross the app boundary for its handler typing.+ */+export type ChatClientToolHandlers = {+ apply_filters: (input: unknown) => unknown | Promise<unknown>;+ set_property_filters: (input: unknown) => unknown | Promise<unknown>;+ set_event_names_filter: (input: unknown) => unknown | Promise<unknown>;+};diff --git a/packages/validation/src/index.ts b/packages/validation/src/index.tsindex 67a41956b..eaf0de842 100644--- a/packages/validation/src/index.ts+++ b/packages/validation/src/index.ts@@ -639,3 +639,4 @@ export type ICreateImport = z.infer<typeof zCreateImport>;export * from './types.insights';export * from './track.validation';export * from './event-blocklist';+export * from './chat';diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 16d0b5b57..aa12e8b74 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -28,8 +28,8 @@ catalogs:specifier: ^5.9.3version: 5.9.3zod:- specifier: ^4.0.0- version: 4.1.13+ specifier: ^4.1.8+ version: 4.3.6overrides:rolldown: 1.0.0-beta.43@@ -115,12 +115,15 @@ importers:apps/api:dependencies:- '@ai-sdk/anthropic':- specifier: ^1.2.10- version: 1.2.10([email protected])- '@ai-sdk/openai':- specifier: ^1.3.12- version: 1.3.12([email protected])+ '@better-agent/adapters':+ specifier: ^0.1.0-beta.3+ version: 0.1.0-beta.3(@better-agent/[email protected])+ '@better-agent/core':+ specifier: ^0.1.0-beta.3+ version: 0.1.0-beta.3+ '@better-agent/providers':+ specifier: ^0.1.0-beta.3+ version: 0.1.0-beta.3(@better-agent/[email protected])'@fastify/compress':specifier: ^8.1.0version: 8.1.0@@ -190,9 +193,6 @@ importers:'@trpc/server':specifier: ^11.6.0version: 11.6.0([email protected])- ai:- specifier: ^4.2.10- version: 4.2.10([email protected])([email protected])fast-json-stable-hash:specifier: ^1.0.3version: 1.0.3@@ -207,7 +207,7 @@ importers:version: 5.0.0fastify-zod-openapi:specifier: ^5.6.1- version: 5.6.1(@fastify/[email protected])(@fastify/[email protected])([email protected])([email protected])+ version: 5.6.1(@fastify/[email protected])(@fastify/[email protected])([email protected])([email protected])groupmq:specifier: 'catalog:'version: 2.0.0-next.3([email protected])@@ -240,7 +240,7 @@ importers:version: 9.0.1zod:specifier: 'catalog:'- version: 4.1.13+ version: 4.3.6devDependencies:'@faker-js/faker':specifier: ^9.0.1@@ -340,16 +340,16 @@ importers:version: 12.23.25(@emotion/[email protected])([email protected]([email protected]))([email protected])fumadocs-core:specifier: 16.7.11- version: 16.7.11(@mdx-js/[email protected])(@tanstack/[email protected]([email protected]([email protected]))([email protected]))(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])+ version: 16.7.11(@mdx-js/[email protected])(@tanstack/[email protected]([email protected]([email protected]))([email protected]))(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])fumadocs-mdx:specifier: 14.2.11- version: 14.2.11(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected](@mdx-js/[email protected])(@tanstack/[email protected]([email protected]([email protected]))([email protected]))(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 14.2.11(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected](@mdx-js/[email protected])(@tanstack/[email protected]([email protected]([email protected]))([email protected]))(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))fumadocs-openapi:specifier: ^10.6.7- version: 10.6.7(20b279af7e6f0aee6451333d6680f64b)+ version: 10.6.7(01b28b67f52de47092414c2bb19973db)fumadocs-ui:specifier: 16.7.11- version: 16.7.11(@emnapi/[email protected])(@emnapi/[email protected])(@emotion/[email protected])(@types/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected](@mdx-js/[email protected])(@tanstack/[email protected]([email protected]([email protected]))([email protected]))(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])([email protected])+ version: 16.7.11(@emnapi/[email protected])(@emnapi/[email protected])(@emotion/[email protected])(@types/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected](@mdx-js/[email protected])(@tanstack/[email protected]([email protected]([email protected]))([email protected]))(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])([email protected])geist:specifier: 1.5.1version: 1.5.1([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))@@ -388,7 +388,7 @@ importers:version: 1.0.7([email protected])zod:specifier: 'catalog:'- version: 4.1.13+ version: 4.3.6devDependencies:'@tailwindcss/postcss':specifier: ^4.1.17@@ -423,9 +423,9 @@ importers:apps/start:dependencies:- '@ai-sdk/react':- specifier: ^1.2.5- version: 1.2.5([email protected])([email protected])+ '@better-agent/client':+ specifier: ^0.1.0-beta.3'@codemirror/commands':specifier: ^6.7.0version: 6.10.1@@ -636,9 +636,6 @@ importers:'@types/d3':specifier: ^7.4.3version: 7.4.3- ai:- specifier: ^4.2.10- version: 4.2.10([email protected])([email protected])bind-event-listener:specifier: ^3.0.0version: 3.0.0@@ -825,6 +822,9 @@ importers:tw-animate-css:specifier: ^1.3.6version: 1.3.7+ use-stick-to-bottom:+ specifier: ^1.1.3+ version: 1.1.3([email protected])usehooks-ts:specifier: ^2.14.0version: 2.14.0([email protected])@@ -833,7 +833,7 @@ importers:version: 5.1.4([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))zod:specifier: 'catalog:'- version: 4.1.13+ version: 4.3.6devDependencies:'@biomejs/biome':specifier: 1.9.4@@ -1201,7 +1201,7 @@ importers:version: 9.0.1zod:specifier: 'catalog:'- version: 4.1.13+ version: 4.3.6devDependencies:'@openpanel/tsconfig':specifier: workspace:*@@ -1247,7 +1247,7 @@ importers:version: 0.0.5([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])zod:specifier: 'catalog:'- version: 4.1.13+ version: 4.3.6devDependencies:'@openpanel/tsconfig':specifier: workspace:*@@ -1318,7 +1318,7 @@ importers:version: 9.0.1zod:specifier: 'catalog:'- version: 4.1.13+ version: 4.3.6devDependencies:'@openpanel/logger':specifier: workspace:*@@ -1425,7 +1425,7 @@ importers:dependencies:'@modelcontextprotocol/sdk':specifier: ^1.12.0- version: 1.27.1([email protected])+ version: 1.27.1([email protected])'@openpanel/common':specifier: workspace:*version: link:../common@@ -1443,7 +1443,7 @@ importers:version: link:../validationzod:specifier: 'catalog:'- version: 4.1.13+ version: 4.3.6devDependencies:'@openpanel/tsconfig':specifier: workspace:*@@ -1811,7 +1811,7 @@ importers:version: 9.0.1zod:specifier: 'catalog:'- version: 4.1.13+ version: 4.3.6devDependencies:'@openpanel/tsconfig':specifier: workspace:*@@ -1839,7 +1839,7 @@ importers:version: link:../constantszod:specifier: 'catalog:'- version: 4.1.13+ version: 4.3.6devDependencies:'@openpanel/tsconfig':specifier: workspace:*@@ -1884,54 +1884,6 @@ importers:packages:- '@ai-sdk/[email protected]':- resolution: {integrity: sha512-PyE7EC2fPjs9DnzRAHDrPQmcnI2m2Eojr8pfhckOejOlDEh2w7NnSJr1W3qe5hUWzKr+6d7NG1ZKR9fhmpDdEQ==}- engines: {node: '>=18'}- peerDependencies:- zod: ^3.0.0-- '@ai-sdk/[email protected]':- resolution: {integrity: sha512-ueAP69p8a/ZR2ns+pmlr9h/nyV2/DAwzfnPUGZiLpXbxWnLXd2g3a7l38CuEhBydH/nOfDb/byMgpS8+bnJHTg==}- engines: {node: '>=18'}- peerDependencies:- zod: ^3.0.0-- '@ai-sdk/[email protected]':- resolution: {integrity: sha512-o3fWTzkxzI5Af7U7y794MZkYNEsxbjLam2nxyoUZSScqkacb7vZ3EYHLh21+xCcSSzEC161C7pZAGHtC0hTUMw==}- engines: {node: '>=18'}- peerDependencies:- zod: ^3.23.8-- '@ai-sdk/[email protected]':- resolution: {integrity: sha512-kM0xS3GWg3aMChh9zfeM+80vEZfXzR3JEUBdycZLtbRZ2TRT8xOj3WodGHPb06sUK5yD7pAXC/P7ctsi2fvUGQ==}- engines: {node: '>=18'}- peerDependencies:- zod: ^3.23.8-- '@ai-sdk/[email protected]':- resolution: {integrity: sha512-0M+qjp+clUD0R1E5eWQFhxEvWLNaOtGQRUaBn8CUABnSKredagq92hUS9VjOzGsTm37xLfpaxl97AVtbeOsHew==}- engines: {node: '>=18'}-- '@ai-sdk/[email protected]':- resolution: {integrity: sha512-qZMxYJ0qqX/RfnuIaab+zp8UAeJn/ygXXAffR5I4N0n1IrvA6qBsjc8hXLmBiMV2zoXlifkacF7sEFnYnjBcqg==}- engines: {node: '>=18'}-- '@ai-sdk/[email protected]':- resolution: {integrity: sha512-0jOop3S2WkDOdO4X5I+5fTGqZlNX8/h1T1eYokpkR9xh8Vmrxqw8SsovqGvrddTsZykH8uXRsvI+G4FTyy894A==}- engines: {node: '>=18'}- peerDependencies:- react: ^18 || ^19 || ^19.0.0-rc- zod: ^3.23.8- peerDependenciesMeta:- zod:- optional: true-- '@ai-sdk/[email protected]':- resolution: {integrity: sha512-wLTxEZrKZRyBmlVZv8nGXgLBg5tASlqXwbuhoDu0MhZa467ZFREEnosH/OC/novyEHTQXko2zC606xoVbMrUcA==}- engines: {node: '>=18'}- peerDependencies:- zod: ^3.23.8-'@alloc/[email protected]':resolution: {integrity: sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==}engines: {node: '>=10'}@@ -3047,6 +2999,44 @@ packages:resolution: {integrity: sha512-qQ5m48eI/MFLQ5PxQj4PFaprjyCTLI37ElWMmNs0K8Lk3dVeOdNpB3ks8jc7yM5CDmVC73eMVk/trk3fgmrUpA==}engines: {node: '>=6.9.0'}+ '@better-agent/[email protected]':+ resolution: {integrity: sha512-SSxiATXDA2ubfBkX5XDIJ33XbNiXOZ5boHVZM1AJyVVMcm0yhGZX177GesHywgHRslY4fMvPFfHPk28VlTyq/w==}+ peerDependencies:+ '@better-agent/core': 0.1.0-beta.3++ '@better-agent/[email protected]':+ resolution: {integrity: sha512-+fqFcmxHQRBE5D69Cq8EZJpU0xjNi4UfQSSSgxwz2CWmdaGAep6Xhh5CRFaJBvqXv6+WHdM3d8g2sXQKCyZqHw==}+ engines: {bun: '>=1.3.3', node: '>=20'}+ peerDependencies:+ preact: ^10.0.0+ react: ^18.0.0 || ^19.0.0+ solid-js: ^1.9.0+ svelte: ^4.0.0 || ^5.0.0+ vue: ^3.3.0+ peerDependenciesMeta:+ preact:+ optional: true+ react:+ optional: true+ solid-js:+ optional: true+ svelte:+ optional: true+ vue:+ optional: true++ '@better-agent/[email protected]':+ resolution: {integrity: sha512-Mic8iDyHz/2ESTgZvgslPD+zf3iYFiSBda2l0f2T3UD/wMXux9rkSVXCpD8jSgMYWUxx1gt8Fns+7IVQfbnDJw==}+ engines: {bun: '>=1.0.0', node: '>=20'}++ '@better-agent/[email protected]':+ resolution: {integrity: sha512-6YEYeQSyr9a0gzdP08dcyklZ/qjyglmzeUYPg5VotQS19KmV4+ErKHyUm/clGRDdM7+qxz7cC6QbM+6uJ/USUA==}+ peerDependencies:+ '@better-agent/core': 0.1.0-beta.3++ '@better-agent/[email protected]':+ resolution: {integrity: sha512-Rj39OFkWSHEl6uPf3b9zXsFMh3DjbTI9ivghh6+JToVwQM31y6PhaXpWc8xXAIZiParDetJgpNEeWip8UF2vkA==}+'@biomejs/[email protected]':resolution: {integrity: sha512-1rkd7G70+o9KkTn5KLmDYXihGoTaIGO9PIIN2ZB7UJxFrWw04CZHPYiMRjYsaDvVV7hP1dYNRLxSANLaBFGpog==}engines: {node: '>=14.21.3'}@@ -9742,9 +9732,6 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ==}- '@types/[email protected]':- resolution: {integrity: sha512-xFdR6tkm0MWvBfO8xXCSsinYxHcqkQUlcHeSpMC2ukzOb6lwQAfDmW+Qt0AvlGd8HpsS28qKsB+oPeJn9I39jg==}-'@types/[email protected]':resolution: {integrity: sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==}@@ -10370,16 +10357,6 @@ packages:resolution: {integrity: sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==}engines: {node: '>=8'}- resolution: {integrity: sha512-rOfKbNRWlzwxbFll6W9oAdnC0R5VVbAJoof+p92CatHzA3reqQZmYn33IBnj+CgqeXYUsH9KX9Wnj7g2wCHc9Q==}- engines: {node: '>=18'}- peerDependencies:- react: ^18 || ^19 || ^19.0.0-rc- zod: ^3.23.8- peerDependenciesMeta:- react:- optional: true-resolution: {integrity: sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==}peerDependencies:@@ -11940,9 +11917,6 @@ packages:resolution: {integrity: sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==}- resolution: {integrity: sha512-IayShXAgj/QMXgB0IWmKx+rOPuGMhqm5w6jvFxmVenXKIzRqTAAsbBPT3kWQeGANj3jGgvcvv4yK6SxqYmikgw==}-resolution: {integrity: sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==}engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}@@ -14032,15 +14006,16 @@ packages:resolution: {integrity: sha512-HqMnbz0tz2DaEJ3ntsqtx3ezzZyDE7G56A/pPY/NGmrPu76UzsWquOpHFRAf5beTNXoH2LU5cQePVvRli1nchA==}engines: {node: '>=20'}+ resolution: {integrity: sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==}+ engines: {node: '>=16'}+resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==}resolution: {integrity: sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==}- resolution: {integrity: sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==}-resolution: {integrity: sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==}@@ -14052,11 +14027,6 @@ packages:resolution: {integrity: sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==}- resolution: {integrity: sha512-3QItJOXp2AP1uv7waBkao5nCvhEv+QmJAd38Ybq7wNI74Q+BBmnLn4EDKz6yI9xGAIQoUF87qHt+kc1IVxB4zQ==}- engines: {node: ^18.0.0 || >=20.0.0}- hasBin: true-resolution: {integrity: sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==}@@ -15149,6 +15119,10 @@ packages:resolution: {integrity: sha512-SrQrok4CATudVzBS7coSz26QRSmlK9TzzoFbeKfcPBUFPjcQM9Rqvr/DlJkOrwI/0KcgvMub1n1g5Jt9EgRn4A==}+ resolution: {integrity: sha512-kOCT/1MCPAxY5iUV3wytNFUMUolzuwd/VF/1KCx7kf6CutrOsTie+84zTGTpgQycjvfLdBBdvBvFLqFD2c0wkQ==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-pZvgD5L0IEvX5/9GWyHMf3m8BKiVQwsCMHfoFosXtXBMnaS0ZnIJ9ST4b4NqLVKDEm8QBxoNNGNaBv2JNF6XNA==}peerDependencies:@@ -17705,11 +17679,6 @@ packages:resolution: {integrity: sha512-TEznBskvdvEJElo/j7BiIZAoaQEWyj/NCmwiV0izlVRf5DnCBFdowkEXERDA3JgUlAYoAJi0S7atWit7nkTMtw==}- resolution: {integrity: sha512-dshNvs3ExOqtZ6kJBaAsabhPdHyeY4P2cKwRCniDVifBMoG/SVI7tfLWqPXriVspf2Rg4tPzXJTnwaihIeFw2A==}- peerDependencies:- react: ^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0-resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==}@@ -17834,10 +17803,6 @@ packages:resolution: {integrity: sha512-fcwX4mndzpLQKBS1DVYhGAcYaYt7vsHNIvQV+WXMvnow5cgjPphq5CaayLaGsjRdSCKZFNGt7/GYAuXaNOiYCA==}- resolution: {integrity: sha512-nt6AMGKW1p/70DF/hGBdJB57B8Tspmbp5gfJ8ilhLnt7kkr2ye7hzD6NVG8GGErk2HWF34igrL2CXmNIkzKqKw==}- engines: {node: '>=18'}-resolution: {integrity: sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==}@@ -17982,6 +17947,9 @@ packages:resolution: {integrity: sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==}+ resolution: {integrity: sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==}+resolution: {integrity: sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==}@@ -18617,16 +18585,16 @@ packages:'@types/react':optional: true+ resolution: {integrity: sha512-GgRLdeGhxBxpcbrBbEIEoOKUQ9d46/eaSII+wyv1r9Du+NbCn1W/OE+VddefvRP4+5w/1kATN/6g2/BAC/yowQ==}+ peerDependencies:+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0+resolution: {integrity: sha512-eEgnFxGQ1Ife9bzYs6VLi8/4X6CObHMw9Qr9tPY43iKwsPw8xE8+EFsf/2cFZ5S3esXgpWgtSCtLNS41F+sKPA==}peerDependencies:react: ^16.8.0 || ^17.0.0 || ^18.0.0- resolution: {integrity: sha512-Rb46I4cGGVBmjamjphe8L/UnvJD+uPPtTkNvX5mZgqdbavhI4EbgIWJiIHXJ8bc/i9EQGPRh4DwEURJ552Do0A==}- peerDependencies:- react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0-resolution: {integrity: sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==}peerDependencies:@@ -19424,9 +19392,6 @@ packages:resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==}- resolution: {integrity: sha512-AvvthqfqrAhNH9dnfmrfKzX5upOdjUVJYFqNSlkmGf64gRaTzlPwz99IHYnVs28qYAybvAlBV+H7pn0saFY4Ig==}-resolution: {integrity: sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==}@@ -19435,57 +19400,6 @@ packages:snapshots:- '@ai-sdk/[email protected]([email protected])':- dependencies:- '@ai-sdk/provider': 1.1.3- '@ai-sdk/provider-utils': 2.2.7([email protected])- zod: 4.1.13-- '@ai-sdk/[email protected]([email protected])':- dependencies:- '@ai-sdk/provider': 1.1.3- '@ai-sdk/provider-utils': 2.2.7([email protected])- zod: 4.1.13-- '@ai-sdk/[email protected]([email protected])':- dependencies:- '@ai-sdk/provider': 1.1.0- nanoid: 3.3.11- secure-json-parse: 2.7.0- zod: 4.1.13-- '@ai-sdk/[email protected]([email protected])':- dependencies:- '@ai-sdk/provider': 1.1.3- nanoid: 3.3.11- secure-json-parse: 2.7.0- zod: 4.1.13-- '@ai-sdk/[email protected]':- dependencies:- json-schema: 0.4.0-- '@ai-sdk/[email protected]':- dependencies:- json-schema: 0.4.0-- dependencies:- '@ai-sdk/provider-utils': 2.2.3([email protected])- '@ai-sdk/ui-utils': 1.2.4([email protected])- react: 19.2.3- swr: 2.3.3([email protected])- throttleit: 2.1.0- optionalDependencies:- zod: 4.1.13-- '@ai-sdk/[email protected]([email protected])':- dependencies:- '@ai-sdk/provider': 1.1.0- '@ai-sdk/provider-utils': 2.2.3([email protected])- zod: 4.1.13- zod-to-json-schema: 3.24.5([email protected])-'@alloc/[email protected]': {}'@ampproject/[email protected]':@@ -22205,6 +22119,36 @@ snapshots:'@babel/helper-string-parser': 7.27.1'@babel/helper-validator-identifier': 7.28.5+ '@better-agent/[email protected](@better-agent/[email protected])':+ dependencies:+ '@better-agent/core': 0.1.0-beta.3++ '@better-agent/[email protected]([email protected])([email protected])([email protected]([email protected]))':+ dependencies:+ '@better-agent/core': 0.1.0-beta.3+ '@better-agent/shared': 0.1.0-beta.3+ optionalDependencies:+ react: 19.2.3+ solid-js: 1.9.9+ vue: 3.5.25([email protected])++ '@better-agent/[email protected]':+ dependencies:+ '@better-agent/shared': 0.1.0-beta.3+ '@standard-schema/spec': 1.1.0+ ajv: 8.18.0+ json-schema-to-ts: 3.1.1++ '@better-agent/[email protected](@better-agent/[email protected])':+ dependencies:+ '@better-agent/core': 0.1.0-beta.3+ '@better-agent/shared': 0.1.0-beta.3+ zod: 4.3.6++ '@better-agent/[email protected]':+ dependencies:+ neverthrow: 8.2.0+'@biomejs/[email protected]':optionalDependencies:'@biomejs/cli-darwin-arm64': 1.9.4@@ -24095,7 +24039,7 @@ snapshots:transitivePeerDependencies:- supports-color- '@modelcontextprotocol/[email protected]([email protected])':+ '@modelcontextprotocol/[email protected]([email protected])':dependencies:'@hono/node-server': 1.19.11([email protected])ajv: 8.18.0@@ -24112,8 +24056,8 @@ snapshots:json-schema-typed: 8.0.2pkce-challenge: 5.0.1raw-body: 3.0.2- zod: 4.1.13- zod-to-json-schema: 3.25.1([email protected])+ zod: 4.3.6+ zod-to-json-schema: 3.25.1([email protected])transitivePeerDependencies:- supports-color@@ -27059,7 +27003,7 @@ snapshots:dependencies:react: 19.2.3- use-sync-external-store: 1.5.0([email protected])+ use-sync-external-store: 1.6.0([email protected])optionalDependencies:'@types/react': 19.2.7@@ -29061,7 +29005,7 @@ snapshots:'@tanstack/store': 0.7.7react: 19.2.3react-dom: 19.2.3([email protected])- use-sync-external-store: 1.5.0([email protected])+ use-sync-external-store: 1.6.0([email protected])dependencies:@@ -29555,8 +29499,6 @@ snapshots:dependencies:'@types/ms': 0.7.34- '@types/[email protected]': {}-'@types/[email protected]':dependencies:'@types/estree': 1.0.8@@ -30360,18 +30302,6 @@ snapshots:clean-stack: 2.2.0indent-string: 4.0.0- dependencies:- '@ai-sdk/provider': 1.1.0- '@ai-sdk/provider-utils': 2.2.3([email protected])- '@ai-sdk/react': 1.2.5([email protected])([email protected])- '@ai-sdk/ui-utils': 1.2.4([email protected])- '@opentelemetry/api': 1.9.0- jsondiffpatch: 0.6.0- zod: 4.1.13- optionalDependencies:- react: 19.2.3-optionalDependencies:ajv: 8.18.0@@ -32216,8 +32146,6 @@ snapshots:- [email protected]: {}-@@ -32333,7 +32261,7 @@ snapshots:dependencies:- '@standard-schema/spec': 1.0.0+ '@standard-schema/spec': 1.1.0fast-check: 3.23.2@@ -33299,14 +33227,14 @@ snapshots:raw-body: 3.0.0secure-json-parse: 2.7.0- [email protected](@fastify/[email protected])(@fastify/[email protected])([email protected])([email protected]):+ [email protected](@fastify/[email protected])(@fastify/[email protected])([email protected])([email protected]):dependencies:'@fastify/error': 4.0.0fast-json-stringify: 6.0.1fastify: 5.6.1fastify-plugin: 5.0.1- zod: 4.1.13- zod-openapi: 5.4.6([email protected])+ zod: 4.3.6+ zod-openapi: 5.4.6([email protected])optionalDependencies:'@fastify/swagger': 9.7.0'@fastify/swagger-ui': 5.2.5@@ -33664,7 +33592,7 @@ snapshots:- '@emnapi/core'- '@emnapi/runtime'- [email protected](@mdx-js/[email protected])(@tanstack/[email protected]([email protected]([email protected]))([email protected]))(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]):+ [email protected](@mdx-js/[email protected])(@tanstack/[email protected]([email protected]([email protected]))([email protected]))(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]):dependencies:'@formatjs/intl-localematcher': 0.8.2'@orama/orama': 3.1.18@@ -33701,18 +33629,18 @@ snapshots:react: 19.2.3react-dom: 19.2.3([email protected])- zod: 4.1.13+ zod: 4.3.6transitivePeerDependencies:- supports-color- [email protected](@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected](@mdx-js/[email protected])(@tanstack/[email protected]([email protected]([email protected]))([email protected]))(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):+ [email protected](@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected](@mdx-js/[email protected])(@tanstack/[email protected]([email protected]([email protected]))([email protected]))(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:'@mdx-js/mdx': 3.1.1'@standard-schema/spec': 1.1.0chokidar: 5.0.0esbuild: 0.27.3estree-util-value-to-estree: 3.5.0- fumadocs-core: 16.7.11(@mdx-js/[email protected])(@tanstack/[email protected]([email protected]([email protected]))([email protected]))(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])+ fumadocs-core: 16.7.11(@mdx-js/[email protected])(@tanstack/[email protected]([email protected]([email protected]))([email protected]))(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])js-yaml: 4.1.1mdast-util-mdx: 3.0.0mdast-util-to-markdown: 2.1.2@@ -33735,7 +33663,7 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected](20b279af7e6f0aee6451333d6680f64b):+ [email protected](01b28b67f52de47092414c2bb19973db):dependencies:'@fastify/deepmerge': 3.2.1'@fumari/json-schema-ts': 0.0.2([email protected])@@ -33750,8 +33678,8 @@ snapshots:chokidar: 5.0.0class-variance-authority: 0.7.1fast-content-type-parse: 3.0.0- fumadocs-core: 16.7.11(@mdx-js/[email protected])(@tanstack/[email protected]([email protected]([email protected]))([email protected]))(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])- fumadocs-ui: 16.7.11(@emnapi/[email protected])(@emnapi/[email protected])(@emotion/[email protected])(@types/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected](@mdx-js/[email protected])(@tanstack/[email protected]([email protected]([email protected]))([email protected]))(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])([email protected])+ fumadocs-core: 16.7.11(@mdx-js/[email protected])(@tanstack/[email protected]([email protected]([email protected]))([email protected]))(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])+ fumadocs-ui: 16.7.11(@emnapi/[email protected])(@emnapi/[email protected])(@emotion/[email protected])(@types/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected](@mdx-js/[email protected])(@tanstack/[email protected]([email protected]([email protected]))([email protected]))(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])([email protected])github-slugger: 2.0.0hast-util-to-jsx-runtime: 2.3.6js-yaml: 4.1.1@@ -33773,7 +33701,7 @@ snapshots:- '@types/react-dom'- supports-color- [email protected](@emnapi/[email protected])(@emnapi/[email protected])(@emotion/[email protected])(@types/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected](@mdx-js/[email protected])(@tanstack/[email protected]([email protected]([email protected]))([email protected]))(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])([email protected]):+ [email protected](@emnapi/[email protected])(@emnapi/[email protected])(@emotion/[email protected])(@types/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected](@mdx-js/[email protected])(@tanstack/[email protected]([email protected]([email protected]))([email protected]))(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])([email protected]):dependencies:'@fumadocs/tailwind': 0.0.3([email protected])'@radix-ui/react-accordion': 1.2.12(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])@@ -33788,7 +33716,7 @@ snapshots:'@radix-ui/react-tabs': 1.1.13(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])class-variance-authority: 0.7.1fuma-cli: 0.0.3(@emnapi/[email protected])(@emnapi/[email protected])- fumadocs-core: 16.7.11(@mdx-js/[email protected])(@tanstack/[email protected]([email protected]([email protected]))([email protected]))(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])+ fumadocs-core: 16.7.11(@mdx-js/[email protected])(@tanstack/[email protected]([email protected]([email protected]))([email protected]))(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])lucide-react: 1.7.0([email protected])motion: 12.38.0(@emotion/[email protected])([email protected]([email protected]))([email protected])@@ -35050,24 +34978,21 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ '@babel/runtime': 7.23.9+ ts-algebra: 2.0.0+- [email protected]: {}-- dependencies:- '@types/diff-match-patch': 1.0.36- chalk: 5.4.1- diff-match-patch: 1.0.5-optionalDependencies:graceful-fs: 4.2.11@@ -36485,6 +36410,10 @@ snapshots:+ optionalDependencies:+ '@rollup/rollup-linux-x64-gnu': 4.52.5+dependencies:react: 19.2.3@@ -39862,12 +39791,6 @@ snapshots:transitivePeerDependencies:- encoding- dependencies:- dequal: 2.0.3- react: 19.2.3- use-sync-external-store: 1.5.0([email protected])-@@ -40023,8 +39946,6 @@ snapshots:- [email protected]: {}-dependencies:readable-stream: 2.3.8@@ -40131,6 +40052,8 @@ snapshots:+ [email protected]: {}+@@ -40724,11 +40647,11 @@ snapshots:optionalDependencies:'@types/react': 19.2.7dependencies:react: 19.2.3dependencies:react: 19.2.3@@ -41606,21 +41529,17 @@ snapshots:dependencies:bops: 0.1.1dependencies:- zod: 4.1.13+ zod: 4.3.6dependencies:zod: 3.25.76dependencies:- zod: 4.1.13-- dependencies:- zod: 4.1.13+ zod: 4.3.6dependencies:@@ -41629,8 +41548,6 @@ snapshots:- [email protected]: {}-diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 4c221bf47..9c96df004 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -6,7 +6,7 @@ packages:# Define a catalog of version ranges.catalog:- zod: ^4.0.0+ zod: ^4.1.8react: ^19.2.3"@types/react": ^19.2.3"react-dom": ^19.2.3