Tracking
Rule
The tracking system provides a single server-side track() call that fans out
to all registered providers, plus the browser-side trackEvent() counterpart.
Built-in providers auto-register from env vars - set the var and tracking
starts. Custom providers can be registered for any analytics backend. Both
surfaces are best-effort and never block request handling.
How It Works
- At server startup,
registerBuiltinProviders() checks env vars and registers any configured providers.
- Application code calls
track(eventName, properties, source) from actions, plugins, or server routes.
- The registry fans out the event to every registered provider. Errors are caught and logged -- a failing provider never crashes the caller.
- Built-in providers batch HTTP calls (flush every 10 seconds or 50 events, whichever comes first). Each send times out after 10 seconds.
API
track(name, properties?, source?)
Fire an analytics event. source is either a { userId, anonymousId, sessionId }
meta object or an action's ctx passed straight through.
import { track } from "@agent-native/core/tracking";
// From an action — pass ctx; userId comes from ctx.userEmail.
run: async ({ name }, ctx) => {
track("meal.logged", { mealName: name, calories: 350 }, ctx);
};
// From a plugin or route with no ctx.
track(
"meal.logged",
{ mealName: "Salad", calories: 350 },
{ userId: "user@example.com" },
);
The caller's browser session comes from the ambient request context
(RequestContext.browserSessionId, set from the X-Agent-Native-Session-Id
header), so it resolves the same whether the UI called the action or the agent
did. Pass sessionId in the meta object to override it — routes that run
outside a request context, such as /_agent-native/track, do exactly that.
Providers map it to their own session field: $session_id for PostHog (which
joins the event to session replay), session_id as a property for Mixpanel and
Amplitude, a top-level sessionId for webhooks and Agent-Native Analytics. It
is absent for callers with no browser — cron, CLI, MCP, A2A.
identify(userId, traits?)
Identify a user with traits. Forwarded to providers that support it.
import { identify } from "@agent-native/core/tracking";
identify("user@example.com", { plan: "pro", company: "ExampleCo" });
registerTrackingProvider(provider)
Register a custom provider.
import { registerTrackingProvider } from "@agent-native/core/tracking";
registerTrackingProvider({
name: "my-analytics",
track(event) {
// Send event to your backend
},
identify(userId, traits) {
// Optional
},
flush() {
// Optional -- called on graceful shutdown
},
});
flushTracking()
Flush all providers (call before process exit).
Built-in Providers
Set the env var and the provider auto-registers at startup. No SDK dependencies -- all providers use raw HTTP.
| Provider |
Env vars |
| PostHog |
POSTHOG_API_KEY (required), POSTHOG_HOST (optional, defaults to https://us.i.posthog.com), POSTHOG_ERROR_TRACKING=false (optional opt-out) |
| Mixpanel |
MIXPANEL_TOKEN |
| Amplitude |
AMPLITUDE_API_KEY |
| Agent-Native Analytics |
AGENT_NATIVE_ANALYTICS_PUBLIC_KEY (server), AGENT_NATIVE_ANALYTICS_ENDPOINT (optional, defaults to https://analytics.agent-native.com/track) |
| Webhook |
TRACKING_WEBHOOK_URL (required), TRACKING_WEBHOOK_AUTH (optional, sent as Authorization header) |
Multiple providers can be active simultaneously. All receive every event.
Browser-side trackEvent() also forwards to Agent-Native Analytics when VITE_AGENT_NATIVE_ANALYTICS_PUBLIC_KEY is present. Use VITE_AGENT_NATIVE_ANALYTICS_ENDPOINT to override the default browser endpoint. The built-in Agent-Native Analytics sender is quiet on localhost/local dev by default; set AGENT_NATIVE_ANALYTICS_ALLOW_LOCALHOST=true only for an intentional local ingestion test.
An app served from a hosted beta host (beta.*.agent-native.com) reports to beta Analytics: resolveLaneEndpoint moves an endpoint on a production lane host to its beta lane for browser events, auth-page events, replay uploads, and server events. A new sender that reads the analytics endpoint must pass it through resolveLaneEndpoint too, or beta traffic splits. Beta and production Analytics share one database, so an ingest change runs on beta traffic first, and checking it on beta proves the merged code rather than production's. An endpoint on any other host is left as configured.
Error Capture
Exceptions fan out through server/capture-error.ts to every registered
backend - Sentry, PostHog, and the tracking providers - from one
captureError() call. Backends are additive: configuring a second one does not
displace the first, and no backend is required for the others to work.
When first-party Agent-Native Analytics is configured, browser
configureTracking() captures uncaught errors, unhandled rejections, and
manual captureException() calls as $exception events through /track.
On the server, the core route plugin registers the tracking capture provider:
captureError() calls captureException(), and the Agent-Native provider sends
the same event when the server public key is configured. Analytics groups both
into owner-scoped error_issues and error_events, shown in Monitoring ->
Errors and exposed to authenticated agents through list-error-issues and
get-error-issue. This remains available even when external Sentry is
unavailable or rate-limited.
Emit through captureError() / captureException(). Never hand-roll a
track("$exception", …): each backend needs its own payload shape and the
providers build it.
- Provider-agnostic wiring must not live in a provider plugin. The Nitro
error hook is in core-routes-plugin.ts, not sentry-plugin.ts, because
that plugin returns early when no SENTRY_DSN is set — hooking route errors
there meant an app on any other backend silently reported none.
captureError() is the one noise and flood boundary. The drop rules live
in shared/error-noise.ts (expected 4xx, access-control rejections, Lambda
socket hang up, third-party/extension/GTM stacks, stale chunks, opaque
Script error.); the Nitro hook, every explicit captureError() call, the
browser capture, Sentry beforeSend, and the analytics ingest all call
classifyErrorNoise(). After the filter, server/capture-error.ts folds
transient-database, database-credential, and configuration failures into one
aggregate per (class, route): the first event immediately, then one summary
per window carrying suppressedCount. Every drop is counted
(getCaptureErrorStats()); an error that matches no rule is reported every
time. A backend must hang off registerErrorCaptureProvider, never call a
provider SDK from a catch block, or it skips both. Two escape hatches keep a
rule from hiding a real failure: tag a capture
reportExpected: "true" (REPORT_EXPECTED_FAILURE_TAG) when your code raises
an access-control or 4xx failure as a failure (a runner whose grant was
lost), and give an explicit browser capture a context or area tag so a
stackless Safari/Firefox network error from it is not dropped as
unattributable. Stale-chunk failures are dropped because route-chunk-recovery
reloads on them; when it cannot (cooldown, desktop) it reports one
RouteChunkRecoveryExhausted per page session instead.
- A backend can accept a malformed payload and still show a count. PostHog
ingested the framework's camelCase
$exception for a long time and rendered
empty, ungroupable issues — which reads as coverage, not as breakage. When
adding or changing a backend, check what an event looks like in its UI, not
just that the request returned 200.
- Attribute the error. Without a user id, server exceptions land under
anonymous and split one person in two against their browser events. Pass
aiTraceId for anything inside an agent run so the issue and the LLM trace
resolve to each other.
- Every server capture carries a failure packet at
extra.failureContext (observability/failure-context.ts): app, route,
action or automation name, threadId, runId, requestId, userScope
(org or personal, never an email), threadUrl
(https://<app host>/?thread=<chat_threads.id>), build, environment,
errorCode, failureClass. The boundary derives it from what the call site
already passes (tags.action, extra.runId / threadId / request_id,
aiTraceId) and from the ambient chat run, so a capture inside a run names
its thread with no change at the call site. Work that runs outside any
request (a scheduled automation) passes failure: { threadId, automationName, userScope } on the capture. A run id also becomes aiTraceId. The Analytics
issue page links threadUrl; hand any agent the packet and it can run
get-agent-thread-debug with the runId. Never put an email, a token or a
prompt in it.
- CLI telemetry has its own allowlist.
@agent-native/core and
@agent-native/skills send through packages/core/src/cli/telemetry.ts, which
silently drops any property missing from CLI_TELEMETRY_PROPERTIES in
telemetry-sanitize.ts, and any string value that could hold a path, URL or
email. Adding a CLI property means adding it there and to
packages/core/docs/content/telemetry.mdx; a test fails until the page lists
it. Pass the error itself as error and it is cut down to a short hint. Wrap
a message we wrote in KnownCliError to report it whole. Nothing that names a
project, a path or a person belongs in a CLI event.
- Rates are events, not log lines.
tracking/failure-counters.ts counts a
failure class per (event, bounded dimensions) and ships count per window
(first occurrence at once, the rest once a minute, SUM(count) is exact):
action_error_counts (action_name, error_code, status_class,
action_source) and credential_state_counts (credential_state,
credential_subject, source). Automation pauses and automatic resumes are
automation_paused / automation_resumed (automation_hash, never the
name), the client's open circuits are action_circuit_tripped, and a chat run
that ended on a credential problem is a $ai_trace with credential_state.
Attachment mint/resolve/delete outcomes (ok included) are
attachment_outcome_counts (operation, status, reason, who_can_fix),
and a template counts its own classes with countOutcome("<thing>_counts", { ...tokens }) from @agent-native/core/tracking (Mail's Gmail cooldowns are
gmail_cooldown_counts, by site). Never one event per failure; a name that
is not <thing>_counts is dropped with one console error.
- Browser outcomes are bounded, too.
agent_run_outcome is one event per
run (outcome, legacy code, terminal_source,
verified_after_pipe_closed, resume_attempts, run_id, thread_id, and
turn_id when the page started the turn, except a replay whose turn the
server did not name):
every interrupted / failed / unverified run up to 30 per page, every
stopped run up to its own 30 (so stops never crowd out failures), and
succeeded sampled at 10% with sample_weight. A turn the server refuses
at its start (no model connected, a 5xx) is a failed run too, with
terminal_source: local and the refused turn's id. A failed or
interrupted run adds its cause from AGENT_TROUBLE_CAUSES when one fits
its code, and Analytics groups the rest by code. A code that is not
an identifier is sent as unrecognized_code (agentErrorCodeForTelemetry),
because a thrower's data.code can be a sentence. It never carries the
run's message, not even redacted: no pattern can tell an unquoted document
or person's name from the words around it, so a message stays out of every
event. A provider error is provider_error only when its code
came from a structured HTTP status (http_5xx, including a status on a
wrapped cause); a status that appears only in message text is not read. agent_feedback_submitted (sentiment,
run_id, thread_id) is the browser's copy of a thumbs rating, because
$ai_feedback has no browser session. Every pageview carries
agent_signals: 1 (AGENT_SIGNALS_PAGEVIEW_PROPERTY): clients before it
sampled stops at 10% and sent no ratings or page_load_id, so Analytics
reads a session's cancelled runs, thumbs-down, and quick backs as measured
only after seeing the marker and while no unmarked pageview or sampled stop
shares the session (tabs share one session id), and counts only stops sent
unsampled. Keep all three guarantees while the marker ships. Every
pageview also carries page_load_id (PAGE_LOAD_PAGEVIEW_PROPERTY),
the same until the page reloads, because quick backs compare pages only
within one page load.
session_navigation is one event per document that left because of the
session (reason, and for signed_out the evidence: signed_out_body or
http_401), never the destination. Both are emitted from the single place
that decides (agentkit-protocol.ts, navigateForSession; a refused
start from the transport's start-run catch), not the callers.
agent_chat_stuck_detected fires once per run and only while the stuck
banner shows, so Analytics' stuck chats are ones the person saw. It carries
reason, dispatchMode, hasInFlightWork and heartbeatSinceSec, so a run
the server still holds (a live background worker) reads differently from a
dead one.
Symbolication is per-backend and not automatic: the framework uploads no source
maps to PostHog, so minified browser stacks stay minified there. Known gap, not
a bug to re-diagnose.
Browser keys and the SSR shell
Public keys (POSTHOG_PUBLIC_KEY, the Sentry client DSN, and the first-party
Analytics public key) ship inside the
CDN-cached SSR shell — publishable and identical for every visitor. Server keys
never do, and are never a fallback for a public one: POSTHOG_API_KEY may be a
private key and this value lands in public HTML.
Browser errors post directly to the backend rather than through
/_agent-native/track, because that route requires a resolved session and
relaying would drop every signed-out crash.
When adding a client config field, update both server/posthog-config.ts
and the mirrored worker emitter in deploy/build.ts — the worker bundles a
string copy and cannot import the module, so a one-sided edit drops the config
silently in deployed builds. posthog-config.spec.ts pins the two outputs
together.
Cookie consent
Visitors in the consent region (shared/consent.ts, copied from builder.io's
banner rules) see ConsentBanner, which AppProviders and the docs root
mount, and choose two categories: performance (Google Analytics,
Amplitude, Ahrefs) and targeting (Google Tag Manager, attribution).
Everyone else gets no banner and every tag at once.
- Every third-party browser tag goes through the gate: server-injected
scripts use
consentGatedScript() in server/analytics.ts; client code
uses whenConsentAllows(category, run) from
@agent-native/core/client/consent. A tag in a raw <script> or a
<noscript> fallback runs before the visitor chooses.
- The GTM container (
GTM_CONTAINER_ID, shared by every app and the docs
site) carries the ad pixels: Meta, LinkedIn, Reddit, X, Bing UET, Google
Ads and OpenAI, plus HubSpot, Dreamdata, Vector, Unify, Common Room and
Apollo. Gating the container gates them all, which is why it sits under
targeting. Tags added inside GTM need no code change; tags added
anywhere else do.
- The inline bootstrap in
server/analytics.ts runs the queue on pages that
never load the app bundle. It repeats the cookie format and time-zone
rules of client/consent.ts; change both together. Each queued loader
runs once a page, even after a reject and a fresh accept.
- A loaded tag can't be unloaded, so Google's tags follow Consent Mode: the
server pushes a
consent default from the stored choice (all denied
without one) to every Google data layer before any tag, and
client/consent.ts pushes a consent update on each region answer and
choice. Our own gtag events also wait for performance. Non-Google tags
in GTM stop only on the next page load.
- Use
consentDecision(category) for anything a revoke can't undo once
sent; it is null until the visitor's choice or the server's region is
known. consentAllowsNow guesses from the time zone, so only pair it with
storage a revoke can clear.
- First-party analytics keeps counting in the region before consent, but the
visitor id
an_aid waits for performance: until then
getOrCreateAnalyticsAnonymousId() returns undefined and stores nothing,
and events go out with no anonymousId and
properties.analytics_consent: "withheld". Events sent before the region
is known wait for it, or leave without the id, marked
analytics_consent: "unknown", if the page closes first. The plain
sign-in page reads the id through the same helper and holds its events
with whenConsentDecided; never write an_aid directly. A choice made in
another tab applies at once in tabs of the same app, and on focus in
another app on the site. A
reject clears a stored id.
Those rows count as events and views but never as people; the Analytics
activation funnel joins them to a signup in the same session. Session
replay waits for performance too, with no time-zone head start; a reject
stops it, discards what it hasn't uploaded (including a batch an upload in
flight puts back), and forgets its stored replay identity. Amplitude rechecks the
choice before it initializes and never sends events from before an accept.
Google events held for the region's answer go out only if it allows them. Sentry error capture and the session id an_sid aren't
gated.
MCP Server Events
The MCP server an app exposes reports its own usage. packages/core/src/mcp/analytics.ts
emits one event per protocol request, and the emission points sit in the shared
server builder (build-server.ts), so the HTTP mount and the stdio transport
report identically.
| Event |
Fires on |
$mcp_initialize |
the client/server handshake (HTTP mount only) |
$mcp_tools_list |
tools/list |
$mcp_tool_call |
tools/call, success or failure |
$mcp_resources_list |
resources/list |
$mcp_resource_read |
resources/read |
Names come from PostHog's MCP analytics vocabulary
(https://posthog.com/docs/mcp-analytics/events) on purpose, so PostHog's MCP
dashboards read these events with no mapping layer — but they go through
track() like every other event, so Mixpanel, Amplitude, a webhook, and
Agent-Native Analytics receive the same ones.
Shared properties: $mcp_source (http / stdio), $mcp_server_name,
$mcp_server_version, $mcp_app_id, $mcp_client_name, $mcp_client_version,
$mcp_client_user_agent, $mcp_vendor_client, $mcp_protocol_version. Per
event: $mcp_tool_name, $mcp_tool_description, $mcp_tool_category
(read / write), $mcp_listed_tool_names, $mcp_duration_ms,
$mcp_is_error, $mcp_error_type, $mcp_error_message, $mcp_resource_name,
$mcp_resource_uri.
- A client's own name is only on the wire at
initialize. The mount is
stateless — one server per request — so no later event can recover it.
$mcp_initialize carries the clientInfo from the handshake; every other
event falls back to the 2026-era per-request _meta and the HTTP user agent,
and $mcp_vendor_client buckets both spellings onto one row.
- A failed call is reported with its reason, not just
isError. The
tools/call handler renders "unknown tool", "forbidden scope", and a thrown
action error as the same shape of error result, so each sets $mcp_error_type
where it returns rather than having it guessed back out of the response text.
- Payloads stay out.
$mcp_response is never emitted. $mcp_parameters is
off by default and redacted when on — tool arguments carry user content.
Off switches: MCP_ANALYTICS=false (observability.mcpEvents) disables the
events; MCP_ANALYTICS_PARAMETERS=true (observability.mcpCaptureParameters)
opts into arguments. They sit in observability with the other capture
switches, not in analytics — they gate every provider, not the first-party
Agent-Native Analytics sender whose key lives there.
Default Baseline Events
Template roots call configureTracking() once during app startup. That installs default browser pageview tracking for hosted apps:
- Event:
pageview
- Fires on initial load,
history.pushState, history.replaceState, and popstate
- De-dupes repeated events for the same URL
- Includes
url, path, hostname, referrer, title, navigation_type, agent_signals, page_load_id, app, and inferred template
- Includes LLM connection context on browser events when known:
llm_connection (builder, anthropic, openai, etc.), llm_engine, llm_model, llm_connection_source, and llm_connection_configured
- Does not send first-party events from localhost/local dev
Visitor identity (anonymousId + sessionId)
Every browser-side trackEvent() POST to the Agent-Native Analytics /track endpoint includes:
anonymousId — persistent per-browser visitor ID stored in localStorage under agent-native.anonymous_id. Generated once and reused across sessions. Use this for unique-visitor and returning-visitor metrics. In the consent region it's absent until the visitor accepts analytics cookies (see Cookie consent).
sessionId — rotating per-visit ID stored in localStorage under agent-native.session_id, with a 30-minute idle timeout (matches GA4 / Mixpanel defaults). Use this for sessions-per-visitor, pages-per-session, and session-duration metrics.
userId — only set when the calling code passes properties.userId. Anonymous traffic leaves this NULL by design; anonymousId is the fallback.
These fields land in the analytics_events.anonymous_id, analytics_events.session_id, and analytics_events.user_id columns in the analytics template. Storage access is wrapped in try/catch — private-browsing / blocked-storage clients silently degrade to NULL rather than crashing the page.
Referral / viral attribution (first-touch)
configureTracking() also captures an anonymous visitor's first-touch referral context once, on first page load, and persists it across the signup boundary so the server-side signup event records where the user came from. This powers virality metrics for every template (Clips share links, Plans public pages, etc.).
There is one capture implementation, captureAttribution() from @agent-native/core/client/analytics. Every page that can be someone's first visit calls it, including the server-rendered sign-in page, which never runs configureTracking() and passes { landingPath } so landing_path names the app path behind the sign-in page. Never copy the capture into a page: the sign-in page's private copy silently dropped ad click ids, site handoff fields, and last touch for every visitor who landed on it.
Share-link params (set by whatever generates the link; read client-side only):
ref — referral source bucket, e.g. clip_share, plan_share
via — the referrer's stable user id (the clip/plan owner)
utm_source, utm_medium, utm_campaign, utm_content, utm_term
Client persistence (first-write-wins, except that the first visit with a source replaces one without; last touch lives in an_last_touch / an_lt):
localStorage key an_attribution and first-party cookie an_ft (path=/; max-age=2592000; SameSite=Lax, not HttpOnly — non-sensitive, written by client JS).
- Both store the same URL-encoded compact JSON (empty fields omitted, each value capped at 120 chars):
{ ref, via, utm_source, utm_medium, utm_campaign, utm_content, utm_term, landing_path, landing_referrer, landed_at }. landing_referrer is the host only of document.referrer (scrubbed; same-origin referrers are dropped).
- A durable copy, cookie
an_fts, set only by our server (POST /_agent-native/auth/attribution, same-origin, no session needed) and expiring 365 days after landed_at, never extended by later visits. The browser sends its first touch there each load until the server holds that visit. Safari caps cookies written by page JavaScript at seven days, so only a server-set cookie can keep first touch for a year. The value carries v: "1"; a reader ignores other versions. When the browser's copies are gone, capture restores them from an_fts. Each sync after the browser writes an_ft or an_lt also has the server write them again from the request's cookies, so Safari keeps them their full 30 days too.
- Every copy is compared with
preferFirstTouch (shared/first-touch-persistence.ts): the first visit with a source, else the first visit. Never add a second ordering rule: the server cookie route, the browser, and signup must agree on which visit is first touch, or a slow response from one tab overwrites a better touch from another.
- Attribution is a
targeting consent category. Visitors in the consent region (builder.io's GDPR list: the EU, the rest of the EEA, Monaco, San Marino, Åland and France's overseas regions; not the UK or Switzerland, in packages/core/src/shared/consent.ts) get nothing stored until they opt in through the an_consent cookie. The banner writes an_consent in the page and then POST /_agent-native/auth/consent writes it again from the server, so Safari keeps the choice its full year. The browser gates capture with whenConsentAllows("targeting", …) from client/consent.ts, which asks GET /_agent-native/auth/consent-region (the request's country) and falls back to the time zone; a reject clears every copy. The server refuses an_fts and clears all three cookies by request country unless an_consent grants targeting. Everyone else is stored as before, with no banner. Don't add attribution storage that bypasses captureAttribution(), or it skips this check.
getFirstTouchAttribution() (from @agent-native/core/client) returns the parsed object or null.
Signup event enrichment (server-side, from the an_fts and an_ft cookies on the signup/OAuth-callback request, whichever preferFirstTouch picks, with an_fts winning a tie, derived in packages/core/src/server/attribution.ts):
referral_source — ref if present, else derived: /share/… → clip_share; a plan public path (/p/, /plan/, /share-plan/) → plan_share; a non-empty external referring host → external; otherwise direct.
referrer_user (= via), referral_medium (= utm_medium), referral_campaign (= utm_campaign)
utm_source, utm_medium, utm_campaign, utm_content, utm_term (raw passthrough)
first_touch_path (= landing_path), landing_referrer
Attribution parsing is fully defensive and never blocks signup — a missing/malformed cookie falls back to referral_source: "direct".
Other framework-level baseline events:
session status from useSession(), with signed_in
action.response from the browser action transport, with action name,
the route template of the page that made the request (omitted when no
manifest route matches),
browser-perceived duration and TTFB, response status/outcome, response size
when known, and parsed Server-Timing phases for framework readiness and
database work. Its request_id joins the exact browser and server events.
This separates server time from CDN/network/body overhead. One at or over
SLOW_ACTION_RESPONSE_MS (1 s) is never sampled. When someone waited for
it (isWaitedActionResponse: the page stayed visible and the request was
not cancelled), it is also marked on the session replay
(agent-native.slow_request) with its action, method, duration, status,
outcome, and page_hidden.
web_vitals once per page view, with the React Router route template
(/sessions/:id, never the ids; omitted when no manifest route matches,
because a normalized raw path still carries slugs and emails. It is the one
tracked event with no url or path, even from getDefaultProps:
ROUTE_ONLY_EVENT_NAMES in client/analytics.ts strips them),
navigation_type (load, client, or resume after the tab was
hidden, sent only when it saw an interaction or layout shift), and
ttfb_ms, lcp_ms, inp_ms, and cls. TTFB and LCP exist only for
document loads, a load in a background tab is not reported, and a metric the browser cannot measure (including CLS when
the layout-shift observer fails) is omitted rather than sent as 0. A page
view ends on pushState/popstate to another path or when the tab is
hidden; replaceState keeps it, so redirects land on the final route.
Measured with native PerformanceObservers; configureTracking({ webVitals: false }) turns it off. Each page view also marks the replay.
- Request timing is an OpenTelemetry
http.server span, not a product event. Each
framework HTTP request records method, bounded route template, status code,
first-request-in-isolate cold marker, framework readiness wait, and database
operation count and wall time. The span goes only to the registered
OpenTelemetry provider and never reaches analytics providers, so it cannot
fire product alerts. Its status is error for 5xx responses only. Ingest
endpoints, /api/analytics/replay, and AGENT_NATIVE_HTTP_TELEMETRY_DISABLED
record no span. Cold or 1 s-plus requests also write an
agent-native.slow_request log line with process age, readiness wait, and
database timings. Responses carry Server-Timing for app, startup, db,
db-connect, and db-slowest (plus startup-db-* for initialization
database work) and an X-Agent-Native-Request-Id header where applicable.
Query text and parameters are never captured. There is no sampling knob for
this span; export volume is governed by the OpenTelemetry sampler.
signup from Better Auth user creation, with auth_provider, auth_user_id, and first-touch referral attribution (referral_source, referrer_user, referral_medium, referral_campaign, utm_*, first_touch_path, landing_referrer — see "Referral / viral attribution" above)
builder connect clicked and builder connect popup blocked from browser Use Builder.io CTAs
builder connect started, builder connect succeeded, builder connect failed, builder disconnect succeeded, and builder disconnect failed from the Builder connection routes, with LLM connection context when resolvable
$ai_generation from instrumented agent loops, with PostHog AI Observability fields such as $ai_trace_id, $ai_session_id, $ai_model, $ai_provider, $ai_input_tokens, $ai_output_tokens, $ai_latency, $ai_total_cost_usd, and mirrored Agent-Native query fields such as run_id, thread_id, turn_id, cost_cents_x100, duration_ms, tool_calls, and status. A bounded tools array contains names, start offsets, durations, statuses, and coarse error classes only; interrupted tools and failed runs remain visible, and delegated runs include protocol/task/parent-run/parent-turn correlation. Run failure messages are omitted from every tracking provider even with content capture enabled. $ai_error carries a fixed message derived from terminal_code, a named cause, terminal state, and retryability. The error_message field and tool error output text are absent. Local trace SQL retains debugging detail under the observability capture settings.
agent_run_terminal is one event per run: from the run's own process, or from the SQL write that ended it for that process (a reap with reaped: true, reap_source, recovery_outcome; a stop with status: "aborted" and abort_reason; the reaper's repair from the event log; a run that fails or is released before its worker starts). Not sent yet: a background chunk that hands off to a continuation, and a run the production agent marks errored before its run loop starts (a preparation, history or dispatch failure). A row aborted as duplicate_submission or execution-lease-busy stood in for another run and sends none. An event sent from a SQL write has no model, engine or attempt_count, since only the run's process knows them; every reported aborted run is sent this way. It carries turn_id and the run's user (the turn's initiator when a SQL write ended it, never the request that ended it; none for an anonymous visitor). run_started also carries turn_id.
agent_turn_submitted is one browser event per agent request the server accepts (not on send, so a busy-slot refusal then queue counts once; a replay is not counted, including a retry the server answers with the run it already started), with the turn_id the server stores on the run, initiator (user, app for sendToAgentChat including a send deferred while the thread restored, system for continuations, recoveries, approvals, setup replays and background sends), surface, and submit_message_id / recovery_of_run_id when present. Continuations repeat the turn's turn_id as system, so count turns by distinct turn_id. A send routed to Builder or an MCP host is reported once with routed_to and no turn_id, also when the host has not confirmed it. A queued message the server's inbox drain admits sends no agent_turn_submitted yet; its run still reports agent_run_terminal with turn_id queued-<message id>. A queued message the browser promotes is counted.
agent_run_terminal carries error_code and error_cause, never error_detail. Run and completion captures, and Builder gateway failures, use captureError(..., { errorMessagePolicy: "omit" }): providers receive the original exception type, stack frames without the original message header or nested causes, and a fixed Internal Server Error message. Noise filtering still sees the original failure; flood summaries use the fixed label. Monitoring groups by app, type, frame, error code, and failure class instead of user-specific message wording.
For new lifecycle events, call track() server-side when the server is the source of truth, and trackEvent() client-side only for browser interactions.
Lifecycle taxonomy
Lifecycle event names use lowercase snake_case; lifecycle properties use the
same convention. The shared dimensions are app_name, template_name,
user_id, user_email, workspace_id, session_id, output_id,
output_type, source, and referrer. App/template values are canonical ids
without the agent-native- prefix. Identity is also stored in the event's
top-level user/session columns for joins.
The canonical lifecycle events are app_entered, core_action_started,
core_action_completed, core_action_failed, output_viewed,
output_shared, cta_clicked, return_usage, and cross_app_used. The
framework also emits action_started, action_completed, and
action_failed for mutating defineAction() calls so UI, agent, MCP, A2A,
automation, and CLI activity share one action-level trail. Read-only actions
and high-frequency refresh, polling, navigation, and application-state actions
are excluded.
App entry is emitted once per app and browser session. Tracking is action-level
only: it does not install mouse, pointer, scroll, keypress, or DOM autocapture.
Existing legacy events remain available and emit their canonical lifecycle
counterpart where the meaning is unambiguous, so downstream dashboards can
migrate without losing historical names.
Event name migration
All new event names and properties use lowercase snake_case. The shared
track() and browser trackEvent() emitters preserve a legacy event exactly
and, for names in LEGACY_TRACKING_EVENT_NAME_ALIASES, emit a canonical alias
with legacy_event_name and canonical_event_name provenance properties. Use
the canonical alias for new dashboards and new call sites; do not normalize
historical warehouse rows or add new legacy names. Provider/framework names
such as $ai_*, $mcp_*, $exception, action.response, and
app.first_action are intentional exceptions.
Provider Interface
interface TrackingProvider {
name: string;
track(event: TrackingEvent): void | Promise<void>;
identify?(
userId: string,
traits?: Record<string, unknown>,
): void | Promise<void>;
flush?(): void | Promise<void>;
}
interface TrackingEvent {
name: string;
properties?: Record<string, unknown>;
timestamp?: string;
userId?: string;
}
Design Decisions
- globalThis singleton -- the registry uses a
Symbol.for key on globalThis so multiple ESM graph instances (dev-mode Vite + Nitro, symlinks) share one provider set.
- Best-effort fan-out -- provider errors are caught and logged, never propagated. A broken analytics integration must not break app functionality.
- Batched HTTP -- built-in providers enqueue events and flush every 10 seconds or 50 events, minimizing outbound requests.
- NOT bridged to the event bus -- tracking and the event bus are separate concerns. The event bus is for triggering automations; tracking is for analytics. Do not subscribe to
track() calls from the event bus or vice versa.
Key Files
| File |
Purpose |
packages/core/src/tracking/registry.ts |
track(), identify(), registerTrackingProvider(), flushTracking() |
packages/core/src/tracking/providers.ts |
Built-in providers (PostHog, Mixpanel, Amplitude, Agent-Native Analytics, Webhook) and registerBuiltinProviders() |
packages/core/src/tracking/types.ts |
TrackingEvent and TrackingProvider interfaces |
packages/core/src/tracking/posthog-exception.ts |
$exception_list builder + stack-frame parser (isomorphic: server and browser) |
packages/core/src/tracking/redaction.ts |
Shared bounding/redaction helpers used by every exception emitter |
packages/core/src/shared/error-noise.ts |
The one noise rule set (classifyErrorNoise) plus frame-origin and PII scrubbers; browser, server, Sentry, and ingest all call it |
packages/core/src/server/error-noise-filter.ts |
Provider-agnostic drop rules, applied by |
…(truncated)
1---2name: tracking3description: >-4 Server-side analytics tracking with pluggable providers. Use when adding5 analytics events, registering custom tracking providers, or configuring6 built-in providers (PostHog, Mixpanel, Amplitude, Webhook).7scope: dev8metadata:9 source: https://skillmd.com/skills/builderio/tracking10 internal: true11---1213# Tracking1415## Rule1617The tracking system provides a single server-side `track()` call that fans out18to all registered providers, plus the browser-side `trackEvent()` counterpart.19Built-in providers auto-register from env vars - set the var and tracking20starts. Custom providers can be registered for any analytics backend. Both21surfaces are best-effort and never block request handling.2223## How It Works24251. At server startup, `registerBuiltinProviders()` checks env vars and registers any configured providers.262. Application code calls `track(eventName, properties, source)` from actions, plugins, or server routes.273. The registry fans out the event to every registered provider. Errors are caught and logged -- a failing provider never crashes the caller.284. Built-in providers batch HTTP calls (flush every 10 seconds or 50 events, whichever comes first). Each send times out after 10 seconds.2930## API3132### `track(name, properties?, source?)`3334Fire an analytics event. `source` is either a `{ userId, anonymousId, sessionId }`35meta object or an action's `ctx` passed straight through.3637```ts38import { track } from "@agent-native/core/tracking";3940// From an action — pass ctx; userId comes from ctx.userEmail.41run: async ({ name }, ctx) => {42 track("meal.logged", { mealName: name, calories: 350 }, ctx);43};4445// From a plugin or route with no ctx.46track(47 "meal.logged",48 { mealName: "Salad", calories: 350 },49 { userId: "user@example.com" },50);51```5253The caller's browser session comes from the ambient request context54(`RequestContext.browserSessionId`, set from the `X-Agent-Native-Session-Id`55header), so it resolves the same whether the UI called the action or the agent56did. Pass `sessionId` in the meta object to override it — routes that run57outside a request context, such as `/_agent-native/track`, do exactly that.58Providers map it to their own session field: `$session_id` for PostHog (which59joins the event to session replay), `session_id` as a property for Mixpanel and60Amplitude, a top-level `sessionId` for webhooks and Agent-Native Analytics. It61is absent for callers with no browser — cron, CLI, MCP, A2A.6263### `identify(userId, traits?)`6465Identify a user with traits. Forwarded to providers that support it.6667```ts68import { identify } from "@agent-native/core/tracking";6970identify("user@example.com", { plan: "pro", company: "ExampleCo" });71```7273### `registerTrackingProvider(provider)`7475Register a custom provider.7677```ts78import { registerTrackingProvider } from "@agent-native/core/tracking";7980registerTrackingProvider({81 name: "my-analytics",82 track(event) {83 // Send event to your backend84 },85 identify(userId, traits) {86 // Optional87 },88 flush() {89 // Optional -- called on graceful shutdown90 },91});92```9394### `flushTracking()`9596Flush all providers (call before process exit).9798## Built-in Providers99100Set the env var and the provider auto-registers at startup. No SDK dependencies -- all providers use raw HTTP.101102| Provider | Env vars |103| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |104| PostHog | `POSTHOG_API_KEY` (required), `POSTHOG_HOST` (optional, defaults to `https://us.i.posthog.com`), `POSTHOG_ERROR_TRACKING=false` (optional opt-out) |105| Mixpanel | `MIXPANEL_TOKEN` |106| Amplitude | `AMPLITUDE_API_KEY` |107| Agent-Native Analytics | `AGENT_NATIVE_ANALYTICS_PUBLIC_KEY` (server), `AGENT_NATIVE_ANALYTICS_ENDPOINT` (optional, defaults to `https://analytics.agent-native.com/track`) |108| Webhook | `TRACKING_WEBHOOK_URL` (required), `TRACKING_WEBHOOK_AUTH` (optional, sent as `Authorization` header) |109110Multiple providers can be active simultaneously. All receive every event.111112Browser-side `trackEvent()` also forwards to Agent-Native Analytics when `VITE_AGENT_NATIVE_ANALYTICS_PUBLIC_KEY` is present. Use `VITE_AGENT_NATIVE_ANALYTICS_ENDPOINT` to override the default browser endpoint. The built-in Agent-Native Analytics sender is quiet on localhost/local dev by default; set `AGENT_NATIVE_ANALYTICS_ALLOW_LOCALHOST=true` only for an intentional local ingestion test.113114An app served from a hosted beta host (`beta.*.agent-native.com`) reports to beta Analytics: `resolveLaneEndpoint` moves an endpoint on a production lane host to its beta lane for browser events, auth-page events, replay uploads, and server events. A new sender that reads the analytics endpoint must pass it through `resolveLaneEndpoint` too, or beta traffic splits. Beta and production Analytics share one database, so an ingest change runs on beta traffic first, and checking it on beta proves the merged code rather than production's. An endpoint on any other host is left as configured.115116## Error Capture117118Exceptions fan out through `server/capture-error.ts` to every registered119backend - Sentry, PostHog, and the tracking providers - from one120`captureError()` call. Backends are additive: configuring a second one does not121displace the first, and no backend is required for the others to work.122123When first-party Agent-Native Analytics is configured, browser124`configureTracking()` captures uncaught errors, unhandled rejections, and125manual `captureException()` calls as `$exception` events through `/track`.126On the server, the core route plugin registers the tracking capture provider:127`captureError()` calls `captureException()`, and the Agent-Native provider sends128the same event when the server public key is configured. Analytics groups both129into owner-scoped `error_issues` and `error_events`, shown in Monitoring ->130Errors and exposed to authenticated agents through `list-error-issues` and131`get-error-issue`. This remains available even when external Sentry is132unavailable or rate-limited.133134Emit through `captureError()` / `captureException()`. Never hand-roll a135`track("$exception", …)`: each backend needs its own payload shape and the136providers build it.137138- **Provider-agnostic wiring must not live in a provider plugin.** The Nitro139 `error` hook is in `core-routes-plugin.ts`, not `sentry-plugin.ts`, because140 that plugin returns early when no `SENTRY_DSN` is set — hooking route errors141 there meant an app on any other backend silently reported none.142- **`captureError()` is the one noise and flood boundary.** The drop rules live143 in `shared/error-noise.ts` (expected 4xx, access-control rejections, Lambda144 `socket hang up`, third-party/extension/GTM stacks, stale chunks, opaque145 `Script error.`); the Nitro hook, every explicit `captureError()` call, the146 browser capture, Sentry `beforeSend`, and the analytics ingest all call147 `classifyErrorNoise()`. After the filter, `server/capture-error.ts` folds148 transient-database, database-credential, and configuration failures into one149 aggregate per (class, route): the first event immediately, then one summary150 per window carrying `suppressedCount`. Every drop is counted151 (`getCaptureErrorStats()`); an error that matches no rule is reported every152 time. A backend must hang off `registerErrorCaptureProvider`, never call a153 provider SDK from a catch block, or it skips both. Two escape hatches keep a154 rule from hiding a real failure: tag a capture155 `reportExpected: "true"` (`REPORT_EXPECTED_FAILURE_TAG`) when your code raises156 an access-control or 4xx failure as a failure (a runner whose grant was157 lost), and give an explicit browser capture a `context` or `area` tag so a158 stackless Safari/Firefox network error from it is not dropped as159 unattributable. Stale-chunk failures are dropped because route-chunk-recovery160 reloads on them; when it cannot (cooldown, desktop) it reports one161 `RouteChunkRecoveryExhausted` per page session instead.162- **A backend can accept a malformed payload and still show a count.** PostHog163 ingested the framework's camelCase `$exception` for a long time and rendered164 empty, ungroupable issues — which reads as coverage, not as breakage. When165 adding or changing a backend, check what an event looks like in its UI, not166 just that the request returned 200.167- **Attribute the error.** Without a user id, server exceptions land under168 `anonymous` and split one person in two against their browser events. Pass169 `aiTraceId` for anything inside an agent run so the issue and the LLM trace170 resolve to each other.171- **Every server capture carries a failure packet** at172 `extra.failureContext` (`observability/failure-context.ts`): app, route,173 action or automation name, `threadId`, `runId`, `requestId`, `userScope`174 (`org` or `personal`, never an email), `threadUrl`175 (`https://<app host>/?thread=<chat_threads.id>`), build, environment,176 `errorCode`, `failureClass`. The boundary derives it from what the call site177 already passes (`tags.action`, `extra.runId` / `threadId` / `request_id`,178 `aiTraceId`) and from the ambient chat run, so a capture inside a run names179 its thread with no change at the call site. Work that runs outside any180 request (a scheduled automation) passes `failure: { threadId, automationName,181 userScope }` on the capture. A run id also becomes `aiTraceId`. The Analytics182 issue page links `threadUrl`; hand any agent the packet and it can run183 `get-agent-thread-debug` with the `runId`. Never put an email, a token or a184 prompt in it.185- **CLI telemetry has its own allowlist.** `@agent-native/core` and186 `@agent-native/skills` send through `packages/core/src/cli/telemetry.ts`, which187 silently drops any property missing from `CLI_TELEMETRY_PROPERTIES` in188 `telemetry-sanitize.ts`, and any string value that could hold a path, URL or189 email. Adding a CLI property means adding it there and to190 `packages/core/docs/content/telemetry.mdx`; a test fails until the page lists191 it. Pass the error itself as `error` and it is cut down to a short hint. Wrap192 a message we wrote in `KnownCliError` to report it whole. Nothing that names a193 project, a path or a person belongs in a CLI event.194- **Rates are events, not log lines.** `tracking/failure-counters.ts` counts a195 failure class per (event, bounded dimensions) and ships `count` per window196 (first occurrence at once, the rest once a minute, `SUM(count)` is exact):197 `action_error_counts` (`action_name`, `error_code`, `status_class`,198 `action_source`) and `credential_state_counts` (`credential_state`,199 `credential_subject`, `source`). Automation pauses and automatic resumes are200 `automation_paused` / `automation_resumed` (`automation_hash`, never the201 name), the client's open circuits are `action_circuit_tripped`, and a chat run202 that ended on a credential problem is a `$ai_trace` with `credential_state`.203 Attachment mint/resolve/delete outcomes (ok included) are204 `attachment_outcome_counts` (`operation`, `status`, `reason`, `who_can_fix`),205 and a template counts its own classes with `countOutcome("<thing>_counts",206 { ...tokens })` from `@agent-native/core/tracking` (Mail's Gmail cooldowns are207 `gmail_cooldown_counts`, by `site`). Never one event per failure; a name that208 is not `<thing>_counts` is dropped with one console error.209- **Browser outcomes are bounded, too.** `agent_run_outcome` is one event per210 run (`outcome`, legacy `code`, `terminal_source`,211 `verified_after_pipe_closed`, `resume_attempts`, `run_id`, `thread_id`, and212 `turn_id` when the page started the turn, except a replay whose turn the213 server did not name):214 every `interrupted` / `failed` / `unverified` run up to 30 per page, every215 `stopped` run up to its own 30 (so stops never crowd out failures), and216 `succeeded` sampled at 10% with `sample_weight`. A turn the server refuses217 at its start (no model connected, a 5xx) is a `failed` run too, with218 `terminal_source: local` and the refused turn's id. A failed or219 interrupted run adds its `cause` from `AGENT_TROUBLE_CAUSES` when one fits220 its `code`, and Analytics groups the rest by `code`. A code that is not221 an identifier is sent as `unrecognized_code` (`agentErrorCodeForTelemetry`),222 because a thrower's `data.code` can be a sentence. It never carries the223 run's message, not even redacted: no pattern can tell an unquoted document224 or person's name from the words around it, so a message stays out of every225 event. A provider error is `provider_error` only when its code226 came from a structured HTTP status (`http_5xx`, including a status on a227 wrapped cause); a status that appears only in message text is not read. `agent_feedback_submitted` (`sentiment`,228 `run_id`, `thread_id`) is the browser's copy of a thumbs rating, because229 `$ai_feedback` has no browser session. Every `pageview` carries230 `agent_signals: 1` (`AGENT_SIGNALS_PAGEVIEW_PROPERTY`): clients before it231 sampled stops at 10% and sent no ratings or `page_load_id`, so Analytics232 reads a session's cancelled runs, thumbs-down, and quick backs as measured233 only after seeing the marker and while no unmarked pageview or sampled stop234 shares the session (tabs share one session id), and counts only stops sent235 unsampled. Keep all three guarantees while the marker ships. Every236 `pageview` also carries `page_load_id` (`PAGE_LOAD_PAGEVIEW_PROPERTY`),237 the same until the page reloads, because quick backs compare pages only238 within one page load.239 `session_navigation` is one event per document that left because of the240 session (`reason`, and for `signed_out` the `evidence`: `signed_out_body` or241 `http_401`), never the destination. Both are emitted from the single place242 that decides (`agentkit-protocol.ts`, `navigateForSession`; a refused243 start from the transport's start-run catch), not the callers.244 `agent_chat_stuck_detected` fires once per run and only while the stuck245 banner shows, so Analytics' stuck chats are ones the person saw. It carries246 `reason`, `dispatchMode`, `hasInFlightWork` and `heartbeatSinceSec`, so a run247 the server still holds (a live background worker) reads differently from a248 dead one.249250Symbolication is per-backend and not automatic: the framework uploads no source251maps to PostHog, so minified browser stacks stay minified there. Known gap, not252a bug to re-diagnose.253254### Browser keys and the SSR shell255256Public keys (`POSTHOG_PUBLIC_KEY`, the Sentry client DSN, and the first-party257Analytics public key) ship inside the258CDN-cached SSR shell — publishable and identical for every visitor. Server keys259never do, and are never a fallback for a public one: `POSTHOG_API_KEY` may be a260private key and this value lands in public HTML.261262Browser errors post directly to the backend rather than through263`/_agent-native/track`, because that route requires a resolved session and264relaying would drop every signed-out crash.265266When adding a client config field, update **both** `server/posthog-config.ts`267and the mirrored worker emitter in `deploy/build.ts` — the worker bundles a268string copy and cannot import the module, so a one-sided edit drops the config269silently in deployed builds. `posthog-config.spec.ts` pins the two outputs270together.271272### Cookie consent273274Visitors in the consent region (`shared/consent.ts`, copied from builder.io's275banner rules) see `ConsentBanner`, which `AppProviders` and the docs root276mount, and choose two categories: `performance` (Google Analytics,277Amplitude, Ahrefs) and `targeting` (Google Tag Manager, attribution).278Everyone else gets no banner and every tag at once.279280- Every third-party browser tag goes through the gate: server-injected281 scripts use `consentGatedScript()` in `server/analytics.ts`; client code282 uses `whenConsentAllows(category, run)` from283 `@agent-native/core/client/consent`. A tag in a raw `<script>` or a284 `<noscript>` fallback runs before the visitor chooses.285- The GTM container (`GTM_CONTAINER_ID`, shared by every app and the docs286 site) carries the ad pixels: Meta, LinkedIn, Reddit, X, Bing UET, Google287 Ads and OpenAI, plus HubSpot, Dreamdata, Vector, Unify, Common Room and288 Apollo. Gating the container gates them all, which is why it sits under289 `targeting`. Tags added inside GTM need no code change; tags added290 anywhere else do.291- The inline bootstrap in `server/analytics.ts` runs the queue on pages that292 never load the app bundle. It repeats the cookie format and time-zone293 rules of `client/consent.ts`; change both together. Each queued loader294 runs once a page, even after a reject and a fresh accept.295- A loaded tag can't be unloaded, so Google's tags follow Consent Mode: the296 server pushes a `consent default` from the stored choice (all denied297 without one) to every Google data layer before any tag, and298 `client/consent.ts` pushes a `consent update` on each region answer and299 choice. Our own `gtag` events also wait for `performance`. Non-Google tags300 in GTM stop only on the next page load.301- Use `consentDecision(category)` for anything a revoke can't undo once302 sent; it is `null` until the visitor's choice or the server's region is303 known. `consentAllowsNow` guesses from the time zone, so only pair it with304 storage a `revoke` can clear.305- First-party analytics keeps counting in the region before consent, but the306 visitor id `an_aid` waits for `performance`: until then307 `getOrCreateAnalyticsAnonymousId()` returns `undefined` and stores nothing,308 and events go out with no `anonymousId` and309 `properties.analytics_consent: "withheld"`. Events sent before the region310 is known wait for it, or leave without the id, marked311 `analytics_consent: "unknown"`, if the page closes first. The plain312 sign-in page reads the id through the same helper and holds its events313 with `whenConsentDecided`; never write `an_aid` directly. A choice made in314 another tab applies at once in tabs of the same app, and on focus in315 another app on the site. A316 reject clears a stored id.317 Those rows count as events and views but never as people; the Analytics318 activation funnel joins them to a signup in the same session. Session319 replay waits for `performance` too, with no time-zone head start; a reject320 stops it, discards what it hasn't uploaded (including a batch an upload in321 flight puts back), and forgets its stored replay identity. Amplitude rechecks the322 choice before it initializes and never sends events from before an accept.323 Google events held for the region's answer go out only if it allows them. Sentry error capture and the session id `an_sid` aren't324 gated.325326## MCP Server Events327328The MCP server an app exposes reports its own usage. `packages/core/src/mcp/analytics.ts`329emits one event per protocol request, and the emission points sit in the shared330server builder (`build-server.ts`), so the HTTP mount and the stdio transport331report identically.332333| Event | Fires on |334| ---------------------- | --------------------------------------------- |335| `$mcp_initialize` | the client/server handshake (HTTP mount only) |336| `$mcp_tools_list` | `tools/list` |337| `$mcp_tool_call` | `tools/call`, success or failure |338| `$mcp_resources_list` | `resources/list` |339| `$mcp_resource_read` | `resources/read` |340341Names come from PostHog's MCP analytics vocabulary342(https://posthog.com/docs/mcp-analytics/events) on purpose, so PostHog's MCP343dashboards read these events with no mapping layer — but they go through344`track()` like every other event, so Mixpanel, Amplitude, a webhook, and345Agent-Native Analytics receive the same ones.346347Shared properties: `$mcp_source` (`http` / `stdio`), `$mcp_server_name`,348`$mcp_server_version`, `$mcp_app_id`, `$mcp_client_name`, `$mcp_client_version`,349`$mcp_client_user_agent`, `$mcp_vendor_client`, `$mcp_protocol_version`. Per350event: `$mcp_tool_name`, `$mcp_tool_description`, `$mcp_tool_category`351(`read` / `write`), `$mcp_listed_tool_names`, `$mcp_duration_ms`,352`$mcp_is_error`, `$mcp_error_type`, `$mcp_error_message`, `$mcp_resource_name`,353`$mcp_resource_uri`.354355- **A client's own name is only on the wire at `initialize`.** The mount is356 stateless — one server per request — so no later event can recover it.357 `$mcp_initialize` carries the `clientInfo` from the handshake; every other358 event falls back to the 2026-era per-request `_meta` and the HTTP user agent,359 and `$mcp_vendor_client` buckets both spellings onto one row.360- **A failed call is reported with its reason, not just `isError`.** The361 `tools/call` handler renders "unknown tool", "forbidden scope", and a thrown362 action error as the same shape of error result, so each sets `$mcp_error_type`363 where it returns rather than having it guessed back out of the response text.364- **Payloads stay out.** `$mcp_response` is never emitted. `$mcp_parameters` is365 off by default and redacted when on — tool arguments carry user content.366367Off switches: `MCP_ANALYTICS=false` (`observability.mcpEvents`) disables the368events; `MCP_ANALYTICS_PARAMETERS=true` (`observability.mcpCaptureParameters`)369opts into arguments. They sit in `observability` with the other capture370switches, not in `analytics` — they gate every provider, not the first-party371Agent-Native Analytics sender whose key lives there.372373## Default Baseline Events374375Template roots call `configureTracking()` once during app startup. That installs default browser pageview tracking for hosted apps:376377- Event: `pageview`378- Fires on initial load, `history.pushState`, `history.replaceState`, and `popstate`379- De-dupes repeated events for the same URL380- Includes `url`, `path`, `hostname`, `referrer`, `title`, `navigation_type`, `agent_signals`, `page_load_id`, `app`, and inferred `template`381- Includes LLM connection context on browser events when known: `llm_connection` (`builder`, `anthropic`, `openai`, etc.), `llm_engine`, `llm_model`, `llm_connection_source`, and `llm_connection_configured`382- Does not send first-party events from localhost/local dev383384### Visitor identity (`anonymousId` + `sessionId`)385386Every browser-side `trackEvent()` POST to the Agent-Native Analytics `/track` endpoint includes:387388- `anonymousId` — persistent per-browser visitor ID stored in `localStorage` under `agent-native.anonymous_id`. Generated once and reused across sessions. Use this for unique-visitor and returning-visitor metrics. In the consent region it's absent until the visitor accepts analytics cookies (see Cookie consent).389- `sessionId` — rotating per-visit ID stored in `localStorage` under `agent-native.session_id`, with a 30-minute idle timeout (matches GA4 / Mixpanel defaults). Use this for sessions-per-visitor, pages-per-session, and session-duration metrics.390- `userId` — only set when the calling code passes `properties.userId`. Anonymous traffic leaves this NULL by design; `anonymousId` is the fallback.391392These fields land in the `analytics_events.anonymous_id`, `analytics_events.session_id`, and `analytics_events.user_id` columns in the analytics template. Storage access is wrapped in try/catch — private-browsing / blocked-storage clients silently degrade to NULL rather than crashing the page.393394### Referral / viral attribution (first-touch)395396`configureTracking()` also captures an anonymous visitor's **first-touch** referral context once, on first page load, and persists it across the signup boundary so the server-side `signup` event records where the user came from. This powers virality metrics for every template (Clips share links, Plans public pages, etc.).397398There is one capture implementation, `captureAttribution()` from `@agent-native/core/client/analytics`. Every page that can be someone's first visit calls it, including the server-rendered sign-in page, which never runs `configureTracking()` and passes `{ landingPath }` so `landing_path` names the app path behind the sign-in page. Never copy the capture into a page: the sign-in page's private copy silently dropped ad click ids, site handoff fields, and last touch for every visitor who landed on it.399400**Share-link params** (set by whatever generates the link; read client-side only):401402- `ref` — referral source bucket, e.g. `clip_share`, `plan_share`403- `via` — the referrer's stable user id (the clip/plan owner)404- `utm_source`, `utm_medium`, `utm_campaign`, `utm_content`, `utm_term`405406**Client persistence** (first-write-wins, except that the first visit with a source replaces one without; last touch lives in `an_last_touch` / `an_lt`):407408- `localStorage` key `an_attribution` and first-party cookie `an_ft` (`path=/; max-age=2592000; SameSite=Lax`, not HttpOnly — non-sensitive, written by client JS).409- Both store the same URL-encoded compact JSON (empty fields omitted, each value capped at 120 chars): `{ ref, via, utm_source, utm_medium, utm_campaign, utm_content, utm_term, landing_path, landing_referrer, landed_at }`. `landing_referrer` is the **host only** of `document.referrer` (scrubbed; same-origin referrers are dropped).410- A durable copy, cookie `an_fts`, set only by our server (`POST /_agent-native/auth/attribution`, same-origin, no session needed) and expiring 365 days after `landed_at`, never extended by later visits. The browser sends its first touch there each load until the server holds that visit. Safari caps cookies written by page JavaScript at seven days, so only a server-set cookie can keep first touch for a year. The value carries `v: "1"`; a reader ignores other versions. When the browser's copies are gone, capture restores them from `an_fts`. Each sync after the browser writes `an_ft` or `an_lt` also has the server write them again from the request's cookies, so Safari keeps them their full 30 days too.411- Every copy is compared with `preferFirstTouch` (`shared/first-touch-persistence.ts`): the first visit with a source, else the first visit. Never add a second ordering rule: the server cookie route, the browser, and signup must agree on which visit is first touch, or a slow response from one tab overwrites a better touch from another.412- Attribution is a `targeting` consent category. Visitors in the consent region (builder.io's GDPR list: the EU, the rest of the EEA, Monaco, San Marino, Åland and France's overseas regions; not the UK or Switzerland, in `packages/core/src/shared/consent.ts`) get nothing stored until they opt in through the `an_consent` cookie. The banner writes `an_consent` in the page and then `POST /_agent-native/auth/consent` writes it again from the server, so Safari keeps the choice its full year. The browser gates capture with `whenConsentAllows("targeting", …)` from `client/consent.ts`, which asks `GET /_agent-native/auth/consent-region` (the request's country) and falls back to the time zone; a reject clears every copy. The server refuses `an_fts` and clears all three cookies by request country unless `an_consent` grants targeting. Everyone else is stored as before, with no banner. Don't add attribution storage that bypasses `captureAttribution()`, or it skips this check.413- `getFirstTouchAttribution()` (from `@agent-native/core/client`) returns the parsed object or `null`.414415**Signup event enrichment** (server-side, from the `an_fts` and `an_ft` cookies on the signup/OAuth-callback request, whichever `preferFirstTouch` picks, with `an_fts` winning a tie, derived in `packages/core/src/server/attribution.ts`):416417- `referral_source` — `ref` if present, else derived: `/share/…` → `clip_share`; a plan public path (`/p/`, `/plan/`, `/share-plan/`) → `plan_share`; a non-empty external referring host → `external`; otherwise `direct`.418- `referrer_user` (= `via`), `referral_medium` (= `utm_medium`), `referral_campaign` (= `utm_campaign`)419- `utm_source`, `utm_medium`, `utm_campaign`, `utm_content`, `utm_term` (raw passthrough)420- `first_touch_path` (= `landing_path`), `landing_referrer`421422Attribution parsing is fully defensive and never blocks signup — a missing/malformed cookie falls back to `referral_source: "direct"`.423424Other framework-level baseline events:425426- `session status` from `useSession()`, with `signed_in`427- `action.response` from the browser action transport, with action name,428 the `route` template of the page that made the request (omitted when no429 manifest route matches),430 browser-perceived duration and TTFB, response status/outcome, response size431 when known, and parsed `Server-Timing` phases for framework readiness and432 database work. Its `request_id` joins the exact browser and server events.433 This separates server time from CDN/network/body overhead. One at or over434 `SLOW_ACTION_RESPONSE_MS` (1 s) is never sampled. When someone waited for435 it (`isWaitedActionResponse`: the page stayed visible and the request was436 not cancelled), it is also marked on the session replay437 (`agent-native.slow_request`) with its action, method, duration, status,438 outcome, and `page_hidden`.439- `web_vitals` once per page view, with the React Router `route` template440 (`/sessions/:id`, never the ids; omitted when no manifest route matches,441 because a normalized raw path still carries slugs and emails. It is the one442 tracked event with no `url` or `path`, even from `getDefaultProps`:443 `ROUTE_ONLY_EVENT_NAMES` in `client/analytics.ts` strips them),444 `navigation_type` (`load`, `client`, or `resume` after the tab was445 hidden, sent only when it saw an interaction or layout shift), and446 `ttfb_ms`, `lcp_ms`, `inp_ms`, and `cls`. TTFB and LCP exist only for447 document loads, a load in a background tab is not reported, and a metric the browser cannot measure (including CLS when448 the layout-shift observer fails) is omitted rather than sent as 0. A page449 view ends on `pushState`/`popstate` to another path or when the tab is450 hidden; `replaceState` keeps it, so redirects land on the final route.451 Measured with native `PerformanceObserver`s; `configureTracking({452 webVitals: false })` turns it off. Each page view also marks the replay.453- Request timing is an OpenTelemetry `http.server` span, not a product event. Each454 framework HTTP request records method, bounded route template, status code,455 first-request-in-isolate cold marker, framework readiness wait, and database456 operation count and wall time. The span goes only to the registered457 OpenTelemetry provider and never reaches analytics providers, so it cannot458 fire product alerts. Its status is `error` for 5xx responses only. Ingest459 endpoints, `/api/analytics/replay`, and `AGENT_NATIVE_HTTP_TELEMETRY_DISABLED`460 record no span. Cold or 1 s-plus requests also write an461 `agent-native.slow_request` log line with process age, readiness wait, and462 database timings. Responses carry `Server-Timing` for `app`, `startup`, `db`,463 `db-connect`, and `db-slowest` (plus `startup-db-*` for initialization464 database work) and an `X-Agent-Native-Request-Id` header where applicable.465 Query text and parameters are never captured. There is no sampling knob for466 this span; export volume is governed by the OpenTelemetry sampler.467- `signup` from Better Auth user creation, with `auth_provider`, `auth_user_id`, and first-touch referral attribution (`referral_source`, `referrer_user`, `referral_medium`, `referral_campaign`, `utm_*`, `first_touch_path`, `landing_referrer` — see "Referral / viral attribution" above)468- `builder connect clicked` and `builder connect popup blocked` from browser Use Builder.io CTAs469- `builder connect started`, `builder connect succeeded`, `builder connect failed`, `builder disconnect succeeded`, and `builder disconnect failed` from the Builder connection routes, with LLM connection context when resolvable470- `$ai_generation` from instrumented agent loops, with PostHog AI Observability fields such as `$ai_trace_id`, `$ai_session_id`, `$ai_model`, `$ai_provider`, `$ai_input_tokens`, `$ai_output_tokens`, `$ai_latency`, `$ai_total_cost_usd`, and mirrored Agent-Native query fields such as `run_id`, `thread_id`, `turn_id`, `cost_cents_x100`, `duration_ms`, `tool_calls`, and `status`. A bounded `tools` array contains names, start offsets, durations, statuses, and coarse error classes only; interrupted tools and failed runs remain visible, and delegated runs include protocol/task/parent-run/parent-turn correlation. Run failure messages are omitted from every tracking provider even with content capture enabled. `$ai_error` carries a fixed message derived from `terminal_code`, a named `cause`, terminal state, and retryability. The `error_message` field and tool error output text are absent. Local trace SQL retains debugging detail under the observability capture settings.471- `agent_run_terminal` is one event per run: from the run's own process, or from the SQL write that ended it for that process (a reap with `reaped: true`, `reap_source`, `recovery_outcome`; a stop with `status: "aborted"` and `abort_reason`; the reaper's repair from the event log; a run that fails or is released before its worker starts). Not sent yet: a background chunk that hands off to a continuation, and a run the production agent marks errored before its run loop starts (a preparation, history or dispatch failure). A row aborted as `duplicate_submission` or `execution-lease-busy` stood in for another run and sends none. An event sent from a SQL write has no `model`, `engine` or `attempt_count`, since only the run's process knows them; every reported aborted run is sent this way. It carries `turn_id` and the run's user (the turn's initiator when a SQL write ended it, never the request that ended it; none for an anonymous visitor). `run_started` also carries `turn_id`.472- `agent_turn_submitted` is one browser event per agent request the server accepts (not on send, so a busy-slot refusal then queue counts once; a replay is not counted, including a retry the server answers with the run it already started), with the `turn_id` the server stores on the run, `initiator` (`user`, `app` for `sendToAgentChat` including a send deferred while the thread restored, `system` for continuations, recoveries, approvals, setup replays and background sends), `surface`, and `submit_message_id` / `recovery_of_run_id` when present. Continuations repeat the turn's `turn_id` as `system`, so count turns by distinct `turn_id`. A send routed to Builder or an MCP host is reported once with `routed_to` and no `turn_id`, also when the host has not confirmed it. A queued message the server's inbox drain admits sends no `agent_turn_submitted` yet; its run still reports `agent_run_terminal` with `turn_id` `queued-<message id>`. A queued message the browser promotes is counted.473- `agent_run_terminal` carries `error_code` and `error_cause`, never `error_detail`. Run and completion captures, and Builder gateway failures, use `captureError(..., { errorMessagePolicy: "omit" })`: providers receive the original exception type, stack frames without the original message header or nested causes, and a fixed `Internal Server Error` message. Noise filtering still sees the original failure; flood summaries use the fixed label. Monitoring groups by app, type, frame, error code, and failure class instead of user-specific message wording.474475For new lifecycle events, call `track()` server-side when the server is the source of truth, and `trackEvent()` client-side only for browser interactions.476477### Lifecycle taxonomy478479Lifecycle event names use lowercase `snake_case`; lifecycle properties use the480same convention. The shared dimensions are `app_name`, `template_name`,481`user_id`, `user_email`, `workspace_id`, `session_id`, `output_id`,482`output_type`, `source`, and `referrer`. App/template values are canonical ids483without the `agent-native-` prefix. Identity is also stored in the event's484top-level user/session columns for joins.485486The canonical lifecycle events are `app_entered`, `core_action_started`,487`core_action_completed`, `core_action_failed`, `output_viewed`,488`output_shared`, `cta_clicked`, `return_usage`, and `cross_app_used`. The489framework also emits `action_started`, `action_completed`, and490`action_failed` for mutating `defineAction()` calls so UI, agent, MCP, A2A,491automation, and CLI activity share one action-level trail. Read-only actions492and high-frequency refresh, polling, navigation, and application-state actions493are excluded.494495App entry is emitted once per app and browser session. Tracking is action-level496only: it does not install mouse, pointer, scroll, keypress, or DOM autocapture.497Existing legacy events remain available and emit their canonical lifecycle498counterpart where the meaning is unambiguous, so downstream dashboards can499migrate without losing historical names.500501### Event name migration502503All new event names and properties use lowercase `snake_case`. The shared504`track()` and browser `trackEvent()` emitters preserve a legacy event exactly505and, for names in `LEGACY_TRACKING_EVENT_NAME_ALIASES`, emit a canonical alias506with `legacy_event_name` and `canonical_event_name` provenance properties. Use507the canonical alias for new dashboards and new call sites; do not normalize508historical warehouse rows or add new legacy names. Provider/framework names509such as `$ai_*`, `$mcp_*`, `$exception`, `action.response`, and510`app.first_action` are intentional exceptions.511512## Provider Interface513514```ts515interface TrackingProvider {516 name: string;517 track(event: TrackingEvent): void | Promise<void>;518 identify?(519 userId: string,520 traits?: Record<string, unknown>,521 ): void | Promise<void>;522 flush?(): void | Promise<void>;523}524525interface TrackingEvent {526 name: string;527 properties?: Record<string, unknown>;528 timestamp?: string;529 userId?: string;530}531```532533## Design Decisions534535- **globalThis singleton** -- the registry uses a `Symbol.for` key on globalThis so multiple ESM graph instances (dev-mode Vite + Nitro, symlinks) share one provider set.536- **Best-effort fan-out** -- provider errors are caught and logged, never propagated. A broken analytics integration must not break app functionality.537- **Batched HTTP** -- built-in providers enqueue events and flush every 10 seconds or 50 events, minimizing outbound requests.538- **NOT bridged to the event bus** -- tracking and the event bus are separate concerns. The event bus is for triggering automations; tracking is for analytics. Do not subscribe to `track()` calls from the event bus or vice versa.539540## Key Files541542| File | Purpose |543| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |544| `packages/core/src/tracking/registry.ts` | `track()`, `identify()`, `registerTrackingProvider()`, `flushTracking()` |545| `packages/core/src/tracking/providers.ts` | Built-in providers (PostHog, Mixpanel, Amplitude, Agent-Native Analytics, Webhook) and `registerBuiltinProviders()` |546| `packages/core/src/tracking/types.ts` | `TrackingEvent` and `TrackingProvider` interfaces |547| `packages/core/src/tracking/posthog-exception.ts` | `$exception_list` builder + stack-frame parser (isomorphic: server and browser) |548| `packages/core/src/tracking/redaction.ts` | Shared bounding/redaction helpers used by every exception emitter |549| `packages/core/src/shared/error-noise.ts` | The one noise rule set (`classifyErrorNoise`) plus frame-origin and PII scrubbers; browser, server, Sentry, and ingest all call it |550| `packages/core/src/server/error-noise-filter.ts` | Provider-agnostic drop rules, applied by 551552…(truncated)