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

15.4 KB
Raw Blame
/**
 * Usage-shape telemetry for features that had no event of their own.
 *
 * Pure on purpose: the worker calls captureEvent, the CLI and MCP server call
 * captureCliEvent. This module never imports the PostHog client, so the MCP
 * bundle does not grow by the SDK. Every value is a count, a boolean, or a
 * closed enum. Names, questions, prompts, paths, phone numbers and message
 * text are not parameters here, so they cannot be sent.
 */
import type { ChatDbAccess } from '../../integrations/imessage-observer/chatdb.js';
import type { WindowUsage } from '../../integrations/imessage-observer/worker-sink.js';

export const CORPUS_ACTIONS = ['build', 'list', 'get', 'delete', 'rebuild', 'prime', 'query', 'reprime'] as const;
export type CorpusAction = (typeof CORPUS_ACTIONS)[number];

const OBSERVATION_TYPES = ['bugfix', 'discovery', 'decision', 'refactor'] as const;

export interface CorpusFilterShape {
  project?: string;
  types?: readonly string[];
  concepts?: readonly string[];
  files?: readonly string[];
  query?: string;
  date_start?: string;
  date_end?: string;
  limit?: number;
}

export interface CorpusUsageInput {
  action: CorpusAction;
  /** HTTP status the caller was given. 0 when the client left before an answer. */
  status: number;
  disconnected?: boolean;
  durationMs: number;
  transport?: 'json' | 'sse';
  /** Presence and lengths only. The strings themselves are never copied out. */
  filter?: CorpusFilterShape;
  hasDescription?: boolean;
  observationCount?: number;
  tokenEstimate?: number;
  typeBreakdown?: Record<string, number>;
  wasPrimed?: boolean;
  forced?: boolean;
  /** Set only when a rebuild was refused for shrinking the corpus. */
  shrinkRefused?: boolean;
  /** AppError code, mapped to a closed category. The code string is not sent. */
  failureCode?: string;
  previousObservationCount?: number;
  resultCount?: number;
  primedCount?: number;
  observationsSent?: number;
  observationsMatching?: number;
  observationsInCorpus?: number;
  observationsTruncated?: number;
  /** Character count of the question, never the question. */
  questionChars?: number;
}

function finite(value: number | undefined): value is number {
  return typeof value === 'number' && Number.isFinite(value);
}

function questionLength(chars: number): 'short' | 'medium' | 'long' {
  if (chars <= 80) return 'short';
  if (chars <= 400) return 'medium';
  return 'long';
}

/** Whole days between two date strings. Unparseable input is omitted, not sent. */
function dateSpanDays(start: string | undefined, end: string | undefined): number | undefined {
  if (!start || !end) return undefined;
  const from = Date.parse(start);
  const to = Date.parse(end);
  if (!Number.isFinite(from) || !Number.isFinite(to)) return undefined;
  return Math.max(0, Math.round(Math.abs(to - from) / 86_400_000));
}

function corpusOutcome(input: CorpusUsageInput): 'ok' | 'error' | 'aborted' {
  if (input.disconnected || input.status === 504) return 'aborted';
  if (input.status >= 200 && input.status < 300) return 'ok';
  return 'error';
}

function corpusErrorCategory(input: CorpusUsageInput): string | undefined {
  if (input.disconnected) return 'disconnect';
  if (input.status === 504) return 'timeout';
  if (input.status >= 200 && input.status < 300) return undefined;
  if (input.status === 404) return 'not_found';
  if (input.status === 403) return 'forbidden';
  if (input.failureCode === 'CORPUS_NOT_PRIMED') return 'not_primed';
  if (input.failureCode === 'CLAUDE_CLI_SETUP_REQUIRED' || input.status === 424) return 'setup';
  if (input.status === 409) return input.shrinkRefused ? 'shrink' : 'busy';
  if (input.status === 400) return 'validation';
  if (input.status >= 500) return 'provider';
  return 'unknown';
}

/** Properties for one `corpus_used` event. Filter text stays on the machine. */
export function corpusUsageProperties(input: CorpusUsageInput): Record<string, string | number | boolean> {
  const props: Record<string, string | number | boolean> = {
    corpus_action: input.action,
    outcome: corpusOutcome(input),
    duration_ms: Math.max(0, Math.round(input.durationMs)),
  };
  const category = corpusErrorCategory(input);
  if (category) props.error_category = category;
  if (input.transport) props.transport = input.transport;
  const filter = input.filter;
  if (filter) {
    props.has_project = Boolean(filter.project);
    props.has_types = (filter.types?.length ?? 0) > 0;
    props.has_concepts = (filter.concepts?.length ?? 0) > 0;
    props.has_files = (filter.files?.length ?? 0) > 0;
    props.has_query = Boolean(filter.query);
    props.has_date_range = Boolean(filter.date_start || filter.date_end);
    if ((filter.types?.length ?? 0) > 0) props.type_count = filter.types!.length;
    if ((filter.concepts?.length ?? 0) > 0) props.concept_count = filter.concepts!.length;
    if ((filter.files?.length ?? 0) > 0) props.file_count = filter.files!.length;
    if (finite(filter.limit)) props.requested_limit = filter.limit;
    const span = dateSpanDays(filter.date_start, filter.date_end);
    if (span !== undefined) props.timeline_depth_days = span;
  }
  if (input.hasDescription !== undefined) props.has_description = input.hasDescription;
  if (finite(input.observationCount)) props.observation_count = input.observationCount;
  if (finite(input.tokenEstimate)) props.token_estimate = input.tokenEstimate;
  if (input.wasPrimed !== undefined) props.was_primed = input.wasPrimed;
  if (input.forced !== undefined) props.forced = input.forced;
  if (finite(input.previousObservationCount)) props.previous_observation_count = input.previousObservationCount;
  if (finite(input.resultCount)) props.result_count = input.resultCount;
  if (finite(input.primedCount)) props.primed_count = input.primedCount;
  if (finite(input.observationsSent)) props.observations_sent = input.observationsSent;
  if (finite(input.observationsMatching)) props.observations_matching = input.observationsMatching;
  if (finite(input.observationsInCorpus)) props.observations_in_corpus = input.observationsInCorpus;
  if (finite(input.observationsTruncated)) props.observations_truncated = input.observationsTruncated;
  if (finite(input.questionChars)) props.question_length = questionLength(input.questionChars);
  if (input.typeBreakdown) {
    const buckets = { bugfix: 0, discovery: 0, decision: 0, refactor: 0, other: 0 };
    for (const [type, count] of Object.entries(input.typeBreakdown)) {
      if (!finite(count) || count <= 0) continue;
      if ((OBSERVATION_TYPES as readonly string[]).includes(type)) buckets[type as typeof OBSERVATION_TYPES[number]] += count;
      else buckets.other += count;
    }
    props.obs_type_bugfix = buckets.bugfix;
    props.obs_type_discovery = buckets.discovery;
    props.obs_type_decision = buckets.decision;
    props.obs_type_refactor = buckets.refactor;
    props.obs_type_other = buckets.other;
  }
  return props;
}

/** MCP tools the server advertises. Anything else collapses to `other`. */
export const MCP_TOOL_FEATURES = [
  'work_state_write', 'dumb_search', 'save_memory', 'important_workflow', 'search', 'timeline',
  'get_observations', 'get_tool_uses', 'get_review_stack', 'import_review_cards', 'work_state_read',
  'team_brief', 'team_search', 'session_start_context', 'observation_add', 'observation_record_event',
  'observation_search', 'observation_context', 'observation_generation_status', 'smart_search',
  'smart_unfold', 'smart_outline', 'build_corpus', 'list_corpora', 'prime_corpus', 'query_corpus',
  'rebuild_corpus', 'reprime_corpus',
] as const;

const MCP_TOOL_FEATURE_SET = new Set<string>(MCP_TOOL_FEATURES);

export function mcpToolFeature(name: string): string {
  return MCP_TOOL_FEATURE_SET.has(name) ? name : 'other';
}

/**
 * CLI verbs a person runs. Hook-fired and already-instrumented verbs are
 * omitted so a SessionStart `start` or an install does not double-count.
 */
const CLI_ALIASES: Record<string, string> = {
  upgrade: 'update',
  remove: 'uninstall',
  t3: 't3code',
  't3-code': 't3code',
  't3code': 't3code',
};

const CLI_SKIP = new Set([
  '', 'install', 'update', 'uninstall', 'hook', 'start', 'telemetry', 'version', 'help',
  '--version', '-v', '--help', '-h',
]);

const CLI_COMMANDS = new Set([
  'repair', 'stop', 'restart', 'status', 'doctor', 'prune', 'teambrain', 'server',
  'antigravity-cli', 't3code', 'pi', 'gemini', 'kimi', 'hermes', 'imessage', 'aider',
  'devin', 'zcode', 'mcode', 'muse-code', 'atomcode', 'grok', 'worker', 'search', 'mcp', 'adopt',
  'project', 'cleanup', 'backup', 'restore', 'transcript', 'memory', 'messages', 'sync', 'import',
]);

export function cliCommandFeature(command: string): string | null {
  const name = CLI_ALIASES[command] ?? command;
  if (CLI_SKIP.has(name) || CLI_SKIP.has(command)) return null;
  return CLI_COMMANDS.has(name) ? name : null;
}

/**
 * Worker routes that are a feature of their own. Capture, search, corpus,
 * setup, work-state and the viewer page counter already have events, so
 * those paths return null. Polling GETs that only fill a page the viewer
 * already counted are omitted too.
 */
export function workerFeature(method: string, path: string): string | null {
  const verb = method.toUpperCase();
  const route = path.split('?')[0];
  if (
    route.startsWith('/api/sessions/init')
    || route.startsWith('/api/sessions/observations')
    || route.startsWith('/api/sessions/summarize')
    || route.startsWith('/api/sessions/session-end')
    || route.startsWith('/api/sessions/native-prompt')
    || route.startsWith('/api/search')
    || route.startsWith('/api/corpus')
    || route.startsWith('/api/spool')
    || route.startsWith('/api/setup')
    || route.startsWith('/api/work-state')
    || route === '/api/context/inject'
    || route === '/api/work-view/usage'
  ) return null;

  if (verb === 'POST' && route === '/api/settings') return 'settings';
  if (verb === 'POST' && route === '/api/mcp/toggle') return 'mcp_toggle';
  if (verb === 'POST' && route === '/api/memory/save') return 'memory_save';
  if (verb === 'POST' && route === '/api/memory/ingest') return 'memory_ingest';
  if (verb === 'POST' && route === '/api/import') return 'memory_import';
  if (verb === 'POST' && route === '/api/backup/run') return 'backup';
  if (verb === 'POST' && route === '/api/dedup/scan') return 'dedup_scan';
  if (verb === 'POST' && /^\/api\/dedup\/candidates\/[^/]+\/resolve$/.test(route)) return 'dedup_resolve';
  if (verb === 'POST' && route === '/api/projects/merge') return 'project_merge';
  if (verb === 'DELETE' && (
    route.startsWith('/api/observation/')
    || route.startsWith('/api/summary/')
    || route.startsWith('/api/prompt/')
    || route.startsWith('/api/sessions/')
  )) return 'memory_delete';
  if (verb === 'POST' && route === '/api/processing') return 'processing_repair';
  if (verb === 'POST' && route === '/api/teambrain/search') return 'team_search';
  if (verb === 'GET' && route === '/api/teambrain/brief') return 'team_brief';
  if (verb === 'GET' && (route === '/api/timeline' || route === '/api/timeline/by-query')) return 'timeline';
  if (verb === 'POST' && route === '/api/dumb-search') return 'dumb_search';
  if (verb === 'POST' && route === '/api/observations/batch') return 'observations_read';
  if (verb === 'GET' && route.startsWith('/api/observation/')) return 'observation_read';
  if (verb === 'POST' && route === '/api/tool-uses/batch') return 'tool_uses_read';
  if (verb === 'POST' && route === '/api/sdk-sessions/batch') return 'sessions_read';
  if (verb === 'POST' && route === '/api/context/semantic') return 'context_semantic';
  if (verb === 'GET' && (route === '/api/context/recent' || route === '/api/context/preview')) return 'context_read';
  if (verb === 'POST' && route === '/api/advisor-calls') return 'advisor';
  if (verb === 'POST' && route === '/api/logs/clear') return 'logs_clear';
  if (verb === 'POST' && route === '/api/sync/setup/import-prompts') return 'sync_import';
  if (verb === 'POST' && route.startsWith('/api/sync/recovery')) return 'sync_recovery';
  if (verb === 'POST' && route === '/api/work-view/review') return 'work_review';
  if (verb === 'POST' && route === '/api/work-view/rules/load-in-claude-code') return 'work_rules_load';
  if (verb === 'POST' && route === '/api/work-view/rules') return 'work_rules';
  if (verb === 'POST' && route.startsWith('/api/work-view/focus/share')) return 'work_share';
  if (verb === 'POST' && route.startsWith('/api/work-view/focus')) return 'work_focus';
  if (verb === 'POST' && route === '/api/work-view/suggestions') return 'work_suggestion';
  if (verb === 'POST' && route === '/api/work-view/refresh') return 'work_refresh';
  if (verb === 'POST' && route === '/api/work-view/conversations/continue') return 'work_continue';
  if (verb === 'POST' && route === '/api/work-view/conversations/stop') return 'work_continue_stop';
  if (verb === 'POST' && route.startsWith('/api/work-view/conversations/open-in-app')) return 'work_open_in_app';
  if (verb === 'POST' && route === '/api/work-view/shared-ledger') return 'work_ledger';
  if (verb === 'POST' && route === '/api/work-view/activity') return 'work_activity';
  if (verb === 'POST' && route === '/api/work-view/agents/mark-finished') return 'work_agent_finished';
  if (verb === 'POST' && route.startsWith('/api/work-view/review-stack')) return 'review_stack';
  return null;
}

export const MESSAGE_SOURCES = ['mac', 'photon', 'replay'] as const;
export type MessageSource = (typeof MESSAGE_SOURCES)[number];

/** Every Messages event. The worker route that relays the Mac app's events accepts only these. */
export const MESSAGES_EVENTS = [
  'messages_observer_started',
  'messages_observer_stopped',
  'messages_window',
  'messages_chats_listed',
  'messages_checked',
  'messages_settings',
] as const;
export type MessagesEvent = (typeof MESSAGES_EVENTS)[number];

/** Where the Mac app's helper hands its Messages events to the worker's consent gate. */
export const MESSAGES_TELEMETRY_ROUTE = '/api/telemetry/messages';

/** Why the Messages database could not be read, as chatdb.ts defines it. */
export type ChatDbFailureReason = Extract<ChatDbAccess, { ok: false }>['reason'];
export type MessageAccess = 'ok' | 'unknown' | ChatDbFailureReason;

export function messageAccess(reason: ChatDbFailureReason | undefined, ok: boolean): MessageAccess {
  if (ok) return 'ok';
  return reason ?? 'unknown';
}

export function messagesWindowProperties(usage: WindowUsage, source: MessageSource): Record<string, string | number | boolean> {
  const properties: Record<string, string | number | boolean> = {
    source,
    outcome: usage.outcome === 'sent' ? 'ok' : 'error',
    message_count: Math.max(0, Math.round(usage.messageCount)),
    is_group: usage.isGroup,
  };
  if (usage.outcome === 'skipped') properties.error_category = 'skipped';
  else if (usage.outcome === 'excluded') properties.error_category = 'excluded';
  else if (usage.outcome === 'dropped') properties.error_category = 'dropped';
  else if (usage.outcome === 'error') properties.error_category = 'provider';
  return properties;
}

/** Counts from chat ids the observer already holds. The ids themselves are not returned. */
export function messagesSelectionCounts(
  guids: readonly string[],
  hasFocus: (guid: string) => boolean,
): { chat_count: number; group_count: number; direct_count: number; focused_count: number } {
  let group = 0;
  let direct = 0;
  let focused = 0;
  for (const guid of guids) {
    if (guid.includes(';+;')) group += 1;
    else direct += 1;
    if (hasFocus(guid)) focused += 1;
  }
  return { chat_count: guids.length, group_count: group, direct_count: direct, focused_count: focused };
}