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
TypeScript aiai-agentsai-memoryanthropicartificial-intelligencechromadbclaudeclaude-agent-sdkclaude-agentsclaude-codeclaude-code-pluginclaude-skillsembeddingslong-term-memorymem0memory-engineopenmemoryragsqlitesupermemory
import { redactText } from './error-scrub.js';
/**
* Whitelist scrubber for telemetry event properties.
*
* Only these keys may ever leave the machine. Everything else — paths,
* project names, prompts, queries, emails, IPs, env values — is dropped
* silently, regardless of what a call site passes in.
*/
export const ALLOWED_PROPERTY_KEYS: Set<string> = new Set([
'version',
'os',
// os_version is the kernel release string (e.g. "10.0.22631"), is_wsl a
// boolean — platform facts for diagnosing install→worker funnel dropoff.
'os_version',
'is_wsl',
'arch',
'runtime',
'runtime_version',
'node_version',
'duration_ms',
'outcome',
'error_category',
'locale',
'is_ci',
// Bounded enums/counters only — never user content. endpoint is one of OUR
// route names, ide/provider/runtime_mode are installer enums, trigger is
// start|heartbeat, count/has_summary/is_update are volume/shape metrics.
'endpoint',
'ide',
'provider',
'runtime_mode',
'trigger',
'count',
// How many worker_started / worker_stopped the daily event stands in for.
'restart_count',
'has_summary',
'is_update',
// Install funnel shape — install_method is a package-manager enum parsed
// from npm_config_user_agent, the *_version keys are tool version strings.
// stage is the cmem Pro trial poll's closed enum
// (awaiting_login | awaiting_checkout | awaiting_approval) on
// trial_poll_timeout — never an email, token, pairing secret, or device
// user code (those never enter any event property).
'stage',
// phase is the installer OAuth pairing phase, a closed enum
// (login | enrollment) on installer_oauth_timeout and
// installer_oauth_start_failed.
'phase',
'install_method',
'interactive',
// provider_source is how the installer decided the provider, a closed enum
// (flag | default | persisted | prompt) on install_completed.
'provider_source',
'bun_version',
'uv_version',
'claude_code_version',
// Installer CMEM Pro offer exposure — a fixed trial-length integer plus
// closed experiment/surface/source enums. Never user or account data.
'trial_days',
'trial_variant',
'offer_surface',
'funnel_source',
// context_injected depth/economics — integers, booleans, and our own enums.
'observation_count',
'session_count',
'timeline_depth_days',
'has_session_summary',
'obs_type_bugfix',
'obs_type_discovery',
'obs_type_decision',
'obs_type_refactor',
'obs_type_other',
'tokens_injected',
'tokens_saved_vs_naive',
'mode',
'search_strategy',
// session_compressed depth — model id, our trigger names, real token usage.
'observation_type',
'hook',
'compression_ms',
'tokens_input',
'tokens_output',
'compression_ratio',
'model',
// Provider-reported spend of one compression call in USD (SDK result message
// for Claude, usage.cost for OpenRouter) — never an estimate.
'cost_usd',
// 'openrouter' | 'custom' — whether the OpenRouter provider talks to
// openrouter.ai or a user-pointed OpenAI-compatible gateway.
'endpoint_class',
// worker_started install snapshot — aggregate shape of the local memory DB:
// row counts, file size in MB, and day-granularity age/recency. Counts and
// day deltas only — never project names, observation text, or content.
'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',
// search_performed retrieval quality — result_count is an integer,
// chroma_available a boolean, fallback_reason one of OUR enum values
// (none | chroma_connection | chroma_error | chroma_not_initialized | chroma_zero_results).
// Never the query, never an error message.
'result_count',
'chroma_available',
'fallback_reason',
// session_compressed trust signals — booleans, counters, and our own
// closed enums (invalid_output_class: xml | idle | prose, where 'xml' means
// XML-shaped output that still failed to parse; abort_reason:
// idle | shutdown | overflow | restart_guard | quota | rate_limit | auth |
// provider_switch | deadline_exceeded | output_retry | drift | none).
// Never model output, never raw abort strings.
'invalid_output_class',
'consecutive_invalid_outputs',
'respawn_triggered',
'abort_reason',
// Worker lifecycle health — previous_shutdown (crash | clean | unknown),
// shutdown_reason (stop | restart | signal | idle), uptime in whole
// seconds, and process memory as integer megabytes. No paths, no PIDs.
'previous_shutdown',
'previous_uptime_seconds',
'uptime_seconds',
'shutdown_reason',
'process_rss_mb',
'heap_used_mb',
// hook_failed distress signal — hook_type is one of OUR hook names
// (context | session-init | observation | summarize | session-end | file-context),
// error_mode (worker_unavailable | blocking_error), plus a consecutive
// failure counter, threshold flag, and a pre-latch-state flag. Never an
// error message.
'hook_type',
'error_mode',
'consecutive_failures',
'threshold_tripped',
'pre_latch_state',
// usage_limit_hit — the SDK's rate_limit_info projected to closed enums:
// limit_window (five_hour | seven_day | seven_day_opus | seven_day_sonnet |
// seven_day_overage_included | overage | unknown), overage_status (allowed |
// allowed_warning | rejected | unknown), a boolean, and whole minutes until
// the window resets. Never the provider's limit message text.
'limit_window',
'overage_status',
'is_using_overage',
'resets_in_minutes',
// Historical backfill (backfill.ts) — anonymous per-day rollup counters,
// the backfilled:true flag, and the single inferred-install date string
// (YYYY-MM-DD). Counts/sums and closed-enum buckets only — never project
// names, prompt text, or any raw string column. observation_count,
// session_count, and the obs_type_* family are shared with live
// context_injected above (different per-event semantics — see PR notes).
'discovery_tokens',
// read_tokens: per-day sum of once-each observation read cost
// (ceil(len(text)/CHARS_PER_TOKEN_ESTIMATE)); paired with discovery_tokens to
// derive the historical tokens_saved_vs_naive series. tokens_saved_vs_naive
// itself is whitelisted above (shared key name with live context_injected).
'read_tokens',
'summary_count',
'prompt_count',
'project_count',
'backfilled',
'first_active_date',
'session_completed_count',
'session_failed_count',
'sessions_claude_count',
'sessions_codex_count',
'sessions_gemini_count',
'sessions_other_platform_count',
'subagent_obs_count',
// Rollup events emitted by TelemetryBuffer (buffer.ts) — aggregate fields
// that replace the high-volume per-event stream with 5-minute windows.
// observer_turn_rollup aggregation fields:
'total_tokens_input',
'total_tokens_output',
'total_cost_usd',
'avg_duration_ms',
'avg_compression_ms',
'outcomes_ok',
'outcomes_error',
'outcomes_aborted',
// Integer subset of outcomes_aborted: turns abandoned at the LLM deadline.
'outcomes_aborted_deadline_exceeded',
'outcomes_invalid_output',
'top_model',
// top_abort_reason: the dominant normalized abort_reason among the session's
// aborted turns (same closed enum as abort_reason above). Present only when a
// turn aborted; never a raw abort string.
'top_abort_reason',
// Observed-session identity (NOT the observer): the model id the user's IDE
// session ran (from its transcript) and a closed-enum billing posture
// (max | pro | team | enterprise | subscription | api_key | bedrock | vertex | foundry | unknown).
'observed_model',
'observed_billing',
'window_start_ts',
// Phase 2 per-session rollup: rollup_reason is a closed enum
// (session_end | worker_shutdown | safety_flush) explaining why the session's
// single observer_turn_rollup was emitted; window_seq is the partial-flush
// sequence number (0 for a normal one-shot session, incrementing only when a
// long-lived session trips the safety sweep). Enum + integer only.
'rollup_reason',
'window_seq',
// context_injected_rollup aggregation fields:
'total_tokens',
'avg_tokens',
// context_read_timed_out: read_method is a closed enum of context-reader
// method names (ContextReadMethods), queue_wait_ms an integer duration.
'read_method',
'queue_wait_ms',
// skill_invoked — closed skill identity only. skill_id is a first-party
// plugin/skills/ name or `other`; skill_source is first_party | third_party;
// skill_trigger is tool | prompt. Never a third-party skill name, never
// tool_input.args, never the prompt body.
'skill_id',
'skill_source',
'skill_trigger',
// Per-session/window observation volume folded into the rollups so the
// context-cache-value and observation-type metrics survive the retirement of
// the legacy per-occurrence streams. observations_created (generation side,
// observer_turn_rollup) pairs with total_cost_usd to derive cost-per-obs;
// total_observations_injected (injection side, context_injected_rollup) is the
// cache-reuse count; total_tokens_saved_vs_naive is the windowed savings sum.
// The obs_type_* family is already whitelisted above (shared key names).
'observations_created',
'total_observations_injected',
'total_tokens_saved_vs_naive',
// Work-state usage: closed dimensions and counts; no task/session/agent IDs.
'platform', 'agent_role', 'instruction_state',
'instruction_returned_count', 'instruction_disabled_count',
'instruction_excluded_count', 'instruction_missing_count', 'instruction_unknown_count',
'captured_prompt_count', 'captured_session_count', 'captured_tool_count',
'unidentified_tool_event_count', 'native_todo_count',
...['captured', 'mcp'].flatMap(source => ['read', 'write'].flatMap(operation => [
`${source}_${operation}_count`,
...['ok', 'error', 'excluded', 'disabled', 'unknown'].map(outcome => `${source}_${operation}_${outcome}_count`),
])),
// work_view_opened / work_view_switched — which My Work viewer page is on
// screen, as the viewer's own closed page ids (WORK_VIEW_USAGE_VIEWS in src/shared/work-view-pages.ts).
// Never a request title, prompt, observation, file path, or search text.
'view',
'previous_view',
// Which viewer sent the event, and the host it was opened on. Closed enum
// plus a hostname (no path, no user). Local is the worker; hosted is work.cmem.ai.
'viewer_host',
'hostname',
// work_view_hosted_plans_viewed — the Cloud Sync plan setup kept, as the setup
// funnel's closed enum (cloud_sync_monthly | cloud_sync_annual). Never a price,
// an account, or a checkout link.
'cloud_sync_offer',
// auto_update_applied / auto_update_failed (src/services/auto-update/auto-update-apply.ts):
// from_version and to_version are claude-mem release versions, failure_stage
// and restore_result the supervisor's own closed enums
// (AutoUpdateApplyFailureStage, AutoUpdateRestoreResult). Never a path, a
// log line or an error message.
'from_version',
'to_version',
'failure_stage',
'restore_result',
// corpus_used / feature_used / mcp_tool_used / cli_command / messages_*.
// Closed enums, counts and booleans. Never a corpus name, question, answer,
// project, path, phone number, contact name or message.
'corpus_action',
'feature',
'transport',
'has_project',
'has_types',
'has_concepts',
'has_files',
'has_query',
'has_date_range',
'has_description',
'type_count',
'concept_count',
'file_count',
'requested_limit',
'token_estimate',
'was_primed',
'forced',
'previous_observation_count',
'primed_count',
'observations_sent',
'observations_matching',
'observations_in_corpus',
'observations_truncated',
'question_length',
'source',
'message_count',
'is_group',
'chat_count',
'group_count',
'direct_count',
'focused_count',
'windows_sent',
'windows_skipped',
'include_direct',
'has_focus',
'has_default_focus',
'dry_run',
'contact_count',
'line_count',
'setting',
'worker_reachable',
'access',
]);
const MAX_STRING_LENGTH = 200;
/**
* Copies whitelisted primitive values from props into scrubbed, truncating
* strings to MAX_STRING_LENGTH. Extracted so scrubProperties' try stays small.
*/
function copyAllowedProperties(
props: Record<string, unknown>,
scrubbed: Record<string, string | number | boolean>
): void {
if (!props || typeof props !== 'object') return;
for (const key of Object.keys(props)) {
if (!ALLOWED_PROPERTY_KEYS.has(key)) continue;
const value = props[key];
if (key === 'hostname' && typeof value === 'string' && /^[a-z0-9.-]{1,253}$/i.test(value)) {
// The viewer host is the field. The error redactor would turn a loopback
// address into [REDACTED], which is the opposite of what this field is for.
scrubbed[key] = value.toLowerCase();
continue;
}
if (typeof value === 'string') {
const truncated = value.length > MAX_STRING_LENGTH ? value.slice(0, MAX_STRING_LENGTH) : value;
// Allowed keys are supposed to be enums/counters, but a call site can
// still stuff a URL-shaped token into e.g. `endpoint`. Run the error
// redaction pipeline so query/userinfo/assignment secrets cannot ride
// along on a whitelisted key.
scrubbed[key] = redactText(truncated);
} else if (typeof value === 'number' && Number.isFinite(value)) {
scrubbed[key] = value;
} else if (typeof value === 'boolean') {
scrubbed[key] = value;
}
// Everything else (objects, arrays, functions, null, undefined,
// NaN/Infinity, symbols, bigints) is dropped silently.
}
}
/**
* Filters properties down to whitelisted keys with primitive values only.
* Strings are truncated to 200 chars. Objects, arrays, functions, null,
* undefined, and non-finite numbers are dropped. Pure, never throws.
*/
export function scrubProperties(
props: Record<string, unknown>
): Record<string, string | number | boolean> {
const scrubbed: Record<string, string | number | boolean> = {};
try {
copyAllowedProperties(props, scrubbed);
} catch {
// Never throw from the scrubber — worst case we send fewer properties
}
return scrubbed;
}