Skip to content

Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More

4.6 KB
Raw Blame
/**
 * Constants and base properties shared by the two telemetry transports:
 * the worker-resident posthog-node client (telemetry.ts) and the short-lived
 * CLI direct-POST capture (cli-telemetry.ts).
 */

import os from 'os';
import { logger } from '../../utils/logger.js';

declare const __DEFAULT_PACKAGE_VERSION__: string;
const packageVersion =
  typeof __DEFAULT_PACKAGE_VERSION__ !== 'undefined' ? __DEFAULT_PACKAGE_VERSION__ : '0.0.0-dev';

/**
 * Publishable PostHog project token (phc_...). Publishable tokens are safe to
 * embed: the capture endpoints are public POST-only ingestion.
 * `CLAUDE_MEM_TELEMETRY_KEY` always overrides this constant.
 */
export const TELEMETRY_PUBLIC_KEY = 'phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG';

export const DEFAULT_TELEMETRY_HOST = 'https://us.i.posthog.com';

/**
 * How long the worker's shutdown waits for its telemetry client to flush (telemetry.ts flushClientWithTimeout), so a
 * slow or unreachable ingestion host can never hang a worker stop. It lives here, not in telemetry.ts, because a caller
 * that waits for the worker to exit counts it (WORKER_EXIT_WAIT_MS, services/install/shutdown-helper.ts) and runs in
 * the CLI, which does not bundle the worker's posthog-node client.
 */
export const TELEMETRY_SHUTDOWN_FLUSH_TIMEOUT_MS = 3000;

export function getTelemetryApiKey(): string {
  return process.env.CLAUDE_MEM_TELEMETRY_KEY || TELEMETRY_PUBLIC_KEY;
}

export function getTelemetryHost(): string {
  return process.env.CLAUDE_MEM_TELEMETRY_HOST || DEFAULT_TELEMETRY_HOST;
}

/**
 * Epoch columns hold mixed units historically: a few hundred legacy rows were
 * written in seconds, everything since in milliseconds. Normalize to ms in SQL
 * before any date math (10^12 ms ≈ 2001, 10^12 s ≈ year 33658 — no plausible
 * value is ambiguous). Must be applied INSIDE aggregate functions like MIN,
 * never outside.
 */
export function asMs(col: string): string {
  return `CASE WHEN ${col} < 1000000000000 THEN ${col} * 1000 ELSE ${col} END`;
}

/**
 * Whitelisted properties that may also be set as PostHog person properties on
 * lifecycle events (install_*, worker_started). The "person" is the anonymous
 * install UUID — these traits make retention/cohort insights sliceable by
 * platform and product choices. Strict subset of the scrub whitelist.
 */
export const PERSON_PROPERTY_KEYS = [
  'version',
  'os',
  'os_version',
  'is_wsl',
  'arch',
  'runtime',
  'locale',
  'ide',
  'provider',
  'runtime_mode',
  'install_method',
  'claude_code_version',
  // Inferred install day (YYYY-MM-DD) from the one-time historical backfill's
  // install_inferred event — anchors the adoption curve for installs that
  // predate telemetry.
  'first_active_date',
  // Install snapshot (refreshed by the daily worker_started heartbeat) —
  // lets cohorts slice by install scale, age, and activity.
  'db_observation_count',
  'db_session_count',
  'db_summary_count',
  'db_project_count',
  'db_size_mb',
  'install_age_days',
  'obs_count_7d',
  'obs_count_30d',
  'days_since_last_obs',
] as const;

/**
 * Splits already-scrubbed properties into a $set object for person-profile
 * events. Lifecycle events are low-volume (~1-2/day/install), so the
 * person-profile ingestion cost is bounded while unlocking PostHog's native
 * retention, stickiness, lifecycle, and cohort insights.
 */
export function buildPersonSet(
  scrubbed: Record<string, unknown>
): Record<string, unknown> {
  const set: Record<string, unknown> = {};
  for (const key of PERSON_PROPERTY_KEYS) {
    if (scrubbed[key] !== undefined) set[key] = scrubbed[key];
  }
  return set;
}

function detectWsl(): boolean {
  if (process.platform !== 'linux') return false;
  try {
    return Boolean(process.env.WSL_DISTRO_NAME) || os.release().toLowerCase().includes('microsoft');
  } catch (error) {
    const err = error instanceof Error ? error : new Error(String(error));
    logger.warn('SYSTEM', 'Telemetry: WSL detection failed; reporting is_wsl=false', undefined, err);
    return false;
  }
}

export function buildBaseProperties(): Record<string, unknown> {
  return {
    version: packageVersion,
    os: process.platform,
    // Kernel release: "10.0.22631" distinguishes Win10/Win11 builds, Darwin
    // major maps to the macOS release, Linux gives the kernel. os.release()
    // does not throw. System metadata only — never user data.
    os_version: os.release(),
    is_wsl: detectWsl(),
    arch: process.arch,
    runtime: process.versions.bun ? 'bun' : 'node',
    runtime_version: process.versions.bun ?? process.versions.node,
    node_version: process.versions.node,
    is_ci: Boolean(process.env.CI),
    locale: Intl.DateTimeFormat().resolvedOptions().locale,
  };
}