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

2.5 KB
Raw Blame
/**
 * Messages usage events for the CLI and the Mac app, which shells out to it.
 * Counts and closed enums only. Chat names, phone numbers and message text
 * never reach this file's callers as event properties.
 */
import { captureCliEvent } from '../../services/telemetry/cli-telemetry.js';
import { createHarnessWorkerClient } from '../../integrations/harness-worker.js';
import {
  MESSAGES_TELEMETRY_ROUTE,
  messageAccess,
  messagesSelectionCounts,
  messagesWindowProperties,
  type ChatDbFailureReason,
  type MessageSource,
  type MessagesEvent,
} from '../../services/telemetry/usage.js';
import type { WindowUsage } from '../../integrations/imessage-observer/worker-sink.js';

let relayThroughWorker = false;

/**
 * Called by the Mac app's helper (integrations/imessage-mac/observer). The app
 * starts it with only HOME, TMPDIR, PATH and NO_COLOR (CommandRunner.swift), so
 * DO_NOT_TRACK, CLAUDE_MEM_TELEMETRY and CLAUDE_MEM_DATA_DIR never reach its own
 * consent check. Its events go to the worker instead, whose consent gate runs
 * with the user's real environment and data directory.
 */
export function relayMessagesTelemetryThroughWorker(enabled = true): void {
  relayThroughWorker = enabled;
}

export function recordMessages(event: MessagesEvent, properties: Record<string, string | number | boolean>): void {
  if (!relayThroughWorker) {
    void captureCliEvent(event, properties);
    return;
  }
  // One attempt, never started for this: with no worker reachable the event is
  // dropped, not queued or retried.
  createHarnessWorkerClient({ startIfNeeded: false })
    .post(MESSAGES_TELEMETRY_ROUTE, { event, properties })
    .catch(() => { /* Telemetry must never break or slow the observer. */ });
}

export function recordMessageWindow(source: MessageSource): (usage: WindowUsage) => void {
  return usage => recordMessages('messages_window', messagesWindowProperties(usage, source));
}

export function recordMessagesChecked(
  source: MessageSource,
  accessOk: boolean,
  reason: ChatDbFailureReason | undefined,
  workerReachable: boolean,
): void {
  recordMessages('messages_checked', {
    source,
    access: messageAccess(reason, accessOk),
    worker_reachable: workerReachable,
    outcome: accessOk ? 'ok' : 'error',
  });
}

/** Chat ids are counted here and then dropped. */
export function selectionProperties(
  guids: readonly string[],
  hasFocus: (guid: string) => boolean,
  hasDefaultFocus: boolean,
): Record<string, number | boolean> {
  return {
    ...messagesSelectionCounts(guids, hasFocus),
    has_default_focus: hasDefaultFocus,
  };
}