fix(openclaw): persistent anonymous telemetry ID, flush fix, and email resolution (#4790)

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Saket Aryan
2026-04-11 20:57:14 +05:30
committed by GitHub
co-authored by Claude Opus 4.6
parent 9d82e2329d
commit d39ebad09f
10 changed files with 215 additions and 11 deletions
+186 -5
View File
@@ -8,10 +8,10 @@
* Disable with: MEM0_TELEMETRY=false
*/
import { createHash } from "node:crypto";
import { readPluginAuth } from "./cli/config-file.ts";
import { createHash, randomUUID } from "node:crypto";
import { readPluginAuth, writePluginAuth, getBaseUrl } from "./cli/config-file.ts";
export const PLUGIN_VERSION = "1.0.4";
export const PLUGIN_VERSION = "1.0.6";
const POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX";
const POSTHOG_HOST = "https://us.i.posthog.com/i/v0/e/";
@@ -22,6 +22,133 @@ const FLUSH_THRESHOLD = 10;
let eventQueue: Record<string, unknown>[] = [];
let flushTimer: ReturnType<typeof setInterval> | undefined;
let _cachedAnonymousId: string | undefined;
let _aliasCheckDone = false;
/**
* Return a persistent per-machine anonymous ID, generating one if needed.
*
* Stored in ~/.openclaw/openclaw.json under the plugin's `anonymousTelemetryId`
* field so repeat sessions on the same machine share one PostHog identity
* instead of collapsing into a single shared fallback string. The result is
* cached in module memory after the first read so we don't re-touch disk on
* every queued event.
*/
function getOrCreateAnonymousId(): string {
if (_cachedAnonymousId) return _cachedAnonymousId;
try {
const auth = readPluginAuth();
if (auth.anonymousTelemetryId) {
_cachedAnonymousId = auth.anonymousTelemetryId;
return _cachedAnonymousId;
}
} catch {
/* ignore */
}
const newId = `openclaw-anon-${randomUUID().replace(/-/g, "")}`;
try {
writePluginAuth({ anonymousTelemetryId: newId });
} catch {
/* ignore — return generated id anyway */
}
_cachedAnonymousId = newId;
return newId;
}
/**
* If we just resolved to a real identity but a stored anonymous id exists,
* build a one-shot PostHog $identify event so the pre-signup history gets
* stitched onto the authenticated profile. Returns null when no aliasing is
* needed (already done, or no anon id on disk, or still anonymous).
*
* Caller is responsible for pushing the returned event onto eventQueue ahead
* of the regular event.
*/
function maybeBuildIdentifyEvent(
distinctId: string,
): Record<string, unknown> | null {
if (_aliasCheckDone) return null;
if (!distinctId || distinctId.startsWith("openclaw-anon-")) return null;
try {
const auth = readPluginAuth();
const storedAnon = auth.anonymousTelemetryId;
if (!storedAnon) {
_aliasCheckDone = true;
return null;
}
const identifyEvent = {
event: "$identify",
distinct_id: distinctId,
properties: {
$anon_distinct_id: storedAnon,
$lib: "posthog-node",
},
};
try {
writePluginAuth({ anonymousTelemetryId: "" });
} catch {
/* ignore — alias may double-fire next session, harmless */
}
_aliasCheckDone = true;
_cachedAnonymousId = undefined;
return identifyEvent;
} catch {
return null;
}
}
let _emailResolutionAttempted = false;
/**
* If we have an apiKey but no cached userEmail, do a one-shot /v1/ping/
* call to resolve the email and cache it. This runs async as a side-effect;
* the current event ships with md5(apiKey) but subsequent events (including
* those flushed by the beforeExit handler in the same process) will use
* the resolved email.
*/
function maybeResolveEmail(apiKey: string): void {
if (_emailResolutionAttempted) return;
_emailResolutionAttempted = true;
const baseUrl = getBaseUrl().replace(/\/+$/, "");
fetch(`${baseUrl}/v1/ping/`, {
method: "GET",
headers: {
Authorization: `Token ${apiKey}`,
"Content-Type": "application/json",
},
signal: AbortSignal.timeout(5_000),
})
.then((res) => res.json())
.then((data: any) => {
const email = data?.user_email;
if (email) {
try {
writePluginAuth({ userEmail: email });
} catch {
/* ignore */
}
// Upgrade any already-queued events from md5(apiKey) to email
const oldId = createHash("md5").update(apiKey).digest("hex");
for (const ev of eventQueue) {
if (ev.distinct_id === oldId) {
ev.distinct_id = email;
}
// Also upgrade $identify's distinct_id if present
if (
ev.event === "$identify" &&
ev.distinct_id === oldId
) {
ev.distinct_id = email;
}
}
}
})
.catch(() => {
/* silently swallow — md5(apiKey) is used as fallback */
});
}
let _telemetryEnabled: boolean | undefined;
function isTelemetryEnabled(): boolean {
if (_telemetryEnabled !== undefined) return _telemetryEnabled;
@@ -42,7 +169,8 @@ function isTelemetryEnabled(): boolean {
/**
* Return a stable anonymous identifier for the current user.
*
* Priority: cached userEmail (from /v1/ping/) > MD5(apiKey) > fallback.
* Priority: cached userEmail (from /v1/ping/) > MD5(apiKey) >
* persistent per-machine anonymous ID.
*/
function getDistinctId(apiKey?: string): string {
try {
@@ -54,7 +182,7 @@ function getDistinctId(apiKey?: string): string {
if (apiKey) {
return createHash("md5").update(apiKey).digest("hex");
}
return "anonymous-openclaw";
return getOrCreateAnonymousId();
}
function ensureFlushTimer(): void {
@@ -65,6 +193,42 @@ function ensureFlushTimer(): void {
}
}
let _exitHandlerInstalled = false;
/**
* Install a one-time `beforeExit` handler that drains queued events on
* process exit. Without this, short-lived CLI invocations (e.g. one
* `openclaw mem0 status` call) exit before the unref'd flushTimer fires
* and before FLUSH_THRESHOLD is hit, dropping every queued event silently.
*
* Returning a Promise from a `beforeExit` handler keeps the event loop
* alive until that Promise resolves, so the awaited fetch actually has
* time to land at PostHog.
*/
function ensureExitHandler(): void {
if (_exitHandlerInstalled) return;
_exitHandlerInstalled = true;
process.on("beforeExit", async () => {
if (eventQueue.length === 0) return;
const batch = eventQueue;
eventQueue = [];
const body = JSON.stringify({ api_key: POSTHOG_API_KEY, batch });
try {
await fetch(POSTHOG_HOST, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": String(Buffer.byteLength(body)),
},
body,
signal: AbortSignal.timeout(3_000),
});
} catch {
/* silently swallow */
}
});
}
function flushEvents(): void {
if (eventQueue.length === 0) return;
const batch = eventQueue;
@@ -97,6 +261,22 @@ export function captureEvent(
try {
const distinctId = getDistinctId(ctx?.apiKey);
// If we resolved to md5(apiKey) instead of email, kick off a background
// /v1/ping/ to resolve and cache the email. The current event ships with
// the hash, but the async resolution upgrades any still-queued events
// (including this one) before the beforeExit flush fires.
if (ctx?.apiKey && distinctId && !distinctId.includes("@") && !distinctId.startsWith("openclaw-anon-")) {
maybeResolveEmail(ctx.apiKey);
}
// First authenticated event after a previous anonymous session: queue a
// $identify ahead of the regular event so PostHog merges the anonymous
// history onto the authenticated profile in the same batch flush.
const identifyEvent = maybeBuildIdentifyEvent(distinctId);
if (identifyEvent) {
eventQueue.push(identifyEvent);
}
eventQueue.push({
event: eventName,
distinct_id: distinctId,
@@ -115,6 +295,7 @@ export function captureEvent(
});
ensureFlushTimer();
ensureExitHandler();
if (eventQueue.length >= FLUSH_THRESHOLD) {
flushEvents();