Skip to content

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

ralph(M15-101): Per-module fixes: packages/core/src/modules/assistant - R12, R16 and the findings no rule covers

ralph57e895d83fb2
diff --git a/apps/start/src/components/chat/tool-results/tool-labels.ts b/apps/start/src/components/chat/tool-results/tool-labels.ts
index be70cd4a3..69ee2789a 100644
--- a/apps/start/src/components/chat/tool-results/tool-labels.ts
+++ b/apps/start/src/components/chat/tool-results/tool-labels.ts
@@ -186,6 +186,9 @@ const PHRASES: Record<
active: 'Loading property distribution',
done: 'Property distribution',
},
+ // Retired server-side — it was a second wire name over
+ // `list_event_properties`' handler — but conversations saved before that
+ // still replay tool calls under this name, so the label stays.
list_properties_for_event: {
active: 'Loading properties',
done: 'Event properties',
diff --git a/packages/core/src/modules/assistant/src/providers.ts b/packages/core/src/modules/assistant/src/providers.ts
index a8f999694..cdf518488 100644
--- a/packages/core/src/modules/assistant/src/providers.ts
+++ b/packages/core/src/modules/assistant/src/providers.ts
@@ -16,49 +16,73 @@ import type { ChatModelEntry } from '../assistant.constants';
export type { ChatModelEntry } from '../assistant.constants';
export { CHAT_MODELS as ALLOWED_MODELS } from '../assistant.constants';
-// One provider client per process, built on first use. The credentials are
-// the same object for every caller — `loadConfig` runs once at boot — so the
-// memo cannot serve one caller another caller's key.
-let _openai: ReturnType<typeof createOpenAI> | null = null;
+// A provider client is memoized per `CoreConfig`, not per process (ADR-022
+// R16: what a thing owns dies with its owner, and nothing outlives the thing
+// that opened it). `loadConfig` runs once per boot, so a running API still
+// builds each client exactly once; a second config in the same process — a
+// test, a second boot — gets a client carrying ITS credentials rather than the
+// first config's, and both are collected with the config that produced them.
+//
+// There is nothing here to close: `createOpenAI`/`createAnthropic` return a
+// closure over a base URL and a header set that calls the global `fetch`. They
+// hold no socket, so R16's "whoever opens a connection closes it" has no
+// connection to name — only a lifetime, which is what the key fixes.
+const openaiClients = new WeakMap<
+ CoreConfig,
+ ReturnType<typeof createOpenAI>
+>();
+
function openai(config: CoreConfig) {
- if (!_openai) {
- const { apiKey, baseUrl, project, organization } = config.ai.openai;
+ const memoized = openaiClients.get(config);
+ if (memoized) {
+ return memoized;
+ }
- if (!apiKey) {
- console.warn(
- `[chat] OPENAI_API_KEY is not set. Models routed through OpenAI will fail with "x-api-key required" until you add it to the API's env.`
- );
- }
+ const { apiKey, baseUrl, project, organization } = config.ai.openai;
- _openai = createOpenAI({
- apiKey,
- baseURL: baseUrl,
- project,
- organization,
- });
+ if (!apiKey) {
+ console.warn(
+ `[chat] OPENAI_API_KEY is not set. Models routed through OpenAI will fail with "x-api-key required" until you add it to the API's env.`
+ );
}
- return _openai;
+
+ const client = createOpenAI({
+ apiKey,
+ baseURL: baseUrl,
+ project,
+ organization,
+ });
+ openaiClients.set(config, client);
+ return client;
}
-let _anthropic: ReturnType<typeof createAnthropic> | null = null;
+const anthropicClients = new WeakMap<
+ CoreConfig,
+ ReturnType<typeof createAnthropic>
+>();
+
function anthropic(config: CoreConfig) {
- if (!_anthropic) {
- const { apiKey, baseUrl, authToken, version } = config.ai.anthropic;
+ const memoized = anthropicClients.get(config);
+ if (memoized) {
+ return memoized;
+ }
- if (!apiKey) {
- console.warn(
- `[chat] ANTHROPIC_API_KEY is not set. Models routed through Anthropic will fail with "x-api-key required" until you add it to the API's env.`
- );
- }
+ const { apiKey, baseUrl, authToken, version } = config.ai.anthropic;
- _anthropic = createAnthropic({
- apiKey,
- baseURL: baseUrl,
- authToken,
- anthropicVersion: version,
- });
+ if (!apiKey) {
+ console.warn(
+ `[chat] ANTHROPIC_API_KEY is not set. Models routed through Anthropic will fail with "x-api-key required" until you add it to the API's env.`
+ );
}
- return _anthropic;
+
+ const client = createAnthropic({
+ apiKey,
+ baseURL: baseUrl,
+ authToken,
+ anthropicVersion: version,
+ });
+ anthropicClients.set(config, client);
+ return client;
}
export const openaiProvider = openai;
diff --git a/packages/core/src/modules/assistant/src/tools/events.ts b/packages/core/src/modules/assistant/src/tools/events.ts
index e17237734..f13102b75 100644
--- a/packages/core/src/modules/assistant/src/tools/events.ts
+++ b/packages/core/src/modules/assistant/src/tools/events.ts
@@ -2,22 +2,20 @@ import { z } from 'zod';
import type { ServiceDeps } from '../../../../services';
import {
getEventPropertyValuesCore,
- listEventPropertiesCore,
queryEventsCore,
} from '../../../event/event.service';
-import {
- chatTool,
- compactEventProperties,
- resolveDateRange,
- truncateRows,
-} from './helpers';
+import { chatTool, resolveDateRange, truncateRows } from './helpers';
+
+/** How many recent events `analyze_event_distribution` tallies. */
+const DISTRIBUTION_SAMPLE_LIMIT = 100;
+/** How many recent events `correlate_events` pairs up by session. */
+const CORRELATION_SAMPLE_LIMIT = 100;
export const analyzeEventDistribution = (deps: ServiceDeps) =>
chatTool(
{
name: 'analyze_event_distribution',
- description:
- 'For a set of events (or all events in the current view), break down their frequency, top properties, and top sources. Useful for "which events fire the most?" questions.',
+ description: `For a set of events (or all events in the current view), break down their frequency, top countries and top devices. Computed from the ${DISTRIBUTION_SAMPLE_LIMIT} most recent matching events, NOT the whole period — \`sample_size\` is that sample, so describe the shape and never quote the counts as totals.`,
schema: z.object({
eventNames: z.array(z.string()).optional(),
startDate: z.string().optional(),
@@ -36,7 +34,7 @@ export const analyzeEventDistribution = (deps: ServiceDeps) =>
eventNames,
startDate: range.startDate,
endDate: range.endDate,
- limit: 100,
+ limit: DISTRIBUTION_SAMPLE_LIMIT,
});
// Tally frequency by event name
@@ -72,8 +70,7 @@ export const correlateEvents = (deps: ServiceDeps) =>
chatTool(
{
name: 'correlate_events',
- description:
- 'Find pairs of events that frequently occur in the same session. Returns event pairs ranked by co-occurrence count.',
+ description: `Find pairs of events that frequently occur in the same session. Ranked by co-occurrence within the ${CORRELATION_SAMPLE_LIMIT} most recent events, NOT the whole period — treat the counts as a sample, never as totals.`,
schema: z.object({
startDate: z.string().optional(),
endDate: z.string().optional(),
@@ -90,7 +87,7 @@ export const correlateEvents = (deps: ServiceDeps) =>
projectId: context.projectId,
startDate: range.startDate,
endDate: range.endDate,
- limit: 100,
+ limit: CORRELATION_SAMPLE_LIMIT,
});
// Group events by sessionId, then count co-occurring event-name pairs
@@ -148,22 +145,3 @@ export const getEventPropertyDistribution = (deps: ServiceDeps) =>
return truncateRows(result.values, 100);
}
);
-
-export const listPropertiesForEvent = (deps: ServiceDeps) =>
- chatTool(
- {
- name: 'list_properties_for_event',
- description:
- 'List fields available for filtering / breakdown on a specific event (or all events). Returns `columns` (top-level event columns like `path`, `country`, `device` — use bare name) and `properties` (custom JSON keys — use prefixed as `properties.<key>`). Dotted sub-keys inside `properties` are rolled up to their root (e.g. all `__query.*` become a single `__query`); ordered by how many sub-keys roll up under each root.',
- schema: z.object({
- eventName: z.string().optional(),
- }),
- },
- async ({ eventName }, context) => {
- const raw = await listEventPropertiesCore(deps, {
- projectId: context.projectId,
- eventName,
- });
- return compactEventProperties(raw, { eventName });
- }
- );
diff --git a/packages/core/src/modules/assistant/src/tools/helpers.ts b/packages/core/src/modules/assistant/src/tools/helpers.ts
index 6d2567364..cf2e7e3c7 100644
--- a/packages/core/src/modules/assistant/src/tools/helpers.ts
+++ b/packages/core/src/modules/assistant/src/tools/helpers.ts
@@ -36,7 +36,10 @@ const TOOL_TIMEOUT_MS = 30_000;
* or a stalled external fetch would otherwise hold the turn for
* the full latency of the tool. We throw with a known shape so
* the agent sees a clear "tool took too long" message and can
- * decide whether to retry with narrower params or move on.
+ * decide whether to retry with narrower params or move on. It
+ * bounds the TURN, not the work: the race abandons the handler
+ * rather than cancelling it, so the query behind a timed-out
+ * tool keeps running to completion on the server.
*/
export function chatTool(
config: {
diff --git a/packages/core/src/modules/assistant/src/tools/index.ts b/packages/core/src/modules/assistant/src/tools/index.ts
index 7f2b21001..47dd5b0cf 100644
--- a/packages/core/src/modules/assistant/src/tools/index.ts
+++ b/packages/core/src/modules/assistant/src/tools/index.ts
@@ -105,11 +105,14 @@ const SEO_TOOLS: ToolList = [
seo.correlateSeoWithTraffic,
] as ToolList;
+// No property-listing tool here on purpose: `base.listEventProperties` is in
+// BASE_TOOLS, so it is already registered on this page. `list_properties_for_event`
+// was a second wire name over the same handler, and the events page offered the
+// model both at once.
const EVENTS_TOOLS: ToolList = [
events.analyzeEventDistribution,
events.correlateEvents,
events.getEventPropertyDistribution,
- events.listPropertiesForEvent,
] as ToolList;
const INSIGHTS_TOOLS: ToolList = [
diff --git a/packages/core/src/modules/assistant/src/tools/pages.ts b/packages/core/src/modules/assistant/src/tools/pages.ts
index 17be4c179..53d76e328 100644
--- a/packages/core/src/modules/assistant/src/tools/pages.ts
+++ b/packages/core/src/modules/assistant/src/tools/pages.ts
@@ -18,7 +18,7 @@ export const getPagePerformance = (deps: ServiceDeps) =>
{
name: 'get_page_performance',
description:
- 'Per-page performance metrics with SEO signal flags (high bounce, low engagement, good landing page). Sortable by sessions, pageviews, bounce_rate, or avg_duration.',
+ "Per-page performance metrics with SEO signal flags (high bounce, low engagement, good landing page). Sortable by sessions, pageviews, bounce_rate, or avg_duration. Inherits the current view's date range but NOT its property filters, so the numbers are project-wide and can differ from the filter-respecting `get_top_pages`.",
schema: z.object({
startDate: z.string().optional(),
endDate: z.string().optional(),
@@ -54,7 +54,7 @@ export const getPageConversions = (deps: ServiceDeps) =>
{
name: 'get_page_conversions',
description:
- 'For a given conversion event, find which pages drive the most conversions. Includes conversion rate per page.',
+ "For a given conversion event, find which pages drive the most conversions. Includes conversion rate per page. Inherits the current view's date range but NOT its property filters, so the numbers are project-wide and can differ from the filter-respecting `get_top_pages`.",
schema: z.object({
conversionEvent: z
.string()
@@ -88,7 +88,7 @@ export const getEntryExitPages = (deps: ServiceDeps) =>
{
name: 'get_entry_exit_pages',
description:
- 'Top entry pages or top exit pages — useful for understanding where users start and where they bounce.',
+ "Top entry pages or top exit pages — useful for understanding where users start and where they bounce. Inherits the current view's date range but NOT its property filters, so the numbers are project-wide and can differ from the filter-respecting `get_top_pages`.",
schema: z.object({
mode: z.enum(['entry', 'exit']),
startDate: z.string().optional(),
@@ -116,7 +116,7 @@ export const findDecliningPages = (deps: ServiceDeps) =>
{
name: 'find_declining_pages',
description:
- 'Find pages where pageview volume dropped vs the immediately preceding period of the same length. Returns each declining page with absolute and percent change.',
+ "Find pages where pageview volume dropped vs the immediately preceding period of the same length. Returns each declining page with absolute and percent change. Inherits the current view's date range but NOT its property filters, so the numbers are project-wide and can differ from the filter-respecting `get_top_pages`.",
schema: z.object({
startDate: z.string().optional(),
endDate: z.string().optional(),
diff --git a/packages/core/src/modules/assistant/src/tools/references.ts b/packages/core/src/modules/assistant/src/tools/references.ts
index e1003d3b1..11416aedc 100644
--- a/packages/core/src/modules/assistant/src/tools/references.ts
+++ b/packages/core/src/modules/assistant/src/tools/references.ts
@@ -46,6 +46,19 @@ export const listReferences = (deps: ServiceDeps) =>
endDate: endDate ?? context.pageContext?.filters?.endDate,
});
+ // KNOWN DEFECT, deliberately left (M15-101): these two bounds do not
+ // agree, and neither is safe for every shape `resolveDateRange` returns.
+ // It yields `YYYY-MM-DD` from explicit dates and from its 30-day
+ // default, but `YYYY-MM-DD HH:mm:ss` in the PROJECT's timezone when the
+ // page carries a range preset (`chart-dates.ts` `getDatesFromRange`).
+ // On that second shape the `lte` concatenation builds
+ // "2026-09-10 23:59:59T23:59:59.999Z", which is an Invalid Date, and the
+ // `gte` is parsed as LOCAL time rather than UTC. Do NOT "align" the two
+ // by appending `T00:00:00.000Z` to the `gte` — that reads as equivalent
+ // only if `range.startDate` were always date-only, and it is not.
+ // Repairing it changes which rows the preset path returns, and picking
+ // the right window means settling which clock `Reference.date` is stored
+ // in — `modules/reference`'s `getChartReferences` owns that answer.
const db = deps.db;
const rows = await db.reference.findMany({
where: {