@mastra/core
Version:
224 lines (223 loc) • 8.05 kB
JavaScript
import { z } from "zod/v4";
import { createHash } from "crypto";
import os from "os";
import { PostHog } from "posthog-node";
import { execFile } from "child_process";
// src/telemetry/posthog.ts
const POSTHOG_API_KEY = "phc_SBLpZVAB6jmHOct9CABq3PF0Yn5FU3G2FgT4xUr2XrT";
const POSTHOG_HOST = "https://us.posthog.com";
const TRUTHY_DISABLED_VALUES = /* @__PURE__ */ new Set([
"1",
"true",
"yes"
]);
let client = null;
function isTelemetryEnabled() {
const value = process.env["MASTRA_TELEMETRY_DISABLED"];
if (!value) return true;
return !TRUTHY_DISABLED_VALUES.has(value.trim().toLowerCase());
}
function hashTelemetryValue(value) {
return createHash("sha256").update(value).digest("hex");
}
function getHashedHostname() {
return hashTelemetryValue(os.hostname() || "unknown-host").slice(0, 16);
}
function getEETelemetryFallbackDistinctId() {
return `mastra-${getHashedHostname()}`;
}
function getClient() {
if (!isTelemetryEnabled()) return null;
if (!client) client = new PostHog(POSTHOG_API_KEY, {
host: POSTHOG_HOST,
flushAt: 1,
flushInterval: 0,
disableGeoip: false
});
return client;
}
function getSystemProperties() {
return {
os: process.platform,
os_version: os.release(),
node_version: process.version,
platform: process.arch,
machine_id: getHashedHostname(),
mastra_version: process.env["npm_package_version"] || "unknown"
};
}
function buildMessage(event, distinctId, properties) {
return {
distinctId: distinctId || getEETelemetryFallbackDistinctId(),
event,
properties: {
...getSystemProperties(),
...properties
}
};
}
function captureTelemetryEvent(event, distinctId, properties) {
try {
getClient()?.capture(buildMessage(event, distinctId, properties));
} catch {}
}
/**
* Sends the event right away and resolves once the request has finished, so callers
* can wait for delivery before the process exits. Never rejects: PostHog retries
* failed requests internally and reports what still fails through its own error
* channel.
*/
async function captureTelemetryEventImmediate(event, distinctId, properties) {
try {
await getClient()?.captureImmediate(buildMessage(event, distinctId, properties));
} catch {}
}
// src/telemetry/context.ts
const platformProjectIdSchema = z.uuid();
let cachedGitProjectId2;
function normalizeGitRemote(remote) {
try {
if (/^(?:[a-z]:[\\/]|file:)/i.test(remote)) return void 0;
const scpRemote = /^(?:[^/@:\s]+@)?(\[[^\]]+\]|[^/:\s]+):(.+)$/.exec(remote);
const url = new URL(!remote.includes("://") && scpRemote ? `ssh://${scpRemote[1]}/${scpRemote[2]}` : remote);
if (![
"https:",
"http:",
"ssh:",
"git:",
"git+ssh:"
].includes(url.protocol) || !url.hostname) return;
const repositoryPath = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/, "");
return repositoryPath ? `${url.hostname.toLowerCase()}/${repositoryPath}` : void 0;
} catch {
return;
}
}
async function computeGitProjectId2() {
try {
const normalizedRemote = normalizeGitRemote((await new Promise((resolve, reject) => {
execFile("git", [
"remote",
"get-url",
"origin"
], {
cwd: process.env.MASTRA_PROJECT_ROOT || process.cwd(),
encoding: "utf-8",
timeout: 2e3,
maxBuffer: 4096
}, (error, stdout) => {
if (error) reject(error);
else resolve(stdout);
});
})).trim());
return normalizedRemote ? hashTelemetryValue(normalizedRemote).slice(0, 16) : void 0;
} catch {
return;
}
}
/**
* Preserves UUID-shaped Platform project IDs for direct telemetry lookup.
* Other values fall back to a hash of the normalized Git origin, if available.
*/
async function resolveProjectId2() {
const platformProjectId = platformProjectIdSchema.safeParse(process.env.MASTRA_PROJECT_ID?.trim());
if (platformProjectId.success) return `mp_${platformProjectId.data}`;
cachedGitProjectId2 ??= computeGitProjectId2();
return cachedGitProjectId2;
}
async function getServerTelemetryContext() {
return {
projectId: hashTelemetryValue(process.env.MASTRA_PROJECT_ROOT || process.cwd()).slice(0, 16),
distinctId: process.env.MASTRA_CLI_DISTINCT_ID || void 0,
command: process.env.MASTRA_TELEMETRY_COMMAND || "server",
nodeEnv: process.env.NODE_ENV || "development",
projectId2: await resolveProjectId2()
};
}
// src/telemetry/feature-telemetry.ts
const FEATURE_USAGE_EVENT = "mastra_feature_usage";
function countCollection(collection) {
if (!collection || typeof collection !== "object") return 0;
if (collection instanceof Map || collection instanceof Set) return collection.size;
return Object.keys(collection).length;
}
function countAgentsWithMemory(agents) {
if (!agents || typeof agents !== "object") return 0;
return Object.values(agents).filter((agent) => {
try {
return agent?.hasOwnMemory?.() === true;
} catch {
return false;
}
}).length;
}
function bucketStorageType(storage) {
if (!storage) return null;
const constructorName = storage.constructor?.name?.toLowerCase();
if (!constructorName) return "unknown";
if (constructorName.includes("memory")) return "in-memory";
if (constructorName.includes("libsql")) return "libsql";
if (constructorName.includes("postgres")) return "postgres";
if (constructorName.includes("mongo")) return "mongo";
if (constructorName.includes("upstash")) return "upstash";
if (constructorName.includes("dynamodb")) return "dynamodb";
if (constructorName.includes("redis")) return "redis";
return "unknown";
}
function trackFeatureUsage(name, metadata) {
try {
if (!isTelemetryEnabled()) return;
const safeMetadata = { ...metadata };
delete safeMetadata.project_id2;
getServerTelemetryContext().then(({ projectId, projectId2, distinctId, command, nodeEnv }) => {
captureTelemetryEvent(FEATURE_USAGE_EVENT, distinctId, {
...safeMetadata,
feature_name: name,
project_id: projectId,
...projectId2 ? { project_id2: projectId2 } : {},
command,
node_env: nodeEnv
});
}).catch(() => {});
} catch {}
}
function syncFeatureUsageTelemetry(mastra) {
try {
if (!isTelemetryEnabled()) return;
const agents = mastra.listAgents?.();
const agentsWithMemoryCount = countAgentsWithMemory(agents);
const memory = mastra.listMemory?.();
const workspaces = mastra.listWorkspaces?.();
const tts = mastra.getTTS?.();
const promptBlocks = mastra.listPromptBlocks?.();
const processorConfigurations = mastra.listProcessorConfigurations?.();
const agentChannels = mastra.getChannels?.();
const storage = mastra.getStorage?.();
trackFeatureUsage("mastra_instance_summary", {
agent_count: countCollection(agents),
agents_with_memory_count: agentsWithMemoryCount,
agent_controller_count: countCollection(mastra.listAgentControllers?.()),
workflow_count: countCollection(mastra.listWorkflows?.()),
tool_count: countCollection(mastra.listTools?.()),
processor_count: countCollection(mastra.listProcessors?.()),
processor_configuration_count: countCollection(processorConfigurations),
memory_count: countCollection(memory),
vector_count: countCollection(mastra.listVectors?.()),
scorer_count: countCollection(mastra.listScorers?.()),
workspace_count: countCollection(workspaces),
mcp_server_count: countCollection(mastra.listMCPServers?.()),
gateway_count: countCollection(mastra.listGateways?.()),
channel_count: countCollection(mastra.getChannelProviders?.()),
agent_channel_count: countCollection(agentChannels),
tts_count: countCollection(tts),
prompt_block_count: countCollection(promptBlocks),
editor_enabled: !!mastra.getEditor?.(),
studio_enabled: !!mastra.getStudio?.(),
server_middleware_enabled: !!mastra.getServerMiddleware?.(),
storage_type: bucketStorageType(storage),
observability_enabled: !!storage?.stores?.observability
});
} catch {}
}
export { captureTelemetryEvent as a, getServerTelemetryContext as i, syncFeatureUsageTelemetry as n, captureTelemetryEventImmediate as o, trackFeatureUsage as r, isTelemetryEnabled as s, FEATURE_USAGE_EVENT as t };
//# sourceMappingURL=feature-telemetry-DdR8J_5o.js.map