Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

ralph(M5-005): assistant module: Better Agent + tools + /ai/agents + trpc chat into core

ralph87dcc1267414
diff --git a/apps/api/src/agents/app.ts b/apps/api/src/agents/app.ts
index 3034186da..cc02818e8 100644
--- a/apps/api/src/agents/app.ts
+++ b/apps/api/src/agents/app.ts
@@ -1,92 +1,11 @@
-import { betterAgent, defineAgent } from '@better-agent/core';
-import {
- ALLOWED_MODELS,
- type ChatModelEntry,
- openaiProvider,
- resolveModel,
-} from '@openpanel/core';
-import { type ChatAgentContext, chatContextSchema } from './context';
-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;
+// Dissolved into @openpanel/core's assistant module (M5-005): the Better
+// Agent app definition (one agent per allowed model, the Prisma-backed
+// conversation store, the titler agent) moved to
+// packages/core/src/modules/assistant/src/app.ts. This file stays
+// (DELEGATE PATTERN) — apps/api/src/app.ts is the live Fastify route and
+// keeps calling `getChatApp()` from here unchanged.
+//
+// `getChatApp` is a lazy accessor, not a plain value export — see
+// @openpanel/core's index.ts for why a static import here would race
+// @openpanel/db's own circular buffers/base-buffer.ts import.
+export { type ChatApp, getChatApp } from '@openpanel/core';
diff --git a/apps/api/src/agents/context.ts b/apps/api/src/agents/context.ts
deleted file mode 100644
index 7a146a2e4..000000000
--- a/apps/api/src/agents/context.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-// 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/run-context.ts b/apps/api/src/agents/run-context.ts
index 8dd321602..eb58dfb66 100644
--- a/apps/api/src/agents/run-context.ts
+++ b/apps/api/src/agents/run-context.ts
@@ -1,25 +1,9 @@
-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
- * - `resolveDateRange` / the prompt builder, to turn page-context
- * range presets (`"6m"`, `"7d"`, …) into actual dates in the
- * user's project timezone
- *
- * 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;
- /** Project's configured timezone (IANA). Defaults to `UTC`. */
- timezone: string;
-};
-
-export const chatRunContext = new AsyncLocalStorage<ChatRunContext>();
+// Dissolved into @openpanel/core's assistant module (M5-005): the
+// AsyncLocalStorage carrying per-request chat context moved to
+// packages/core/src/modules/assistant/src/run-context.ts. This file stays
+// (DELEGATE PATTERN) — apps/api/src/app.ts wraps the live `/ai/agents/*`
+// handler in `chatRunContext.run(...)`, and the core-side persistence store
+// reads the SAME singleton (resolved once via `getChatRunContext()`, see
+// @openpanel/core's index.ts for why it is a lazy accessor rather than a
+// plain value export).
+export { type ChatRunContext, getChatRunContext } from '@openpanel/core';
diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts
index 282d7ebb3..a4f5ccde9 100644
--- a/apps/api/src/app.ts
+++ b/apps/api/src/app.ts
@@ -36,8 +36,8 @@ import {
serializerCompiler,
validatorCompiler,
} from 'fastify-zod-openapi';
-import { chatApp } from './agents/app';
-import { chatRunContext } from './agents/run-context';
+import { getChatApp } from './agents/app';
+import { getChatRunContext } from './agents/run-context';
import {
healthcheck,
liveness,
@@ -236,6 +236,8 @@ export async function buildApp(
// Preflight OPTIONS is handled by @fastify/cors before this route
// runs, so we only skip auth/ALS for that case.
{
+ const chatApp = await getChatApp();
+ const chatRunContext = await getChatRunContext();
const agentHandler = toFastifyHandler(chatApp);
instance.all('/ai/agents/*', async (request, reply) => {
diff --git a/packages/core/src/clients/ai/providers.ts b/packages/core/src/clients/ai/providers.ts
index b6f1f3546..a92fec224 100644
--- a/packages/core/src/clients/ai/providers.ts
+++ b/packages/core/src/clients/ai/providers.ts
@@ -6,11 +6,11 @@
// `@openpanel/validation` instead.
import { createAnthropic } from '@better-agent/providers/anthropic';
import { createOpenAI } from '@better-agent/providers/openai';
-import type { ChatModelEntry } from '@openpanel/validation';
import { z } from 'zod';
+import type { ChatModelEntry } from '../../modules/assistant/assistant.constants';
-export type { ChatModelEntry } from '@openpanel/validation';
-export { CHAT_MODELS as ALLOWED_MODELS } from '@openpanel/validation';
+export type { ChatModelEntry } from '../../modules/assistant/assistant.constants';
+export { CHAT_MODELS as ALLOWED_MODELS } from '../../modules/assistant/assistant.constants';
const openAiEnvSchema = z.object({
OPENAI_API_KEY: z.string().optional(),
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 0d7a96fcd..00d37c920 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -113,6 +113,55 @@ export {
REQUEST_ID_LENGTH,
REQUEST_ID_LOG_FIELD,
} from './logger';
+// Moved from apps/api/src/agents/* + packages/trpc/src/agents/filter-command.ts
+// (M5-005) — apps/api's `/ai/agents/*` Fastify wrapper and packages/trpc's
+// overview router call these.
+//
+// Loaded via dynamic import, NOT a static re-export like every other service
+// on this barrel: packages/db/src/buffers/base-buffer.ts already imports
+// `@openpanel/core` eagerly, and this module's own chain reaches deep into
+// `@openpanel/db` (the Prisma-backed conversation store, ~30 analytics/report
+// tool functions). A static re-export here would make THIS barrel's own
+// evaluation re-enter `@openpanel/db` while it is still mid-evaluation of
+// `./buffers` — `bot-buffer.ts extends BaseBuffer` then sees `BaseBuffer` as
+// `undefined` (a live TDZ binding that never got the chance to fill in).
+// `event-buffer.test.ts` et al. hit exactly this before this indirection was
+// added. `chatApp` and `chatRunContext` are one-time-per-process values, so
+// callers resolve them once (apps/api's Fastify wrapper does so inside its
+// own already-async route registration) and keep the reference.
+export type {
+ ChatApp,
+ ChatRunContext,
+ FilterCommandResult,
+} from './modules/assistant/assistant.service';
+
+import type { PageContext } from './modules/assistant/assistant.constants';
+
+let _assistant:
+ | Promise<typeof import('./modules/assistant/assistant.service')>
+ | undefined;
+function loadAssistant() {
+ if (!_assistant) {
+ _assistant = import('./modules/assistant/assistant.service');
+ }
+ return _assistant;
+}
+
+export async function getChatApp() {
+ return (await loadAssistant()).chatApp;
+}
+export async function getChatRunContext() {
+ return (await loadAssistant()).chatRunContext;
+}
+export async function runFilterCommand(input: {
+ query: string;
+ projectId: string;
+ pageContext?: PageContext;
+ timezone: string;
+}) {
+ const { runFilterCommand: run } = await loadAssistant();
+ return run(input);
+}
// Dissolved from @openpanel/auth (M4-007) — apps/api's OAuth callbacks and
// @openpanel/trpc's auth/share/user/gsc routers call these directly, the same
// way they reach the other dissolved leaf packages here. `hashPassword` is
diff --git a/packages/core/src/modules/assistant/assistant.constants.ts b/packages/core/src/modules/assistant/assistant.constants.ts
new file mode 100644
index 000000000..0bacbdf9e
--- /dev/null
+++ b/packages/core/src/modules/assistant/assistant.constants.ts
@@ -0,0 +1,321 @@
+import { z } from 'zod';
+
+/**
+ * Moved from packages/validation/src/chat.ts (M5-005, ADR-008's module map:
+ * assistant owns "C"). packages/validation/src/chat.ts becomes a re-export
+ * shim of this file (same shape as packages/validation/src/import.validation.ts
+ * since M5-004), so apps/start's model picker and the SDK-facing types keep
+ * resolving these symbols through @openpanel/validation's existing barrel
+ * unchanged.
+ *
+ * Isomorphic by the AGENTS.md rule: zod and nothing else.
+ *
+ * The full `ChatApp` type (Better Agent's inferred app type) lives in
+ * `./src/app.ts` — it's `typeof chatApp` and inherently bound to the
+ * server-side agent definition, so it stays out of this constants file
+ * (a Prisma/Better-Agent type would follow it into a browser bundle).
+ * `apps/api/src/agents/app.ts` re-exports it (DELEGATE PATTERN) for the
+ * frontend's narrow type-only import.
+ */
+
+// ────────────────────────────────────────────────────────────────────
+// Page context — "what the user is looking at right now"
+// ────────────────────────────────────────────────────────────────────
+
+export const pageContextPageSchema = z.enum([
+ 'overview',
+ 'insights',
+ 'pages',
+ 'seo',
+ 'sessionDetail',
+ 'profileDetail',
+ 'reportEditor',
+ 'events',
+ 'groupDetail',
+ 'dashboard',
+]);
+
+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(),
+ dashboardId: 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 ChatProvider = 'OpenAI' | 'Anthropic';
+
+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: ChatProvider;
+ /**
+ * 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,
+ },
+ {
+ id: 'claude-haiku-4-5',
+ modelId: 'claude-haiku-4-5',
+ label: 'Claude Haiku 4.5',
+ group: 'Anthropic',
+ },
+ {
+ id: 'claude-sonnet-4-6',
+ modelId: 'claude-sonnet-4-6',
+ label: 'Claude Sonnet 4.6',
+ group: 'Anthropic',
+ },
+ {
+ id: 'claude-opus-4-6',
+ modelId: 'claude-opus-4-6',
+ label: 'Claude Opus 4.6',
+ group: 'Anthropic',
+ },
+] as const satisfies readonly ChatModelEntry[];
+
+export type ChatModelId = (typeof CHAT_MODELS)[number]['id'];
+
+/**
+ * localStorage key holding the user's preferred chat model id.
+ *
+ * Bumped to `v2` when the default was switched from `gpt-4-1` to
+ * `gpt-4-1-mini` (April 2026). Existing users had `gpt-4-1` pinned in
+ * their v1 key and hit rate-limit errors almost immediately on Tier 1
+ * OpenAI accounts; invalidating the old key is the only way to
+ * migrate them to the new default without a UI prompt. If you change
+ * the default again, bump the suffix.
+ */
+export const MODEL_STORAGE_KEY = 'op-chat-model-v2';
+
+/**
+ * Preferred default model id. The tRPC `chat.models` endpoint picks
+ * this when it's available in the configured provider set, falling
+ * back to the first entry in `CHAT_MODELS` otherwise. Picked for its
+ * much higher per-minute token budget (OpenAI Tier 1 gives gpt-4.1
+ * just 30k TPM — one user exhausts it with a single long turn —
+ * whereas gpt-4.1-mini gets 200k TPM for the same tier).
+ */
+export const PREFERRED_DEFAULT_MODEL_ID = 'gpt-4-1-mini';
+
+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;
+}
+
+/**
+ * Filter the whitelist to models whose provider has an API key configured.
+ * Returned in the same order as `CHAT_MODELS` (OpenAI first, then Anthropic)
+ * so the first entry is a stable default.
+ */
+export function getAvailableChatModels(providers: {
+ openai: boolean;
+ anthropic: boolean;
+}): ChatModelEntry[] {
+ return CHAT_MODELS.filter((m) => {
+ if (m.group === 'OpenAI') {
+ return providers.openai;
+ }
+ if (m.group === 'Anthropic') {
+ return providers.anthropic;
+ }
+ return false;
+ });
+}
+
+// ────────────────────────────────────────────────────────────────────
+// 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/core/src/modules/assistant/assistant.routes.ts b/packages/core/src/modules/assistant/assistant.routes.ts
new file mode 100644
index 000000000..8ee4a88ee
--- /dev/null
+++ b/packages/core/src/modules/assistant/assistant.routes.ts
@@ -0,0 +1,120 @@
+// Better Agent chat, mounted under `/ai/agents/*` (M5-005). V1's inline
+// Fastify wrapper (apps/api/src/app.ts:223-345) stays the LIVE route
+// (DELEGATE PATTERN) and already calls `chatApp`/`chatRunContext` via
+// `@openpanel/core`'s lazy getters — this route exists to satisfy the module
+// map ("H") and to serve core's own (not yet live) `dashboardRoutes`.
+//
+// NAMED GAP, same as gsc.routes.ts / import.routes.ts: this route is not yet
+// reachable. `resolveSession` (http/session.ts) is a P2 stub that always
+// returns `null`, so the `session` macro 401s every request; main.ts also
+// does not mount `dashboardRoutes` until a real `AppDeps` exists.
+//
+// Elysia has no adapter in `@better-agent/adapters` (only express/fastify),
+// but `BetterAgentApp.handler` already speaks the Web `Request`/`Response`
+// pair Elysia's own handlers do, so this route calls it directly instead of
+// waiting on one. The request body is read via `request.clone()` for the
+// project-access check below — `chatApp.handler` gets the original,
+// unconsumed `request` so it can re-read the body itself.
+//
+// Everything below is dynamically imported, not statically — index.ts's
+// header explains why a static import of `@openpanel/db` or
+// `./assistant.service` here would race `@openpanel/db`'s own circular
+// `buffers/base-buffer.ts` -> `@openpanel/core` import.
+
+import { defineRoutes } from '../../http/define';
+
+function loadDb() {
+ return import('@openpanel/db');
+}
+function loadAssistant() {
+ return import('./assistant.service');
+}
+
+interface RunBody {
+ context?: { projectId?: string; organizationId?: string };
+}
+
+export const assistantRoutes = defineRoutes((app) =>
+ app.all(
+ '/ai/agents/*',
+ async ({ params, session, status, request }) => {
+ const userId = session.userId;
+ if (!userId) {
+ return status(401, { message: 'Sign in required' });
+ }
+
+ const { chatApp, chatRunContext } = await loadAssistant();
+
+ // 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 = params['*'] ?? '';
+ 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 chatApp.handler(request);
+ }
+
+ // Conversation hydration: verify ownership if the row already exists.
+ // A brand-new chat (no row yet) falls through to the agent handler,
+ // whose `ConversationStore.load()` returns null.
+ if (route === 'conversations' && routeId) {
+ const { getConversationById } = await loadDb();
+ const conv = await getConversationById(routeId);
+ if (conv && conv.userId !== userId) {
+ return status(404, { message: 'Conversation not found' });
+ }
+ return chatApp.handler(request);
+ }
+
+ // Everything else (primarily `POST /:name/run`) is an active run and
+ // must carry `context.projectId` + `context.organizationId`.
+ const body = (await request
+ .clone()
+ .json()
+ .catch(() => null)) as RunBody | null;
+ const projectId = body?.context?.projectId;
+ const organizationIdFromBody = body?.context?.organizationId;
+
+ if (!(projectId && organizationIdFromBody)) {
+ return status(400, {
+ message: 'Missing projectId or organizationId in context',
+ });
+ }
+
+ const {
+ getOrganizationByProjectIdCached,
+ getProjectAccess,
+ getSettingsForProject,
+ } = await loadDb();
+ const [access, organization, settings] = await Promise.all([
+ getProjectAccess({ projectId, userId }),
+ getOrganizationByProjectIdCached(projectId),
+ getSettingsForProject(projectId).catch(() => ({ timezone: 'UTC' })),
+ ]);
+ if (
+ !(access && organization) ||
+ organization.id !== organizationIdFromBody
+ ) {
+ return status(403, { message: 'No access to this project' });
+ }
+
+ return chatRunContext.run(
+ {
+ userId,
+ projectId,
+ organizationId: organization.id,
+ timezone: settings.timezone || 'UTC',
+ },
+ () => chatApp.handler(request)
+ );
+ },
+ { session: true, detail: { hide: true } }
+ )
+);
diff --git a/packages/core/src/modules/assistant/assistant.rpc.test.ts b/packages/core/src/modules/assistant/assistant.rpc.test.ts
new file mode 100644
index 000000000..419b06ea6
--- /dev/null
+++ b/packages/core/src/modules/assistant/assistant.rpc.test.ts
@@ -0,0 +1,79 @@
+// Only the "is anyone logged in" boundary and the deterministic model-list
+// shape are exercised here — no LLM call, no database. `chat.models` reads
+// only `process.env` + the static whitelist (assistant.constants.ts);
+// wiring the live-model whitelist against real provider keys is out of
+// scope for a unit test — see assistant.rpc.ts's header.
+
+import { afterEach, beforeEach, expect, test } from 'bun:test';
+import { stubHttpCtx, TEST_SESSION } from '../../../test/rpc-fixtures';
+import { makeTrpcContext } from '../../rpc/base';
+import type { CookieOptions } from '../../shared/cookie';
+import { chatRouter } from './assistant.rpc';
+
+const COOKIE_OPTIONS: CookieOptions = {
+ domain: '.openpanel.dev',
+ secure: true,
+ sameSite: 'lax',
+ httpOnly: true,
+ path: '/',
+};
+
+// EMPTY_SESSION's shape (packages/db/src/services/auth-session.service.ts) —
+// `TrpcContext.session` is never literally `null`, only its `userId` is.
+const EMPTY_SESSION = { session: null, user: null, userId: null };
+
+async function callerWith(session: unknown) {
+ const { ctx } = stubHttpCtx({}, session);
+ const trpcCtx = await makeTrpcContext(ctx, new Headers(), {
+ cookieOptions: COOKIE_OPTIONS,
+ });
+ return chatRouter.createCaller(trpcCtx);
+}
+
+const ORIGINAL_ENV = {
+ OPENAI_API_KEY: process.env.OPENAI_API_KEY,
+ ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY,
+};
+
+beforeEach(() => {
+ delete process.env.OPENAI_API_KEY;
+ delete process.env.ANTHROPIC_API_KEY;
+});
+
+afterEach(() => {
+ if (ORIGINAL_ENV.OPENAI_API_KEY === undefined) {
+ delete process.env.OPENAI_API_KEY;
+ } else {
+ process.env.OPENAI_API_KEY = ORIGINAL_ENV.OPENAI_API_KEY;
+ }
+ if (ORIGINAL_ENV.ANTHROPIC_API_KEY === undefined) {
+ delete process.env.ANTHROPIC_API_KEY;
+ } else {
+ process.env.ANTHROPIC_API_KEY = ORIGINAL_ENV.ANTHROPIC_API_KEY;
+ }
+});
+
+test('models rejects an unauthenticated caller before reading provider keys', async () => {
+ const caller = await callerWith(EMPTY_SESSION);
+ await expect(caller.models()).rejects.toMatchObject({
+ code: 'UNAUTHORIZED',
+ });
+});
+
+test('models returns no models and a null default with no provider keys set', async () => {
+ const caller = await callerWith(TEST_SESSION);
+ await expect(caller.models()).resolves.toEqual({
+ providers: { openai: false, anthropic: false },
+ models: [],
+ defaultModelId: null,
+ });
+});
+
+test('models filters to the configured provider and prefers the recorded default', async () => {
+ process.env.OPENAI_API_KEY = 'sk-test';
+ const caller = await callerWith(TEST_SESSION);
+ const result = await caller.models();
+ expect(result.providers).toEqual({ openai: true, anthropic: false });
+ expect(result.models.every((m) => m.group === 'OpenAI')).toBe(true);
+ expect(result.defaultModelId).toBe('gpt-4-1-mini');
+});
diff --git a/packages/core/src/modules/assistant/assistant.rpc.ts b/packages/core/src/modules/assistant/assistant.rpc.ts
new file mode 100644
index 000000000..ecca6f35e
--- /dev/null
+++ b/packages/core/src/modules/assistant/assistant.rpc.ts
@@ -0,0 +1,44 @@
+// Ported from packages/trpc/src/routers/chat.ts (M5-005).
+//
+// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware
+// stack — lands in core with auth (rpc/base.ts: "those need the resolved
+// Session shape and the access rules, so they land with auth (P6)"). Until
+// then this router does its own minimal "is anyone logged in" check inline,
+// exactly like V1's `enforceUserIsAuthed` (same as cohort.rpc.ts / gsc.rpc.ts
+// / import.rpc.ts). V1 keeps serving the live route through packages/trpc's
+// own `protectedProcedure` (full stack included), now sourcing the model
+// whitelist from `@openpanel/core` instead of `@openpanel/validation`
+// directly (DELEGATE PATTERN), so nothing here is a live regression.
+
+import { createTRPCRouter, procedure } from '../../rpc/base';
+import { TRPCAccessError } from '../../rpc/errors';
+import {
+ getAvailableChatModels,
+ PREFERRED_DEFAULT_MODEL_ID,
+} from './assistant.constants';
+
+function requireLogin(userId: string | null | undefined): string {
+ if (!userId) {
+ throw new TRPCAccessError('Not authenticated');
+ }
+ return userId;
+}
+
+export const chatRouter = createTRPCRouter({
+ models: procedure.query(({ ctx }) => {
+ requireLogin(ctx.session.userId);
+
+ const providers = {
+ openai: Boolean(process.env.OPENAI_API_KEY),
+ anthropic: Boolean(process.env.ANTHROPIC_API_KEY),
+ };
+ const models = getAvailableChatModels(providers);
+ const preferred = models.find((m) => m.id === PREFERRED_DEFAULT_MODEL_ID);
+ const defaultModelId = preferred?.id ?? models[0]?.id ?? null;
+ return {
+ providers,
+ models,
+ defaultModelId,
+ };
+ }),
+});
diff --git a/packages/core/src/modules/assistant/assistant.service.ts b/packages/core/src/modules/assistant/assistant.service.ts
new file mode 100644
index 000000000..4c96ab9f5
--- /dev/null
+++ b/packages/core/src/modules/assistant/assistant.service.ts
@@ -0,0 +1,20 @@
+// Moved from apps/api/src/agents/* (the Better Agent chat app + its tools,
+// prompt and Prisma persistence) and packages/trpc/src/agents/filter-command.ts
+// (M5-005, ADR-007's module map: assistant owns "S"). The bulk of the logic
+// lives under ./src — this file is the module's public entry point, the same
+// shape as insight.service.ts drawing from insight/src/*.
+//
+// V1 keeps running (DELEGATE PATTERN):
+// - apps/api/src/agents/app.ts and apps/api/src/agents/run-context.ts
+// become re-export shims of `chatApp`/`chatRunContext` below. The live
+// Fastify route (apps/api/src/app.ts) still mounts `chatApp` and wraps
+// the handler in `chatRunContext.run(...)` exactly as before.
+// - packages/trpc/src/routers/overview.ts's `runFilterCommand` procedure
+// now imports `runFilterCommand` from `@openpanel/core` instead of the
+// deleted `../agents/filter-command`.
+export type { ChatApp } from './src/app';
+export { chatApp } from './src/app';
+export type { FilterCommandResult } from './src/filter-command';
+export { runFilterCommand } from './src/filter-command';
+export type { ChatRunContext } from './src/run-context';
+export { chatRunContext } from './src/run-context';
diff --git a/packages/core/src/modules/assistant/src/app.ts b/packages/core/src/modules/assistant/src/app.ts
new file mode 100644
index 000000000..54e279328
--- /dev/null
+++ b/packages/core/src/modules/assistant/src/app.ts
@@ -0,0 +1,96 @@
+// Moved from apps/api/src/agents/app.ts (M5-005, ADR-007's module map:
+// assistant owns "S"). `apps/api/src/agents/app.ts` becomes a re-export shim
+// of `chatApp`/`ChatApp` (DELEGATE PATTERN) — the live Fastify route in
+// apps/api/src/app.ts keeps mounting it exactly as before.
+import { betterAgent, defineAgent } from '@better-agent/core';
+import {
+ ALLOWED_MODELS,
+ type ChatModelEntry,
+ openaiProvider,
+ resolveModel,
+} from '../../../clients/ai/providers';
+import { type ChatAgentContext, chatContextSchema } from './context';
+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/packages/core/src/modules/assistant/src/context.ts b/packages/core/src/modules/assistant/src/context.ts
new file mode 100644
index 000000000..26f62b127
--- /dev/null
+++ b/packages/core/src/modules/assistant/src/context.ts
@@ -0,0 +1,15 @@
+// Re-export the shared chat schemas from `../assistant.constants` so the
+// rest of the agent code can keep importing from `./context`. The schemas
+// themselves live in the module's constants file because the frontend needs
+// them too (isomorphic — see assistant.constants.ts's header).
+
+export type {
+ ChatAgentContext,
+ PageContext,
+ PageContextPage,
+} from '../assistant.constants';
+export {
+ chatContextSchema,
+ pageContextPageSchema,
+ pageContextSchema,
+} from '../assistant.constants';
diff --git a/packages/trpc/src/agents/filter-command.ts b/packages/core/src/modules/assistant/src/filter-command.ts
similarity index 97%
rename from packages/trpc/src/agents/filter-command.ts
rename to packages/core/src/modules/assistant/src/filter-command.ts
index f9606c86a..8ab471372 100644
--- a/packages/trpc/src/agents/filter-command.ts
+++ b/packages/core/src/modules/assistant/src/filter-command.ts
@@ -1,3 +1,7 @@
+// Moved from packages/trpc/src/agents/filter-command.ts (M5-005). V1's
+// packages/trpc/src/routers/overview.ts stays the LIVE `runFilterCommand`
+// tRPC procedure (DELEGATE PATTERN) and now imports this module's
+// `runFilterCommand` from @openpanel/core instead of a relative path.
import {
type AgentToolDefinition,
betterAgent,
@@ -6,7 +10,6 @@ import {
type ToolRunContext,
} from '@better-agent/core';
import { intervals, operators, timeWindows } from '@openpanel/constants';
-import { resolveModel } from '@openpanel/core';
import {
getDatesFromRange,
getTopPagesCore,
@@ -15,15 +18,18 @@ import {
resolveDateRange as resolveDateRangeCore,
} from '@openpanel/db';
import {
- CHAT_MODELS,
- type ChatModelEntry,
type IChartEventFilter,
type IChartRange,
objectToZodEnums,
- type PageContext,
zRange,
} from '@openpanel/validation';
import { z } from 'zod';
+import { resolveModel } from '../../../clients/ai/providers';
+import {
+ CHAT_MODELS,
+ type ChatModelEntry,
+ type PageContext,
+} from '../assistant.constants';
const operatorEnum = z.enum(objectToZodEnums(operators));
const rangeEnum = zRange;
diff --git a/apps/api/src/agents/persistence.ts b/packages/core/src/modules/assistant/src/persistence.ts
similarity index 82%
rename from apps/api/src/agents/persistence.ts
rename to packages/core/src/modules/assistant/src/persistence.ts
index ad5331b01..83931c7b9 100644
--- a/apps/api/src/agents/persistence.ts
+++ b/packages/core/src/modules/assistant/src/persistence.ts
@@ -1,8 +1,19 @@
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';
+// db access is LAZY, not a static top-level import — see
+// insight.service.ts's header for the full reasoning (jobs.registry.ts and
+// services.ts pull this module into the eager barrel chain nearly every core
+// test file reaches, and constructing @openpanel/db's clients at import time
+// would spawn a pino-pretty transport worker thread per test file — and, per
+// this module's own history, race @openpanel/db's other eager imports:
+// event-buffer.test.ts et al. saw `BotBuffer extends BaseBuffer` resolve to
+// `undefined` before this lazy load was added).
+function loadDb() {
+ return import('@openpanel/db/src/prisma-client').then((m) => m.db);
+}
+
/**
* Prisma-backed `ConversationStore` for Better Agent.
*
@@ -28,7 +39,9 @@ import { chatRunContext } from './run-context';
* invariant and don't check it explicitly.
*/
function roleOf(item: ConversationItem): string {
- if (item.type === 'message') return item.role;
+ if (item.type === 'message') {
+ return item.role;
+ }
return item.type;
}
@@ -47,13 +60,16 @@ function itemToRow(conversationId: string, item: ConversationItem) {
export const prismaConversationStore: ConversationStore = {
async load({ conversationId }) {
+ const db = await loadDb();
const conv = await db.conversation.findUnique({
where: { id: conversationId },
include: {
messages: { orderBy: { createdAt: 'asc' } },
},
});
- if (!conv) return null;
+ if (!conv) {
+ return null;
+ }
return {
items: conv.messages.map((m) => m.parts as unknown as ConversationItem),
@@ -65,10 +81,11 @@ export const prismaConversationStore: ConversationStore = {
const owner = chatRunContext.getStore();
if (!owner) {
throw new Error(
- 'chatRunContext missing during save — the Fastify wrapper must run first',
+ 'chatRunContext missing during save — the Fastify wrapper must run first'
);
}
+ const db = await loadDb();
await db.$transaction(async (tx) => {
await tx.conversation.upsert({
where: { id: conversationId },
diff --git a/apps/api/src/agents/prompt.ts b/packages/core/src/modules/assistant/src/prompt.ts
similarity index 98%
rename from apps/api/src/agents/prompt.ts
rename to packages/core/src/modules/assistant/src/prompt.ts
index 6f3b15f02..6a7037156 100644
--- a/apps/api/src/agents/prompt.ts
+++ b/packages/core/src/modules/assistant/src/prompt.ts
@@ -164,7 +164,9 @@ function buildPageContextSection(pc?: PageContext): string {
`Today is **${dayName}, ${todayIso}** (UTC).`,
];
- if (!pc) return lines.join('\n');
+ if (!pc) {
+ return lines.join('\n');
+ }
lines.push(`The user is on the **${pc.page}** page.`);
@@ -181,29 +183,29 @@ function buildPageContextSection(pc?: PageContext): string {
if (pc.filters?.eventNames && pc.filters.eventNames.length > 0) {
lines.push(
- `Active event-name filter: ${JSON.stringify(pc.filters.eventNames)}`,
+ `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)}`,
+ `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.`,
+ `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.`,
+ `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.`,
+ `They are viewing group \`${pc.ids.groupId}\`. Group-specific tools are pre-bound to this group.`
);
}
if (pc.ids?.reportId) {
@@ -212,13 +214,13 @@ function buildPageContextSection(pc?: PageContext): string {
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.`,
+ `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)}`,
+ `Quick context (no tool call needed): ${JSON.stringify(pc.primer)}`
);
}
diff --git a/packages/core/src/modules/assistant/src/report-runner.ts b/packages/core/src/modules/assistant/src/report-runner.ts
new file mode 100644
index 000000000..84bf1fe20
--- /dev/null
+++ b/packages/core/src/modules/assistant/src/report-runner.ts
@@ -0,0 +1,160 @@
+// Ported from packages/mcp/src/tools/analytics/reports.ts's `runReport` /
+// `runReportFromConfig` (M5-005).
+//
+// V1's apps/api/src/agents/tools/{base,report}.ts called these two functions
+// straight out of `@openpanel/mcp` — a working cross-package reuse, but one
+// core cannot inherit: `@openpanel/mcp` already depends on `@openpanel/core`
+// (its auth + session-manager modules), so core importing `@openpanel/mcp`
+// back would be a real package cycle (the same shape cohort.service.ts's
+// header documents for `@openpanel/queue`). ADR-007 also explicitly defers
+// unifying MCP's tool definitions with assistant's, so reaching into mcp is
+// not the fix either.
+//
+// The result is a second copy of this dispatch logic, which is exactly the
+// "four independent wrapper layers over the same 34 *Core functions"
+// TARGET_ARCHITECTURE already records as accepted technical debt — this
+// becomes a third layer, not a new problem. Both copies call the same
+// @openpanel/db primitives and must be kept in sync by hand until that debt
+// is paid down.
+import {
+ AggregateChartEngine,
+ ChartEngine,
+ funnelService,
+ getChartStartEndDate,
+ getReportById,
+ getSettingsForProject,
+} from '@openpanel/db';
+
+function reportUrl(
+ organizationId: string,
+ projectId: string,
+ reportId: string
+): string {
+ const base = (
+ process.env.DASHBOARD_URL ||
+ process.env.NEXT_PUBLIC_DASHBOARD_URL ||
+ 'https://dashboard.openpanel.dev'
+ ).replace(/\/$/, '');
+ return `${base}/${organizationId}/${projectId}/reports/${reportId}`;
+}
+
+/**
+ * Execute a saved report by ID. Dispatches on chart type:
+ * - funnel → funnelService.getFunnel
+ * - metric → AggregateChartEngine.execute
+ * - others → ChartEngine.execute
+ *
+ * Deliberately returns the raw engine output — the chat renderer needs the
+ * full chart, unlike MCP's copy which reshapes it for LLM consumption.
+ */
+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) {
+ return { error: 'Report not found', reportId: input.reportId };
+ }
+
+ if (report.projectId !== input.projectId) {
+ return {
+ error: 'Report does not belong to this project',
+ reportId: input.reportId,
+ };
+ }
+
+ const { timezone } = await getSettingsForProject(input.projectId);
+ const { startDate, endDate } = getChartStartEndDate(report, timezone);
+ const chartInput = { ...report, startDate, endDate, timezone };
+
+ 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 === '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) };
+}
+
+/**
+ * Execute an ad-hoc report config (no DB lookup — config is supplied
+ * directly). Used by the `generate_report` / `preview_report_with_changes`
+ * chat tools.
+ */
+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/core/src/modules/assistant/src/run-context.ts b/packages/core/src/modules/assistant/src/run-context.ts
new file mode 100644
index 000000000..8dd321602
--- /dev/null
+++ b/packages/core/src/modules/assistant/src/run-context.ts
@@ -0,0 +1,25 @@
+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
+ * - `resolveDateRange` / the prompt builder, to turn page-context
+ * range presets (`"6m"`, `"7d"`, …) into actual dates in the
+ * user's project timezone
+ *
+ * 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;
+ /** Project's configured timezone (IANA). Defaults to `UTC`. */
+ timezone: string;
+};
+
+export const chatRunContext = new AsyncLocalStorage<ChatRunContext>();
diff --git a/apps/api/src/agents/tools/base.ts b/packages/core/src/modules/assistant/src/tools/base.ts
similarity index 88%
rename from apps/api/src/agents/tools/base.ts
rename to packages/core/src/modules/assistant/src/tools/base.ts
index 22039d31e..8d2be174c 100644
--- a/apps/api/src/agents/tools/base.ts
+++ b/packages/core/src/modules/assistant/src/tools/base.ts
@@ -1,10 +1,4 @@
-import {
- chartTypes,
- lineTypes,
- operators,
-} from '@openpanel/constants';
-import { objectToZodEnums, zReportInput } from '@openpanel/validation';
-import { z } from 'zod';
+import { chartTypes, lineTypes, operators } from '@openpanel/constants';
import {
findProfilesCore,
getAnalyticsOverviewCore,
@@ -22,7 +16,9 @@ import {
queryEventsCore,
querySessionsCore,
} from '@openpanel/db';
-import { runReport, runReportFromConfig } from '@openpanel/mcp';
+import { objectToZodEnums, zReportInput } from '@openpanel/validation';
+import { z } from 'zod';
+import { runReport, runReportFromConfig } from '../report-runner';
import {
chatTool,
compactEventProperties,
@@ -46,7 +42,7 @@ export const listEventNames = chatTool(
async (_input, context) => {
const names = await listEventNamesCore(context.projectId);
return { event_names: names };
- },
+ }
);
export const listEventProperties = chatTool(
@@ -58,7 +54,9 @@ export const listEventProperties = chatTool(
eventName: z
.string()
.optional()
- .describe('Optional — filter to one event. Omit to list properties across all events.'),
+ .describe(
+ 'Optional — filter to one event. Omit to list properties across all events.'
+ ),
}),
},
async ({ eventName }, context) => {
@@ -67,7 +65,7 @@ export const listEventProperties = chatTool(
eventName,
});
return compactEventProperties(raw, { eventName });
- },
+ }
);
export const getEventPropertyValues = chatTool(
@@ -85,7 +83,7 @@ export const getEventPropertyValues = chatTool(
projectId: context.projectId,
eventName,
propertyKey,
- }),
+ })
);
// ─────────────────────────────────────────────────────────────────
@@ -106,9 +104,13 @@ export const listDashboards = chatTool(
});
return dashboards.map((d) => ({
...d,
- dashboard_url: dashboardUrl(context.organizationId, context.projectId, `/dashboards/${d.id}`),
+ dashboard_url: dashboardUrl(
+ context.organizationId,
+ context.projectId,
+ `/dashboards/${d.id}`
+ ),
}));
- },
+ }
);
export const listReports = chatTool(
@@ -117,7 +119,9 @@ export const listReports = chatTool(
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)'),
+ dashboardId: z
+ .string()
+ .describe('The dashboard ID (from list_dashboards)'),
}),
},
async ({ dashboardId }, context) =>
@@ -125,7 +129,7 @@ export const listReports = chatTool(
projectId: context.projectId,
dashboardId,
organizationId: context.organizationId,
- }),
+ })
);
export const getReportData = chatTool(
@@ -142,14 +146,14 @@ export const getReportData = chatTool(
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.",
+ '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.',
'',
@@ -163,7 +167,7 @@ export const generateReport = chatTool(
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.',
+ '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'])
@@ -175,7 +179,9 @@ export const generateReport = chatTool(
z.union([
z.object({
type: z.literal('event'),
- name: z.string().describe('Event name — verify with list_event_names'),
+ name: z
+ .string()
+ .describe('Event name — verify with list_event_names'),
displayName: z.string().optional(),
segment: z
.enum([
@@ -202,13 +208,13 @@ export const generateReport = chatTool(
'- `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'),
+ ].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`.',
+ 'Numeric property on the event to aggregate. Required when segment is `property_sum`/`average`/`max`/`min`. Example: `revenue`, `duration`, `score`.'
),
filters: z
.array(
@@ -216,17 +222,21 @@ export const generateReport = chatTool(
name: z
.string()
.describe(
- 'Field to filter on — verify with list_event_properties. Use the bare column name for top-level columns (e.g. `path`, `country`, `device`) or `properties.<key>` for custom JSON properties (e.g. `properties.plan`).',
+ 'Field to filter on — verify with list_event_properties. Use the bare column name for top-level columns (e.g. `path`, `country`, `device`) or `properties.<key>` for custom JSON properties (e.g. `properties.plan`).'
),
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` / `==`).',
+ '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.'),
- }),
+ .array(
+ z.union([z.string(), z.number(), z.boolean(), z.null()])
+ )
+ .describe(
+ 'Values to match. Use [] with isNull/isNotNull.'
+ ),
+ })
)
.default([])
.optional(),
@@ -236,25 +246,27 @@ export const generateReport = chatTool(
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, …',
+ '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.',
+ '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.'),
+ .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(),
@@ -265,26 +277,28 @@ export const generateReport = chatTool(
.enum(['sum', 'count', 'average', 'min', 'max'])
.optional()
.describe(
- 'How a series is aggregated for display. Only the metric and map chart types read this; `count` is unique profiles. Omit it unless the user asked for a specific aggregation — metric cards then default to unique profiles.',
+ 'How a series is aggregated for display. Only the metric and map chart types read this; `count` is unique profiles. Omit it unless the user asked for a specific aggregation — metric cards then default to unique profiles.'
),
previous: z
.boolean()
.optional()
.describe(
- 'Overlay the same-length previous period for comparison. Great for "vs last week" / "vs last month" questions.',
+ '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.',
+ '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.'),
+ .describe(
+ 'Top-N limit for bar/pie/sankey. Example: "top 10 pages" → limit: 10.'
+ ),
unit: z
.string()
.optional()
@@ -293,13 +307,13 @@ export const generateReport = chatTool(
.enum(['session', 'profile'])
.optional()
.describe(
- 'Only for `chartType: "funnel"`. Whether each funnel step counts by unique session or unique profile. Default is profile.',
+ '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.',
+ 'Short, descriptive card title (3-8 words) — e.g. "Signups per day, last 7 days". Always provide one.'
),
}),
},
@@ -343,14 +357,13 @@ export const generateReport = chatTool(
(b: { name: string }, i: number) => ({
id: String(i + 1),
name: b.name,
- }),
+ })
),
range: 'custom' as const,
// A metric card has always shown the total unique count, so an
// unspecified metric must stay `count` there — `sum` would silently turn
// "1.2k users" into "45k events".
- metric:
- input.metric ?? (input.chartType === 'metric' ? 'count' : 'sum'),
+ metric: input.metric ?? (input.chartType === 'metric' ? 'count' : 'sum'),
previous: input.previous ?? false,
...(input.lineType ? { lineType: input.lineType } : {}),
...(input.limit ? { limit: input.limit } : {}),
@@ -365,7 +378,8 @@ export const generateReport = chatTool(
const parsed = zReportInput.safeParse(config);
if (!parsed.success) {
return {
- error: 'Invalid report config — fix the issues and call generate_report again.',
+ 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,
@@ -376,7 +390,9 @@ export const generateReport = chatTool(
const chart = await runReportFromConfig({
organizationId: context.organizationId,
projectId: context.projectId,
- config: parsed.data as Parameters<typeof runReportFromConfig>[0]['config'],
+ config: parsed.data as Parameters<
+ typeof runReportFromConfig
+ >[0]['config'],
});
return {
// Use the model-supplied title when present; the frontend
@@ -384,15 +400,38 @@ export const generateReport = chatTool(
...(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',
+ '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;
// ─────────────────────────────────────────────────────────────────
@@ -403,11 +442,14 @@ 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.',
+ "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(),
+ interval: z
+ .enum(['hour', 'day', 'week', 'month'])
+ .default('day')
+ .optional(),
}),
},
async ({ startDate, endDate, interval }, context) => {
@@ -424,14 +466,14 @@ export const getAnalyticsOverview = chatTool(
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.',
+ "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(),
@@ -453,14 +495,14 @@ export const getTopPages = chatTool(
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.',
+ "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(),
@@ -481,18 +523,21 @@ export const getTopReferrers = chatTool(
projectId: context.projectId,
startDate: range.startDate,
endDate: range.endDate,
- column: (breakdown ?? 'referrer_name') as 'referrer_name' | 'referrer_type' | 'referrer',
+ 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.',
+ "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(),
@@ -517,14 +562,14 @@ export const getCountryBreakdown = chatTool(
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.',
+ "Visitor breakdown by device / browser / OS. Respects the page's active property filters.",
schema: z.object({
startDate: z.string().optional(),
endDate: z.string().optional(),
@@ -549,14 +594,14 @@ export const getDeviceBreakdown = chatTool(
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.",
+ '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.
@@ -568,7 +613,7 @@ export const getRollingActiveUsers = chatTool(
.string()
.optional()
.describe(
- 'Short, descriptive card title (3-8 words) — e.g. "Monthly active users trend". Always provide one.',
+ 'Short, descriptive card title (3-8 words) — e.g. "Monthly active users trend". Always provide one.'
),
}),
},
@@ -585,7 +630,13 @@ export const getRollingActiveUsers = chatTool(
.toISOString()
.slice(0, 10);
const label =
- window === 1 ? 'DAU' : window === 7 ? 'WAU' : window === 30 ? 'MAU' : `${window}-day active users`;
+ window === 1
+ ? 'DAU'
+ : window === 7
+ ? 'WAU'
+ : window === 30
+ ? 'MAU'
+ : `${window}-day active users`;
const config = {
chartType: 'linear' as const,
@@ -632,7 +683,7 @@ export const getRollingActiveUsers = chatTool(
// Keys the frontend report renderer knows about.
...chart,
};
- },
+ }
);
export const getFunnel = chatTool(
@@ -657,11 +708,14 @@ export const getFunnel = chatTool(
.string()
.optional()
.describe(
- 'Short, descriptive card title (3-8 words) — e.g. "Cart to checkout conversion" or "Signup to paid funnel". Always provide one.',
+ '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) => {
+ async (
+ { steps, startDate, endDate, windowHours, groupBy, title },
+ context
+ ) => {
const pageContext = context.pageContext;
const range = resolveDateRange({
...pageContext?.filters,
@@ -707,7 +761,9 @@ export const getFunnel = chatTool(
const chart = await runReportFromConfig({
organizationId: context.organizationId,
projectId: context.projectId,
- config: chartConfig as Parameters<typeof runReportFromConfig>[0]['config'],
+ config: chartConfig as Parameters<
+ typeof runReportFromConfig
+ >[0]['config'],
});
return {
@@ -716,7 +772,7 @@ export const getFunnel = chatTool(
// Keys the frontend report renderer knows about.
...chart,
};
- },
+ }
);
export const getRetentionCohort = chatTool(
@@ -726,7 +782,7 @@ export const getRetentionCohort = chatTool(
'Weekly active-user retention cohort for the last 12 weeks. Each row is a cohort (the week users were first seen) with cohort size (sum), retained user counts (values) and retained share (percentages) for subsequent weeks; a leading weighted-average row summarises all cohorts.',
schema: z.object({}),
},
- async (_input, context) => getRetentionCohortCore(context.projectId),
+ async (_input, context) => getRetentionCohortCore(context.projectId)
);
export const getUserFlow = chatTool(
@@ -736,17 +792,17 @@ export const getUserFlow = chatTool(
'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'),
+ 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) => {
+ async (
+ { startEvent, endEvent, mode, steps, startDate, endDate },
+ context
+ ) => {
const pageContext = context.pageContext;
const range = resolveDateRange({
...pageContext?.filters,
@@ -762,7 +818,7 @@ export const getUserFlow = chatTool(
startDate: range.startDate,
endDate: range.endDate,
});
- },
+ }
);
// ─────────────────────────────────────────────────────────────────
@@ -773,7 +829,7 @@ 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.',
+ "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(),
@@ -807,7 +863,7 @@ export const queryEvents = chatTool(
limit: input.limit ?? 20,
});
return truncateRows(rows, 100);
- },
+ }
);
export const querySessions = chatTool(
@@ -845,7 +901,7 @@ export const querySessions = chatTool(
limit: input.limit ?? 20,
});
return truncateRows(rows, 100);
- },
+ }
);
export const findProfiles = chatTool(
@@ -875,9 +931,13 @@ export const findProfiles = chatTool(
return truncateRows(
profiles.map((p) => ({
...p,
- dashboard_url: dashboardUrl(context.organizationId, context.projectId, `/profiles/${p.id}`),
+ dashboard_url: dashboardUrl(
+ context.organizationId,
+ context.projectId,
+ `/profiles/${p.id}`
+ ),
})),
- 100,
+ 100
);
- },
+ }
);
diff --git a/apps/api/src/agents/tools/dashboard.ts b/packages/core/src/modules/assistant/src/tools/dashboard.ts
similarity index 96%
rename from apps/api/src/agents/tools/dashboard.ts
rename to packages/core/src/modules/assistant/src/tools/dashboard.ts
index c140b2c51..0551dc420 100644
--- a/apps/api/src/agents/tools/dashboard.ts
+++ b/packages/core/src/modules/assistant/src/tools/dashboard.ts
@@ -49,12 +49,16 @@ export const summarizeDashboard = chatTool(
dashboard_url: dashboardUrl(
context.organizationId,
context.projectId,
- `/dashboards/${dashboard.id}`,
+ `/dashboards/${dashboard.id}`
),
};
if (allReports.length === 0) {
- return { dashboard: meta, reports: [], note: 'Dashboard has no reports.' };
+ return {
+ dashboard: meta,
+ reports: [],
+ note: 'Dashboard has no reports.',
+ };
}
const reports = allReports.slice(0, MAX_REPORTS_PER_SUMMARY);
@@ -96,7 +100,7 @@ export const summarizeDashboard = chatTool(
let data: unknown;
if (report.chartType === 'funnel') {
data = await funnelService.getFunnel(
- chartInput as Parameters<typeof funnelService.getFunnel>[0],
+ chartInput as Parameters<typeof funnelService.getFunnel>[0]
);
} else if (report.chartType === 'metric') {
data = await AggregateChartEngine.execute(chartInput);
@@ -121,7 +125,7 @@ export const summarizeDashboard = chatTool(
error: err instanceof Error ? err.message : String(err),
};
}
- }),
+ })
);
return {
@@ -134,5 +138,5 @@ export const summarizeDashboard = chatTool(
}
: {}),
};
- },
+ }
);
diff --git a/apps/api/src/agents/tools/events.ts b/packages/core/src/modules/assistant/src/tools/events.ts
similarity index 92%
rename from apps/api/src/agents/tools/events.ts
rename to packages/core/src/modules/assistant/src/tools/events.ts
index beacab5b5..b504ab396 100644
--- a/apps/api/src/agents/tools/events.ts
+++ b/packages/core/src/modules/assistant/src/tools/events.ts
@@ -1,9 +1,9 @@
-import { z } from 'zod';
import {
getEventPropertyValuesCore,
listEventPropertiesCore,
queryEventsCore,
} from '@openpanel/db';
+import { z } from 'zod';
import {
chatTool,
compactEventProperties,
@@ -43,8 +43,12 @@ export const analyzeEventDistribution = chatTool(
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);
+ 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) =>
@@ -59,7 +63,7 @@ export const analyzeEventDistribution = chatTool(
top_countries: top(byCountry, 10),
top_devices: top(byDevice, 10),
};
- },
+ }
);
export const correlateEvents = chatTool(
@@ -89,8 +93,12 @@ export const correlateEvents = chatTool(
// 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());
+ 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);
}
@@ -114,7 +122,7 @@ export const correlateEvents = chatTool(
sample_sessions: bySession.size,
top_pairs: pairs,
};
- },
+ }
);
export const getEventPropertyDistribution = chatTool(
@@ -134,7 +142,7 @@ export const getEventPropertyDistribution = chatTool(
propertyKey,
});
return truncateRows(result.values, 100);
- },
+ }
);
export const listPropertiesForEvent = chatTool(
@@ -152,5 +160,5 @@ export const listPropertiesForEvent = chatTool(
eventName,
});
return compactEventProperties(raw, { eventName });
- },
+ }
);
diff --git a/apps/api/src/agents/tools/groups.ts b/packages/core/src/modules/assistant/src/tools/groups.ts
similarity index 97%
rename from apps/api/src/agents/tools/groups.ts
rename to packages/core/src/modules/assistant/src/tools/groups.ts
index 2117428ab..9a1c21c7e 100644
--- a/apps/api/src/agents/tools/groups.ts
+++ b/packages/core/src/modules/assistant/src/tools/groups.ts
@@ -1,10 +1,10 @@
-import { z } from 'zod';
import {
findGroupsCore,
getGroupCore,
getGroupMemberProfiles,
queryEventsCore,
} from '@openpanel/db';
+import { z } from 'zod';
import { chatTool, dashboardUrl, truncateRows } from './helpers';
export const getGroupFull = chatTool(
@@ -45,14 +45,13 @@ export const getGroupFull = chatTool(
recent_events: recentEvents,
dashboard_url: orgPath(`/groups/${id}`),
};
- },
+ }
);
export const getGroupMembers = chatTool(
{
name: 'get_group_members',
- description:
- 'Paginated list of profiles in this group.',
+ 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(),
@@ -79,14 +78,13 @@ export const getGroupMembers = chatTool(
dashboard_url: orgPath(`/profiles/${p.id}`),
})),
};
- },
+ }
);
export const getGroupEvents = chatTool(
{
name: 'get_group_events',
- description:
- 'Recent events from members of this group.',
+ description: 'Recent events from members of this group.',
schema: z.object({
groupId: z.string().optional(),
eventNames: z.array(z.string()).optional(),
@@ -114,7 +112,7 @@ export const getGroupEvents = chatTool(
});
return truncateRows(events, 100);
- },
+ }
);
export const getGroupMetrics = chatTool(
@@ -157,7 +155,9 @@ export const getGroupMetrics = chatTool(
const activeIds30d = new Set<string>();
const sevenDaysAgo = Date.now() - 7 * 86_400_000;
for (const e of recentEvents) {
- if (!e.profile_id) continue;
+ if (!e.profile_id) {
+ continue;
+ }
activeIds30d.add(e.profile_id);
if (new Date(e.created_at).getTime() >= sevenDaysAgo) {
activeIds7d.add(e.profile_id);
@@ -170,7 +170,7 @@ export const getGroupMetrics = chatTool(
active_last_7_days: activeIds7d.size,
active_last_30_days: activeIds30d.size,
};
- },
+ }
);
export const compareGroups = chatTool(
@@ -219,5 +219,5 @@ export const compareGroups = chatTool(
name: g.name,
})),
};
- },
+ }
);
diff --git a/apps/api/src/agents/tools/helpers.ts b/packages/core/src/modules/assistant/src/tools/helpers.ts
similarity index 89%
rename from apps/api/src/agents/tools/helpers.ts
rename to packages/core/src/modules/assistant/src/tools/helpers.ts
index b27aacf68..c8be502b2 100644
--- a/apps/api/src/agents/tools/helpers.ts
+++ b/packages/core/src/modules/assistant/src/tools/helpers.ts
@@ -46,8 +46,8 @@ export function chatTool(
// biome-ignore lint/suspicious/noExplicitAny: deliberate, see comment above
input: any,
ctx: ChatAgentContext,
- runCtx: ToolRunContext,
- ) => Promise<unknown>,
+ runCtx: ToolRunContext
+ ) => Promise<unknown>
): AgentToolDefinition {
// biome-ignore lint/suspicious/noExplicitAny: see block comment above
const contract: any = defineTool({
@@ -55,30 +55,26 @@ export function chatTool(
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);
+ 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;
+ }
+ }) as AgentToolDefinition;
}
/**
@@ -87,7 +83,7 @@ export function chatTool(
*/
export function truncateRows<T>(
rows: T[],
- max = 500,
+ max = 500
): { rows: T[]; total: number; _truncated: boolean } {
if (rows.length <= max) {
return { rows, total: rows.length, _truncated: false };
@@ -127,7 +123,7 @@ export function compactEventProperties(
columns: readonly string[];
properties: Array<{ property_key: string; event_name: string }>;
},
- options: { eventName?: string; max?: number } = {},
+ options: { eventName?: string; max?: number } = {}
): {
event_name?: string;
columns: readonly string[];
@@ -220,13 +216,15 @@ export function resolveDateRange(filters?: PageContext['filters']): {
* numbers that contradict the dashboard.
*/
export function pageContextFilters(
- pageContext: ChatAgentContext['pageContext'],
+ pageContext: ChatAgentContext['pageContext']
): IChartEventFilter[] {
const raw = pageContext?.filters?.eventFilters;
- if (!Array.isArray(raw)) return [];
+ if (!Array.isArray(raw)) {
+ return [];
+ }
return raw.filter(
(f): f is IChartEventFilter =>
- typeof (f as { name?: unknown })?.name === 'string',
+ typeof (f as { name?: unknown })?.name === 'string'
);
}
@@ -249,7 +247,7 @@ export function previousPeriod(startDate: string, endDate: string) {
export function dashboardUrl(
organizationId: string,
projectId: string,
- path = '',
+ path = ''
): string {
const base =
process.env.DASHBOARD_URL ||
diff --git a/apps/api/src/agents/tools/index.ts b/packages/core/src/modules/assistant/src/tools/index.ts
similarity index 100%
rename from apps/api/src/agents/tools/index.ts
rename to packages/core/src/modules/assistant/src/tools/index.ts
diff --git a/apps/api/src/agents/tools/insights.ts b/packages/core/src/modules/assistant/src/tools/insights.ts
similarity index 90%
rename from apps/api/src/agents/tools/insights.ts
rename to packages/core/src/modules/assistant/src/tools/insights.ts
index 429664f98..f1c8acb20 100644
--- a/apps/api/src/agents/tools/insights.ts
+++ b/packages/core/src/modules/assistant/src/tools/insights.ts
@@ -1,5 +1,5 @@
-import { z } from 'zod';
import { db } from '@openpanel/db';
+import { z } from 'zod';
import { chatTool, truncateRows } from './helpers';
export const listInsights = chatTool(
@@ -12,10 +12,10 @@ export const listInsights = chatTool(
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(),
+ .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(),
}),
},
@@ -48,9 +48,9 @@ export const listInsights = chatTool(
// but the table won't pick it as the label column.
id: i.id,
})),
- 100,
+ 100
);
- },
+ }
);
export const explainInsight = chatTool(
@@ -75,7 +75,7 @@ export const explainInsight = chatTool(
take: 20,
});
return { insight, events };
- },
+ }
);
export const findRelatedInsights = chatTool(
@@ -109,9 +109,13 @@ export const findRelatedInsights = chatTool(
take: limit ?? 10,
});
return {
- source_insight: { id: insight.id, moduleKey: insight.moduleKey, dimensionKey: insight.dimensionKey },
+ 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/packages/core/src/modules/assistant/src/tools/pages.ts
similarity index 90%
rename from apps/api/src/agents/tools/pages.ts
rename to packages/core/src/modules/assistant/src/tools/pages.ts
index a523efe3f..8fc1d5ce9 100644
--- a/apps/api/src/agents/tools/pages.ts
+++ b/packages/core/src/modules/assistant/src/tools/pages.ts
@@ -1,11 +1,16 @@
-import { z } from 'zod';
import {
getEntryExitPagesCore,
getPageConversionsCore,
getPagePerformanceCore,
getTopPagesCore,
} from '@openpanel/db';
-import { chatTool, previousPeriod, resolveDateRange, truncateRows } from './helpers';
+import { z } from 'zod';
+import {
+ chatTool,
+ previousPeriod,
+ resolveDateRange,
+ truncateRows,
+} from './helpers';
export const getPagePerformance = chatTool(
{
@@ -39,7 +44,7 @@ export const getPagePerformance = chatTool(
sortOrder: input.sortOrder,
limit: input.limit ?? 50,
});
- },
+ }
);
export const getPageConversions = chatTool(
@@ -72,7 +77,7 @@ export const getPageConversions = chatTool(
limit: input.limit ?? 50,
});
return truncateRows(rows, 100);
- },
+ }
);
export const getEntryExitPages = chatTool(
@@ -99,7 +104,7 @@ export const getEntryExitPages = chatTool(
mode,
});
return truncateRows(rows, 50);
- },
+ }
);
export const findDecliningPages = chatTool(
@@ -115,7 +120,9 @@ export const findDecliningPages = chatTool(
.min(1)
.default(50)
.optional()
- .describe('Filter out pages with fewer than N pageviews in the previous period'),
+ .describe(
+ 'Filter out pages with fewer than N pageviews in the previous period'
+ ),
}),
},
async (input, context) => {
@@ -146,10 +153,17 @@ export const findDecliningPages = chatTool(
(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 }>)
+ 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);
@@ -158,11 +172,17 @@ export const findDecliningPages = chatTool(
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)) };
+ 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/packages/core/src/modules/assistant/src/tools/profile.ts
similarity index 84%
rename from apps/api/src/agents/tools/profile.ts
rename to packages/core/src/modules/assistant/src/tools/profile.ts
index 2c4478bbd..c43703247 100644
--- a/apps/api/src/agents/tools/profile.ts
+++ b/packages/core/src/modules/assistant/src/tools/profile.ts
@@ -1,4 +1,3 @@
-import { z } from 'zod';
import {
findProfilesCore,
getProfileById,
@@ -7,6 +6,7 @@ import {
getProfileWithEvents,
queryEventsCore,
} from '@openpanel/db';
+import { z } from 'zod';
import { chatTool, dashboardUrl, truncateRows } from './helpers';
export const getProfileFull = chatTool(
@@ -27,9 +27,10 @@ export const getProfileFull = chatTool(
getProfileById(id, context.projectId),
getProfileWithEvents(context.projectId, id, 10),
getProfileSessionsCore(context.projectId, id, 5),
- getProfileMetricsCore({ projectId: context.projectId, profileId: id }).catch(
- () => null,
- ),
+ getProfileMetricsCore({
+ projectId: context.projectId,
+ profileId: id,
+ }).catch(() => null),
]);
if (!profile) {
return { error: 'Profile not found', profileId: id };
@@ -39,16 +40,20 @@ export const getProfileFull = chatTool(
metrics,
recent_sessions: sessions,
recent_events: withEvents.recent_events,
- dashboard_url: dashboardUrl(context.organizationId, context.projectId, `/profiles/${id}`),
+ 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.',
+ "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
@@ -68,14 +73,13 @@ export const getProfileEvents = chatTool(
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.',
+ 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(),
@@ -85,16 +89,20 @@ export const getProfileSessions = chatTool(
const sessions = await getProfileSessionsCore(
context.projectId,
profileId || context.pageContext?.ids?.profileId || '',
- limit ?? 20,
+ limit ?? 20
);
return truncateRows(
sessions.map((s) => ({
...s,
- dashboard_url: dashboardUrl(context.organizationId, context.projectId, `/sessions/${s.id}`),
+ dashboard_url: dashboardUrl(
+ context.organizationId,
+ context.projectId,
+ `/sessions/${s.id}`
+ ),
})),
- 100,
+ 100
);
- },
+ }
);
export const getProfileMetrics = chatTool(
@@ -110,7 +118,7 @@ export const getProfileMetrics = chatTool(
getProfileMetricsCore({
projectId: context.projectId,
profileId: profileId || context.pageContext?.ids?.profileId || '',
- }),
+ })
);
export const getProfileJourney = chatTool(
@@ -134,9 +142,10 @@ export const getProfileJourney = chatTool(
limit: maxEvents ?? 50,
}),
getProfileSessionsCore(context.projectId, id, 20),
- getProfileMetricsCore({ projectId: context.projectId, profileId: id }).catch(
- () => null,
- ),
+ getProfileMetricsCore({
+ projectId: context.projectId,
+ profileId: id,
+ }).catch(() => null),
]);
if (!profile) {
@@ -151,7 +160,8 @@ export const getProfileJourney = chatTool(
return {
profile_id: id,
- first_seen: metrics?.firstSeen ?? sessions[sessions.length - 1]?.created_at ?? null,
+ 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,
@@ -172,9 +182,13 @@ export const getProfileJourney = chatTool(
path: e.path,
created_at: e.created_at,
})),
- dashboard_url: dashboardUrl(context.organizationId, context.projectId, `/profiles/${id}`),
+ dashboard_url: dashboardUrl(
+ context.organizationId,
+ context.projectId,
+ `/profiles/${id}`
+ ),
};
- },
+ }
);
export const getProfileGroups = chatTool(
@@ -197,7 +211,7 @@ export const getProfileGroups = chatTool(
group_count: (profile.groups ?? []).length,
groups: profile.groups ?? [],
};
- },
+ }
);
export const compareProfileToAverage = chatTool(
@@ -214,9 +228,10 @@ export const compareProfileToAverage = chatTool(
// 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,
- ),
+ getProfileMetricsCore({
+ projectId: context.projectId,
+ profileId: id,
+ }).catch(() => null),
findProfilesCore({ projectId: context.projectId, limit: 100 }),
]);
@@ -235,13 +250,14 @@ export const compareProfileToAverage = chatTool(
const sampleMetrics = await Promise.all(
sampleIds.map((sid) =>
- getProfileMetricsCore({ projectId: context.projectId, profileId: sid }).catch(
- () => null,
- ),
- ),
+ getProfileMetricsCore({
+ projectId: context.projectId,
+ profileId: sid,
+ }).catch(() => null)
+ )
);
const valid = sampleMetrics.filter(
- (m): m is NonNullable<typeof m> => m != null,
+ (m): m is NonNullable<typeof m> => m != null
);
if (valid.length === 0) {
@@ -252,7 +268,7 @@ export const compareProfileToAverage = chatTool(
};
}
- const avg = (sel: (m: typeof valid[number]) => number) =>
+ const avg = (sel: (m: (typeof valid)[number]) => number) =>
valid.reduce((s, m) => s + sel(m), 0) / valid.length;
const project_avg = {
@@ -264,8 +280,13 @@ export const compareProfileToAverage = chatTool(
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 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)),
@@ -282,12 +303,12 @@ export const compareProfileToAverage = chatTool(
screenViews: ratio(thisMetrics.screenViews, project_avg.screenViews),
avgSessionDurationMin: ratio(
thisMetrics.avgSessionDurationMin,
- project_avg.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/packages/core/src/modules/assistant/src/tools/references.ts
similarity index 97%
rename from apps/api/src/agents/tools/references.ts
rename to packages/core/src/modules/assistant/src/tools/references.ts
index 6e580ad8d..6a68c9fa5 100644
--- a/apps/api/src/agents/tools/references.ts
+++ b/packages/core/src/modules/assistant/src/tools/references.ts
@@ -77,9 +77,9 @@ export const listReferences = chatTool(
description: r.description ?? '',
id: r.id,
})),
- 100,
+ 100
);
- },
+ }
);
export const getReferencesAround = chatTool(
@@ -88,9 +88,7 @@ export const getReferencesAround = chatTool(
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.'),
+ 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(),
}),
@@ -126,5 +124,5 @@ export const getReferencesAround = chatTool(
id: r.id,
})),
};
- },
+ }
);
diff --git a/apps/api/src/agents/tools/report.ts b/packages/core/src/modules/assistant/src/tools/report.ts
similarity index 93%
rename from apps/api/src/agents/tools/report.ts
rename to packages/core/src/modules/assistant/src/tools/report.ts
index f94b0f5e6..889b1d622 100644
--- a/apps/api/src/agents/tools/report.ts
+++ b/packages/core/src/modules/assistant/src/tools/report.ts
@@ -1,7 +1,7 @@
-import { z } from 'zod';
import { listEventPropertiesCore } from '@openpanel/db';
-import { runReportFromConfig } from '@openpanel/mcp';
import type { IReportInput } from '@openpanel/validation';
+import { z } from 'zod';
+import { runReportFromConfig } from '../report-runner';
import { chatTool, previousPeriod, resolveDateRange } from './helpers';
export const previewReportWithChanges = chatTool(
@@ -56,17 +56,18 @@ export const previewReportWithChanges = chatTool(
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.addBreakdown &&
+ !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,
+ (b) => b.name !== input.removeBreakdown
);
}
if (input.addEventFilter) {
@@ -90,9 +91,11 @@ export const previewReportWithChanges = chatTool(
return runReportFromConfig({
organizationId: context.organizationId,
projectId: context.projectId,
- config: next as unknown as Parameters<typeof runReportFromConfig>[0]['config'],
+ config: next as unknown as Parameters<
+ typeof runReportFromConfig
+ >[0]['config'],
});
- },
+ }
);
export const suggestBreakdowns = chatTool(
@@ -121,8 +124,8 @@ export const suggestBreakdowns = chatTool(
listEventPropertiesCore({
projectId: context.projectId,
eventName: name,
- }),
- ),
+ })
+ )
);
// Aggregate property keys across events
@@ -146,7 +149,7 @@ export const suggestBreakdowns = chatTool(
existing_breakdowns: Array.from(used),
suggestions,
};
- },
+ }
);
export const compareToPreviousPeriod = chatTool(
@@ -192,7 +195,7 @@ export const compareToPreviousPeriod = chatTool(
]);
return { current, previous };
- },
+ }
);
export const findAnomaliesInCurrentReport = chatTool(
@@ -240,15 +243,22 @@ export const findAnomaliesInCurrentReport = chatTool(
}
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 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;
+ 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 };
+ 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);
@@ -258,7 +268,7 @@ export const findAnomaliesInCurrentReport = chatTool(
point_count: points.length,
anomalies,
};
- },
+ }
);
export const explainFilterImpact = chatTool(
@@ -311,5 +321,5 @@ export const explainFilterImpact = chatTool(
with_filters: filtered,
without_filters: unfiltered,
};
- },
+ }
);
diff --git a/apps/api/src/agents/tools/seo.ts b/packages/core/src/modules/assistant/src/tools/seo.ts
similarity index 99%
rename from apps/api/src/agents/tools/seo.ts
rename to packages/core/src/modules/assistant/src/tools/seo.ts
index 05beff9fa..a8fb5ded5 100644
--- a/apps/api/src/agents/tools/seo.ts
+++ b/packages/core/src/modules/assistant/src/tools/seo.ts
@@ -1,4 +1,3 @@
-import { z } from 'zod';
import {
getTopPagesCore,
gscGetCannibalizationCore,
@@ -9,6 +8,7 @@ import {
gscGetTopPagesCore,
gscGetTopQueriesCore,
} from '@openpanel/db';
+import { z } from 'zod';
import { chatTool, resolveDateRange, truncateRows } from './helpers';
export const gscGetOverview = chatTool(
@@ -34,7 +34,7 @@ export const gscGetOverview = chatTool(
endDate: range.endDate,
interval,
});
- },
+ }
);
export const gscGetTopQueries = chatTool(
@@ -61,7 +61,7 @@ export const gscGetTopQueries = chatTool(
limit: limit ?? 50,
});
return truncateRows(rows, 100);
- },
+ }
);
export const gscGetTopPages = chatTool(
@@ -88,7 +88,7 @@ export const gscGetTopPages = chatTool(
limit: limit ?? 50,
});
return truncateRows(rows, 100);
- },
+ }
);
export const gscGetQueryDetails = chatTool(
@@ -114,7 +114,7 @@ export const gscGetQueryDetails = chatTool(
endDate: range.endDate,
query,
});
- },
+ }
);
export const gscGetPageDetails = chatTool(
@@ -140,7 +140,7 @@ export const gscGetPageDetails = chatTool(
endDate: range.endDate,
page,
});
- },
+ }
);
export const gscGetQueryOpportunities = chatTool(
@@ -166,7 +166,7 @@ export const gscGetQueryOpportunities = chatTool(
endDate: range.endDate,
minImpressions,
});
- },
+ }
);
export const gscGetCannibalization = chatTool(
@@ -190,7 +190,7 @@ export const gscGetCannibalization = chatTool(
startDate: range.startDate,
endDate: range.endDate,
});
- },
+ }
);
export const correlateSeoWithTraffic = chatTool(
@@ -272,5 +272,5 @@ export const correlateSeoWithTraffic = chatTool(
.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/packages/core/src/modules/assistant/src/tools/session.ts
similarity index 87%
rename from apps/api/src/agents/tools/session.ts
rename to packages/core/src/modules/assistant/src/tools/session.ts
index d4670d72e..3dff771bd 100644
--- a/apps/api/src/agents/tools/session.ts
+++ b/packages/core/src/modules/assistant/src/tools/session.ts
@@ -1,9 +1,9 @@
-import { z } from 'zod';
import {
queryEventsCore,
querySessionsCore,
sessionService,
} from '@openpanel/db';
+import { z } from 'zod';
import { chatTool, dashboardUrl, truncateRows } from './helpers';
export const getSessionFull = chatTool(
@@ -36,16 +36,19 @@ export const getSessionFull = chatTool(
path_length: screenViews.length,
path: screenViews,
events: events.slice(0, 50),
- dashboard_url: dashboardUrl(context.organizationId, context.projectId, `/sessions/${id}`),
+ 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.',
+ description: 'The chronological list of pages visited in this session.',
schema: z.object({
sessionId: z.string().optional(),
}),
@@ -66,7 +69,7 @@ export const getSessionPath = chatTool(
created_at: e.created_at,
}));
return { sessionId: id, page_count: path.length, path };
- },
+ }
);
export const getSessionEvents = chatTool(
@@ -88,7 +91,7 @@ export const getSessionEvents = chatTool(
limit: 100,
});
return truncateRows(events, 100);
- },
+ }
);
export const getSimilarSessions = chatTool(
@@ -123,17 +126,21 @@ export const getSimilarSessions = chatTool(
},
similar_sessions: filtered.map((s) => ({
...s,
- dashboard_url: dashboardUrl(context.organizationId, context.projectId, `/sessions/${s.id}`),
+ 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.',
+ "Compare this session's duration / event count / screen views against the project averages. Helps spot outliers.",
schema: z.object({
sessionId: z.string().optional(),
}),
@@ -151,7 +158,7 @@ export const compareSessionToTypical = chatTool(
return { session, comparison: null };
}
- const avg = (sel: (s: typeof sample[number]) => number) =>
+ const avg = (sel: (s: (typeof sample)[number]) => number) =>
sample.reduce((s, sess) => s + sel(sess), 0) / sample.length;
const project_avg = {
@@ -161,11 +168,18 @@ export const compareSessionToTypical = chatTool(
};
const ratio = (a: number, b: number) => {
- if (b === 0) return { ratio: 0, label: 'equal' as const };
+ 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),
+ label:
+ r > 1.05
+ ? ('above' as const)
+ : r < 0.95
+ ? ('below' as const)
+ : ('equal' as const),
};
};
@@ -183,12 +197,12 @@ export const compareSessionToTypical = chatTool(
event_count: ratio(session.eventCount, project_avg.event_count),
screen_view_count: ratio(
session.screenViewCount,
- project_avg.screen_view_count,
+ project_avg.screen_view_count
),
},
sample_size: sample.length,
};
- },
+ }
);
export const getSessionReferrerContext = chatTool(
@@ -204,7 +218,7 @@ export const getSessionReferrerContext = chatTool(
const id = sessionId || context.pageContext?.ids?.sessionId || '';
const session = await sessionService.byId(id, context.projectId);
- if (!session.referrer && !session.referrerName) {
+ if (!(session.referrer || session.referrerName)) {
return {
session_id: id,
referrer: null,
@@ -232,7 +246,7 @@ export const getSessionReferrerContext = chatTool(
entry_path: s.entry_path,
})),
};
- },
+ }
);
export const getSessionReplaySummary = chatTool(
@@ -251,8 +265,12 @@ export const getSessionReplaySummary = chatTool(
session_id: id,
available: session.hasReplay ?? false,
replay_url: session.hasReplay
- ? dashboardUrl(context.organizationId, context.projectId, `/sessions/${id}`)
+ ? dashboardUrl(
+ context.organizationId,
+ context.projectId,
+ `/sessions/${id}`
+ )
: null,
};
- },
+ }
);
diff --git a/apps/api/src/agents/tools/ui.ts b/packages/core/src/modules/assistant/src/tools/ui.ts
similarity index 96%
rename from apps/api/src/agents/tools/ui.ts
rename to packages/core/src/modules/assistant/src/tools/ui.ts
index 38ed3cc20..dcdb11777 100644
--- a/apps/api/src/agents/tools/ui.ts
+++ b/packages/core/src/modules/assistant/src/tools/ui.ts
@@ -3,7 +3,7 @@ import {
applyFiltersSchema,
setEventNamesFilterSchema,
setPropertyFiltersSchema,
-} from '@openpanel/validation';
+} from '../../assistant.constants';
/**
* Client-side UI-mutator tools.
@@ -11,7 +11,7 @@ import {
* 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
+ * are imported from `assistant.constants.ts` so the frontend handler
* types stay in sync with what the LLM calls.
*/
diff --git a/packages/core/src/rest.routes.ts b/packages/core/src/rest.routes.ts
index 6e16e343f..4b1ec6960 100644
--- a/packages/core/src/rest.routes.ts
+++ b/packages/core/src/rest.routes.ts
@@ -8,6 +8,7 @@ import { openapi } from '@elysiajs/openapi';
import { Elysia } from 'elysia';
import type { AppDeps } from './context';
import { registry } from './metrics';
+import { assistantRoutes } from './modules/assistant/assistant.routes';
import { gscRoutes } from './modules/gsc/gsc.routes';
import { healthRoutes } from './modules/health/health.routes';
import { importRoutes } from './modules/import/import.routes';
@@ -33,12 +34,14 @@ const OPENAPI_EXCLUDED_PATHS = ['/metrics'];
export const publicApiRoutes = (deps: AppDeps) =>
new Elysia({ name: 'core/public-api-routes' }).use(importRoutes(deps));
-// gsc's callback is the first module to land here (M5-002). It is not yet
-// reachable in production: main.ts only mounts `dashboardRoutes` once a real
-// `AppDeps` exists (P3/P4/P8) — see gsc.routes.ts's header for the named gap
-// that keeps it inert until then.
+// gsc's callback was the first module to land here (M5-002); assistant's
+// `/ai/agents/*` (M5-005) joined it. Neither is reachable in production yet:
+// main.ts only mounts `dashboardRoutes` once a real `AppDeps` exists
+// (P3/P4/P8) — see each module's own routes.ts header for its named gap.
export const dashboardRoutes = (deps: AppDeps) =>
- new Elysia({ name: 'core/dashboard-routes' }).use(gscRoutes(deps));
+ new Elysia({ name: 'core/dashboard-routes' })
+ .use(gscRoutes(deps))
+ .use(assistantRoutes(deps));
// healthz/metrics/misc share V1's ops surface (http/context.ts's
// UNLOGGED_PATH_PREFIXES) — unauthenticated, uncorsed, unlogged. /metrics and
diff --git a/packages/core/src/rpc.router.ts b/packages/core/src/rpc.router.ts
index d45ede326..35d37a036 100644
--- a/packages/core/src/rpc.router.ts
+++ b/packages/core/src/rpc.router.ts
@@ -4,6 +4,7 @@
// (ADR-007 decision 19). Only `health` exists so far; the 28 real routers
// land with their module waves (P5-P8).
+import { chatRouter } from './modules/assistant/assistant.rpc';
import { cohortRouter } from './modules/cohort/cohort.rpc';
import { gscRouter } from './modules/gsc/gsc.rpc';
import { healthRouter } from './modules/health/health.rpc';
@@ -17,6 +18,7 @@ export const appRouter = createTRPCRouter({
gsc: gscRouter,
cohort: cohortRouter,
import: importRouter,
+ chat: chatRouter,
});
export type AppRouter = typeof appRouter;
diff --git a/packages/db/src/types.ts b/packages/db/src/types.ts
index 69b4cde77..e8d4e2289 100644
--- a/packages/db/src/types.ts
+++ b/packages/db/src/types.ts
@@ -33,7 +33,7 @@ declare global {
// (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.
+ // in packages/core/src/modules/assistant/src/persistence.ts.
type IPrismaUIMessageParts = unknown[];
type IPrismaSubscriptionStatus =
| 'incomplete'
diff --git a/packages/mcp/src/tools/analytics/property-values.ts b/packages/mcp/src/tools/analytics/property-values.ts
index 6fa8f2143..021119aad 100644
--- a/packages/mcp/src/tools/analytics/property-values.ts
+++ b/packages/mcp/src/tools/analytics/property-values.ts
@@ -25,8 +25,9 @@ const MAX_VALUE_LIMIT = 500;
* rows into a few dozen useful ones.
*
* The in-app chat agent solves the same problem in
- * `apps/api/src/agents/tools/helpers.ts`; kept as a local copy rather than a
- * shared abstraction since the two consumers may want to diverge.
+ * `packages/core/src/modules/assistant/src/tools/helpers.ts`; kept as a local
+ * copy rather than a shared abstraction since the two consumers may want to
+ * diverge.
*/
function compactPropertyKeys(
rows: Array<{ property_key: string }>,
diff --git a/packages/mcp/src/tools/analytics/reports.ts b/packages/mcp/src/tools/analytics/reports.ts
index 3b23238b6..c718bda1c 100644
--- a/packages/mcp/src/tools/analytics/reports.ts
+++ b/packages/mcp/src/tools/analytics/reports.ts
@@ -1,3 +1,4 @@
+import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import {
AggregateChartEngine,
ChartEngine,
@@ -6,8 +7,8 @@ import {
getChartStartEndDate,
getReportById,
getReportsByDashboardId,
- getSettingsForProject} from '@openpanel/db';
-import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+ getSettingsForProject,
+} from '@openpanel/db';
import { z } from 'zod';
import type { McpAuthContext } from '../../auth';
import { dashboardBaseUrl } from '../dashboard-links';
@@ -26,18 +27,32 @@ const DEFAULT_PLOTTED_SERIES = 5;
const MAX_PLOTTED_SERIES = 25;
const MAX_DATA_POINTS = 180;
-function reportUrl(organizationId: string, projectId: string, reportId: string) {
+function reportUrl(
+ organizationId: string,
+ projectId: string,
+ reportId: string
+) {
return `${dashboardBaseUrl()}/${organizationId}/${projectId}/reports/${reportId}`;
}
-function dashboardUrl(organizationId: string, projectId: string, dashboardId: string) {
+function dashboardUrl(
+ organizationId: string,
+ projectId: string,
+ dashboardId: string
+) {
return `${dashboardBaseUrl()}/${organizationId}/${projectId}/dashboards/${dashboardId}`;
}
type ChartSeries = {
id: string;
names: string[];
- metrics: { sum: number; average: number; min: number; max: number; count?: number };
+ metrics: {
+ sum: number;
+ average: number;
+ min: number;
+ max: number;
+ count?: number;
+ };
data: Array<{ date: string; count: number }>;
};
@@ -55,7 +70,7 @@ type ChartSeries = {
*/
function shapeChart(
chart: { series: ChartSeries[]; metrics: unknown },
- options: { seriesLimit: number; plotSeries: number },
+ options: { seriesLimit: number; plotSeries: number }
) {
const { seriesLimit, plotSeries } = options;
const summaries = chart.series.map((serie) => ({
@@ -74,7 +89,9 @@ function shapeChart(
const seenDates = new Set<string>();
for (const serie of plotted) {
for (const point of serie.data) {
- if (seenDates.has(point.date)) continue;
+ if (seenDates.has(point.date)) {
+ continue;
+ }
seenDates.add(point.date);
dates.push(point.date);
}
@@ -82,10 +99,14 @@ function shapeChart(
dates.sort();
const trimmedDates =
- dates.length > MAX_DATA_POINTS ? dates.slice(dates.length - MAX_DATA_POINTS) : dates;
+ dates.length > MAX_DATA_POINTS
+ ? dates.slice(dates.length - MAX_DATA_POINTS)
+ : dates;
const byDate = plotted.map((serie) => {
- const lookup = new Map(serie.data.map((point) => [point.date, point.count]));
+ const lookup = new Map(
+ serie.data.map((point) => [point.date, point.count])
+ );
return lookup;
});
@@ -104,7 +125,8 @@ function shapeChart(
date,
...byDate.map((lookup) => lookup.get(date) ?? 0),
]),
- ...(chart.series.length > plotted.length || dates.length > trimmedDates.length
+ ...(chart.series.length > plotted.length ||
+ dates.length > trimmedDates.length
? {
note: [
chart.series.length > plotted.length
@@ -124,7 +146,7 @@ function shapeChart(
export function registerReportTools(
server: McpServer,
- context: McpAuthContext,
+ context: McpAuthContext
) {
server.tool(
'list_dashboards',
@@ -144,7 +166,7 @@ export function registerReportTools(
...d,
dashboard_url: dashboardUrl(context.organizationId, projectId, d.id),
}));
- }),
+ })
);
server.tool(
@@ -177,7 +199,7 @@ export function registerReportTools(
name: s.name,
displayName: s.displayName,
segment: s.segment,
- },
+ }
),
breakdowns: r.breakdowns,
}));
@@ -185,11 +207,20 @@ export function registerReportTools(
report_url_template: `${dashboardBaseUrl()}/${context.organizationId}/${projectId}/reports/{id}`,
...table(rows, {
limit: MAX_SERIES_LIMIT,
- columns: ['id', 'name', 'chartType', 'range', 'interval', 'metric', 'series', 'breakdowns'],
+ columns: [
+ 'id',
+ 'name',
+ 'chartType',
+ 'range',
+ 'interval',
+ 'metric',
+ 'series',
+ 'breakdowns',
+ ],
unit: 'reports',
}),
};
- }),
+ })
);
server.tool(
@@ -206,7 +237,7 @@ export function registerReportTools(
.max(MAX_PLOTTED_SERIES)
.optional()
.describe(
- `How many of the top series get per-date values in the \`data\` block (default ${DEFAULT_PLOTTED_SERIES}, max ${MAX_PLOTTED_SERIES}). Every series appears in the summary table regardless.`,
+ `How many of the top series get per-date values in the \`data\` block (default ${DEFAULT_PLOTTED_SERIES}, max ${MAX_PLOTTED_SERIES}). Every series appears in the summary table regardless.`
),
},
async ({ projectId: inputProjectId, reportId, seriesLimit, plotSeries }) =>
@@ -224,8 +255,15 @@ export function registerReportTools(
// Funnel and metric results are already small and have their own shape;
// only the multi-series charts need reshaping.
- const chart = result.data as { series?: ChartSeries[]; metrics?: unknown };
- if (result.chartType === 'funnel' || result.chartType === 'metric' || !Array.isArray(chart.series)) {
+ const chart = result.data as {
+ series?: ChartSeries[];
+ metrics?: unknown;
+ };
+ if (
+ result.chartType === 'funnel' ||
+ result.chartType === 'metric' ||
+ !Array.isArray(chart.series)
+ ) {
return result;
}
@@ -237,7 +275,7 @@ export function registerReportTools(
plotSeries: plotSeries ?? DEFAULT_PLOTTED_SERIES,
}),
};
- }),
+ })
);
}
@@ -247,10 +285,12 @@ export function registerReportTools(
* - metric → AggregateChartEngine.execute
* - others → ChartEngine.execute
*
- * Exported so the in-app chat (apps/api/src/agents/tools/base.ts) can reuse the
- * dispatch without going through MCP. Deliberately returns the raw engine
- * output — the MCP tool reshapes it for LLM consumption, the chat renderer
- * needs the full chart.
+ * `@openpanel/core`'s assistant module (src/report-runner.ts, M5-005) carries
+ * its own copy of this dispatch for its in-app chat tools — core cannot
+ * depend on `@openpanel/mcp` (mcp already depends on core), so the reuse this
+ * comment used to describe is now two hand-synced copies. Deliberately
+ * returns the raw engine output here — the MCP tool reshapes it for LLM
+ * consumption, the chat renderer needs the full chart.
*/
export async function runReport(input: {
organizationId: string;
@@ -277,7 +317,10 @@ export async function runReport(input: {
}
if (report.projectId !== input.projectId) {
- return { error: 'Report does not belong to this project', reportId: input.reportId };
+ return {
+ error: 'Report does not belong to this project',
+ reportId: input.reportId,
+ };
}
const { timezone } = await getSettingsForProject(input.projectId);
@@ -292,7 +335,11 @@ export async function runReport(input: {
interval: report.interval,
startDate,
endDate,
- dashboard_url: reportUrl(input.organizationId, input.projectId, input.reportId),
+ dashboard_url: reportUrl(
+ input.organizationId,
+ input.projectId,
+ input.reportId
+ ),
};
if (report.chartType === 'funnel') {
@@ -343,7 +390,12 @@ export async function runReportFromConfig(input: {
};
if (input.config.chartType === 'funnel') {
- return { ...meta, data: await funnelService.getFunnel(chartInput as Parameters<typeof funnelService.getFunnel>[0]) };
+ 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) };
diff --git a/packages/trpc/src/routers/chat.ts b/packages/trpc/src/routers/chat.ts
index 58f226524..55459e29a 100644
--- a/packages/trpc/src/routers/chat.ts
+++ b/packages/trpc/src/routers/chat.ts
@@ -1,8 +1,13 @@
+// Dissolved into @openpanel/core's assistant module (M5-005): the model
+// whitelist and provider-availability helper moved to
+// packages/core/src/modules/assistant/assistant.constants.ts.
+// @openpanel/validation's chat.ts is now a re-export shim of that file (same
+// shape as @openpanel/validation's import.validation.ts since M5-004), so
+// this router keeps resolving the same symbols unchanged.
import {
getAvailableChatModels,
PREFERRED_DEFAULT_MODEL_ID,
} from '@openpanel/validation';
-
import { createTRPCRouter, protectedProcedure } from '../trpc';
/**
diff --git a/packages/trpc/src/routers/overview.ts b/packages/trpc/src/routers/overview.ts
index bce44f13b..024c83e4e 100644
--- a/packages/trpc/src/routers/overview.ts
+++ b/packages/trpc/src/routers/overview.ts
@@ -1,5 +1,6 @@
-// Dissolved into @openpanel/core's insight module (M5-001).
-import { getReferrerSpikes } from '@openpanel/core';
+// Dissolved into @openpanel/core's insight module (M5-001) and, for
+// `runFilterCommand`, its assistant module (M5-005).
+import { getReferrerSpikes, runFilterCommand } from '@openpanel/core';
import {
ch,
clix,
@@ -29,7 +30,6 @@ import {
import { format } from 'date-fns';
import { z } from 'zod';
import { getProjectAccess } from '../access';
-import { runFilterCommand } from '../agents/filter-command';
import { TRPCAccessError, TRPCForbiddenError } from '../errors';
import {
cacheMiddleware,
diff --git a/packages/validation/src/chat.ts b/packages/validation/src/chat.ts
index 46df06808..07f17bd2d 100644
--- a/packages/validation/src/chat.ts
+++ b/packages/validation/src/chat.ts
@@ -1,311 +1,9 @@
-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',
- 'dashboard',
-]);
-
-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(),
- dashboardId: 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 ChatProvider = 'OpenAI' | 'Anthropic';
-
-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: ChatProvider;
- /**
- * 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,
- },
- {
- id: 'claude-haiku-4-5',
- modelId: 'claude-haiku-4-5',
- label: 'Claude Haiku 4.5',
- group: 'Anthropic',
- },
- {
- id: 'claude-sonnet-4-6',
- modelId: 'claude-sonnet-4-6',
- label: 'Claude Sonnet 4.6',
- group: 'Anthropic',
- },
- {
- id: 'claude-opus-4-6',
- modelId: 'claude-opus-4-6',
- label: 'Claude Opus 4.6',
- group: 'Anthropic',
- },
-] as const satisfies readonly ChatModelEntry[];
-
-export type ChatModelId = (typeof CHAT_MODELS)[number]['id'];
-
-/**
- * localStorage key holding the user's preferred chat model id.
- *
- * Bumped to `v2` when the default was switched from `gpt-4-1` to
- * `gpt-4-1-mini` (April 2026). Existing users had `gpt-4-1` pinned in
- * their v1 key and hit rate-limit errors almost immediately on Tier 1
- * OpenAI accounts; invalidating the old key is the only way to
- * migrate them to the new default without a UI prompt. If you change
- * the default again, bump the suffix.
- */
-export const MODEL_STORAGE_KEY = 'op-chat-model-v2';
-
-/**
- * Preferred default model id. The tRPC `chat.models` endpoint picks
- * this when it's available in the configured provider set, falling
- * back to the first entry in `CHAT_MODELS` otherwise. Picked for its
- * much higher per-minute token budget (OpenAI Tier 1 gives gpt-4.1
- * just 30k TPM — one user exhausts it with a single long turn —
- * whereas gpt-4.1-mini gets 200k TPM for the same tier).
- */
-export const PREFERRED_DEFAULT_MODEL_ID = 'gpt-4-1-mini';
-
-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;
-}
-
-/**
- * Filter the whitelist to models whose provider has an API key configured.
- * Returned in the same order as `CHAT_MODELS` (OpenAI first, then Anthropic)
- * so the first entry is a stable default.
- */
-export function getAvailableChatModels(providers: {
- openai: boolean;
- anthropic: boolean;
-}): ChatModelEntry[] {
- return CHAT_MODELS.filter((m) => {
- if (m.group === 'OpenAI') return providers.openai;
- if (m.group === 'Anthropic') return providers.anthropic;
- return false;
- });
-}
-
-// ────────────────────────────────────────────────────────────────────
-// 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>;
-};
+// Moved into @openpanel/core's assistant module (M5-005, ADR-008's module
+// map: assistant owns "C"). Re-exported here for existing
+// @openpanel/validation importers (apps/start's model picker + chat panel) —
+// same shape as packages/validation/src/import.validation.ts since M5-004.
+// The `./modules/assistant/assistant.constants` subpath is a leaf, isomorphic
+// file with no back-imports into @openpanel/validation, so this re-export
+// carries no runtime cycle despite @openpanel/core already depending on
+// @openpanel/validation elsewhere.
+export * from '@openpanel/core/modules/assistant/assistant.constants';