feat(omo-claude): fork telemetry with distinct identity and derived literals
omo_claude_daily_active event + omo-claude: distinct-id salt; PostHog key/host/ LEGACY_PARENT_PACKAGE kept identical (shared project). platform + tmp-fallback derived from constants (no literals). 4-flag opt-out incl inherited OMO_*. cross-package-equivalence + cross-product distinctness tests (RED->GREEN). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
import { renameSync, unlinkSync, writeFileSync } from "node:fs"
|
||||
|
||||
export function writeFileAtomically(filePath: string, content: string): void {
|
||||
const tempPath = `${filePath}.tmp`
|
||||
writeFileSync(tempPath, content, "utf-8")
|
||||
|
||||
try {
|
||||
renameSync(tempPath, filePath)
|
||||
} catch (error) {
|
||||
const isPermissionError =
|
||||
error instanceof Error &&
|
||||
(error.message.includes("EPERM") || error.message.includes("EACCES"))
|
||||
|
||||
if (process.platform === "win32" && isPermissionError) {
|
||||
unlinkSync(filePath)
|
||||
renameSync(tempPath, filePath)
|
||||
return
|
||||
}
|
||||
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { accessSync, constants, mkdirSync } from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
|
||||
import { CACHE_DIR_NAME } from "./product-identity.js"
|
||||
|
||||
type OsProvider = Pick<typeof os, "homedir" | "tmpdir">
|
||||
|
||||
let osProviderOverride: OsProvider | null = null
|
||||
|
||||
export function getOsProvider(): OsProvider {
|
||||
return osProviderOverride ?? os
|
||||
}
|
||||
|
||||
/** @internal test-only */
|
||||
export function __setOsProviderForTesting(provider: OsProvider): void {
|
||||
osProviderOverride = provider
|
||||
}
|
||||
|
||||
/** @internal test-only */
|
||||
export function __resetOsProviderForTesting(): void {
|
||||
osProviderOverride = null
|
||||
}
|
||||
|
||||
function resolveWritableDirectory(preferredDir: string, fallbackSuffix: string): string {
|
||||
try {
|
||||
mkdirSync(preferredDir, { recursive: true })
|
||||
accessSync(preferredDir, constants.W_OK)
|
||||
return preferredDir
|
||||
} catch {
|
||||
const fallbackDir = path.join(getOsProvider().tmpdir(), fallbackSuffix)
|
||||
mkdirSync(fallbackDir, { recursive: true })
|
||||
return fallbackDir
|
||||
}
|
||||
}
|
||||
|
||||
export function getDataDir(): string {
|
||||
const preferredDataDir =
|
||||
process.env["XDG_DATA_HOME"] ?? path.join(getOsProvider().homedir(), ".local", "share")
|
||||
return resolveWritableDirectory(preferredDataDir, `${CACHE_DIR_NAME}-data`)
|
||||
}
|
||||
|
||||
export function getActivityStateDir(): string {
|
||||
return path.join(getDataDir(), CACHE_DIR_NAME)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import {
|
||||
DEFAULT_POSTHOG_API_KEY,
|
||||
DEFAULT_POSTHOG_HOST,
|
||||
} from "./product-identity.js"
|
||||
|
||||
function normalizeEnvValue(value: string | undefined): string | undefined {
|
||||
return value?.trim().toLowerCase()
|
||||
}
|
||||
|
||||
function isDisableFlag(value: string | undefined): boolean {
|
||||
const normalized = normalizeEnvValue(value)
|
||||
return normalized === "1" || normalized === "true"
|
||||
}
|
||||
|
||||
function isTelemetryOptOutFlag(value: string | undefined): boolean {
|
||||
const normalized = normalizeEnvValue(value)
|
||||
return normalized === "0" || normalized === "false" || normalized === "no"
|
||||
}
|
||||
|
||||
export function shouldDisablePostHog(): boolean {
|
||||
return (
|
||||
isDisableFlag(process.env["OMO_DISABLE_POSTHOG"]) ||
|
||||
isTelemetryOptOutFlag(process.env["OMO_SEND_ANONYMOUS_TELEMETRY"]) ||
|
||||
isDisableFlag(process.env["OMO_CLAUDE_DISABLE_POSTHOG"]) ||
|
||||
isTelemetryOptOutFlag(process.env["OMO_CLAUDE_SEND_ANONYMOUS_TELEMETRY"])
|
||||
)
|
||||
}
|
||||
|
||||
export function getPostHogApiKey(): string {
|
||||
const explicit = process.env["POSTHOG_API_KEY"]
|
||||
if (explicit === undefined) {
|
||||
return DEFAULT_POSTHOG_API_KEY
|
||||
}
|
||||
return explicit.trim()
|
||||
}
|
||||
|
||||
export function hasPostHogApiKey(): boolean {
|
||||
return getPostHogApiKey().length > 0
|
||||
}
|
||||
|
||||
export function getPostHogHost(): string {
|
||||
return process.env["POSTHOG_HOST"]?.trim() || DEFAULT_POSTHOG_HOST
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { existsSync, mkdirSync, readFileSync } from "node:fs"
|
||||
import { join } from "node:path"
|
||||
|
||||
import { writeFileAtomically } from "./atomic-write.js"
|
||||
import { getActivityStateDir } from "./data-path.js"
|
||||
|
||||
export type PostHogActivityState = {
|
||||
readonly lastActiveDayUTC?: string
|
||||
}
|
||||
|
||||
export type PostHogActivityCaptureState = {
|
||||
readonly dayUTC: string
|
||||
readonly captureDaily: boolean
|
||||
}
|
||||
|
||||
const POSTHOG_ACTIVITY_STATE_FILE = "posthog-activity.json"
|
||||
|
||||
function getPostHogActivityStateFilePath(): string {
|
||||
return join(getActivityStateDir(), POSTHOG_ACTIVITY_STATE_FILE)
|
||||
}
|
||||
|
||||
function getUtcDayString(date: Date): string {
|
||||
return date.toISOString().slice(0, 10)
|
||||
}
|
||||
|
||||
function isPostHogActivityState(value: unknown): value is PostHogActivityState {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function readPostHogActivityState(): PostHogActivityState {
|
||||
const stateFilePath = getPostHogActivityStateFilePath()
|
||||
|
||||
if (!existsSync(stateFilePath)) {
|
||||
return {}
|
||||
}
|
||||
|
||||
try {
|
||||
const stateContent = readFileSync(stateFilePath, "utf-8")
|
||||
const stateJson: unknown = JSON.parse(stateContent)
|
||||
|
||||
if (!isPostHogActivityState(stateJson)) {
|
||||
return {}
|
||||
}
|
||||
|
||||
return stateJson
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
function writePostHogActivityState(nextState: PostHogActivityState): void {
|
||||
const stateDir = getActivityStateDir()
|
||||
const stateFilePath = getPostHogActivityStateFilePath()
|
||||
|
||||
try {
|
||||
mkdirSync(stateDir, { recursive: true })
|
||||
writeFileAtomically(stateFilePath, `${JSON.stringify(nextState, null, 2)}\n`)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
export function getPostHogActivityCaptureState(
|
||||
now: Date = new Date(),
|
||||
): PostHogActivityCaptureState {
|
||||
const state = readPostHogActivityState()
|
||||
const dayUTC = getUtcDayString(now)
|
||||
const captureDaily = state.lastActiveDayUTC !== dayUTC
|
||||
|
||||
if (captureDaily) {
|
||||
writePostHogActivityState({
|
||||
...state,
|
||||
lastActiveDayUTC: dayUTC,
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
dayUTC,
|
||||
captureDaily,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
export const PRODUCT_NAME = "omo-claude";
|
||||
export const PACKAGE_NAME = "@oh-my-opencode/omo-claude";
|
||||
export const CACHE_DIR_NAME = "omo-claude";
|
||||
export const EVENT_NAME = "omo_claude_daily_active";
|
||||
export const LEGACY_PARENT_PACKAGE = "oh-my-opencode";
|
||||
export const DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com";
|
||||
export const DEFAULT_POSTHOG_API_KEY = "phc_CFJhj5HyvA62QPhvyaUCtaq23aUfznnijg5VaaGkNk74";
|
||||
|
||||
type ComponentPackageManifest = { readonly version?: string };
|
||||
|
||||
function isComponentPackageManifest(value: unknown): value is ComponentPackageManifest {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function readComponentVersionFromManifest(): string {
|
||||
try {
|
||||
const manifestUrl = new URL("../package.json", import.meta.url);
|
||||
const manifestText = readFileSync(manifestUrl, "utf-8");
|
||||
const parsed: unknown = JSON.parse(manifestText);
|
||||
if (isComponentPackageManifest(parsed) && typeof parsed.version === "string") {
|
||||
return parsed.version;
|
||||
}
|
||||
} catch {
|
||||
return "0.0.0";
|
||||
}
|
||||
return "0.0.0";
|
||||
}
|
||||
|
||||
const COMPONENT_VERSION_CACHE = readComponentVersionFromManifest();
|
||||
|
||||
export function getComponentVersion(): string {
|
||||
return COMPONENT_VERSION_CACHE;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { renameSync, unlinkSync, writeFileSync } from "node:fs"
|
||||
|
||||
export function writeFileAtomically(filePath: string, content: string): void {
|
||||
const tempPath = `${filePath}.tmp`
|
||||
writeFileSync(tempPath, content, "utf-8")
|
||||
|
||||
try {
|
||||
renameSync(tempPath, filePath)
|
||||
} catch (error) {
|
||||
const isPermissionError =
|
||||
error instanceof Error &&
|
||||
(error.message.includes("EPERM") || error.message.includes("EACCES"))
|
||||
|
||||
if (process.platform === "win32" && isPermissionError) {
|
||||
unlinkSync(filePath)
|
||||
renameSync(tempPath, filePath)
|
||||
return
|
||||
}
|
||||
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import { describe, expect, it } from "bun:test"
|
||||
|
||||
import * as cliIdentity from "./product-identity"
|
||||
|
||||
describe("cross-package telemetry identity equivalence", () => {
|
||||
describe("#given the omo-claude CLI telemetry product-identity module and the Claude Code plugin component product-identity module", () => {
|
||||
it("#when both are imported #then PRODUCT_NAME, PACKAGE_NAME, CACHE_DIR_NAME, EVENT_NAME, DEFAULT_POSTHOG_HOST, and DEFAULT_POSTHOG_API_KEY are identical", async () => {
|
||||
const pluginIdentity = await import(
|
||||
"../../plugin/components/telemetry/src/product-identity"
|
||||
)
|
||||
|
||||
expect(pluginIdentity.PRODUCT_NAME).toBe(cliIdentity.PRODUCT_NAME)
|
||||
expect(pluginIdentity.PACKAGE_NAME).toBe(cliIdentity.PACKAGE_NAME)
|
||||
expect(pluginIdentity.CACHE_DIR_NAME).toBe(cliIdentity.CACHE_DIR_NAME)
|
||||
expect(pluginIdentity.EVENT_NAME).toBe(cliIdentity.EVENT_NAME)
|
||||
expect(pluginIdentity.DEFAULT_POSTHOG_HOST).toBe(cliIdentity.DEFAULT_POSTHOG_HOST)
|
||||
expect(pluginIdentity.DEFAULT_POSTHOG_API_KEY).toBe(cliIdentity.DEFAULT_POSTHOG_API_KEY)
|
||||
expect(pluginIdentity.LEGACY_PARENT_PACKAGE).toBe(cliIdentity.LEGACY_PARENT_PACKAGE)
|
||||
})
|
||||
})
|
||||
|
||||
describe("#given the omo-claude CLI env-flags module and the Claude Code plugin component env-flags module", () => {
|
||||
it("#when shouldDisablePostHog is checked under each opt-out env var #then both modules disable on the same flags", async () => {
|
||||
const cliEnv = await import("./env-flags")
|
||||
const pluginEnv = await import(
|
||||
"../../plugin/components/telemetry/src/env-flags"
|
||||
)
|
||||
|
||||
const flags = [
|
||||
"OMO_DISABLE_POSTHOG",
|
||||
"OMO_SEND_ANONYMOUS_TELEMETRY",
|
||||
"OMO_CLAUDE_DISABLE_POSTHOG",
|
||||
"OMO_CLAUDE_SEND_ANONYMOUS_TELEMETRY",
|
||||
] as const
|
||||
const previousValues = new Map<string, string | undefined>()
|
||||
for (const flag of flags) {
|
||||
previousValues.set(flag, process.env[flag])
|
||||
delete process.env[flag]
|
||||
}
|
||||
try {
|
||||
expect(cliEnv.shouldDisablePostHog()).toBe(false)
|
||||
expect(pluginEnv.shouldDisablePostHog()).toBe(false)
|
||||
|
||||
for (const optOutFlag of ["OMO_DISABLE_POSTHOG", "OMO_CLAUDE_DISABLE_POSTHOG"] as const) {
|
||||
process.env[optOutFlag] = "1"
|
||||
expect(cliEnv.shouldDisablePostHog()).toBe(true)
|
||||
expect(pluginEnv.shouldDisablePostHog()).toBe(true)
|
||||
delete process.env[optOutFlag]
|
||||
}
|
||||
|
||||
for (const sendFlag of ["OMO_SEND_ANONYMOUS_TELEMETRY", "OMO_CLAUDE_SEND_ANONYMOUS_TELEMETRY"] as const) {
|
||||
process.env[sendFlag] = "0"
|
||||
expect(cliEnv.shouldDisablePostHog()).toBe(true)
|
||||
expect(pluginEnv.shouldDisablePostHog()).toBe(true)
|
||||
delete process.env[sendFlag]
|
||||
}
|
||||
} finally {
|
||||
for (const flag of flags) {
|
||||
const previous = previousValues.get(flag)
|
||||
if (previous === undefined) {
|
||||
delete process.env[flag]
|
||||
} else {
|
||||
process.env[flag] = previous
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("cross-product telemetry identity distinctness", () => {
|
||||
describe("#given the omo-claude product-identity module and the omo-codex product-identity module", () => {
|
||||
it("#when both are imported #then EVENT_NAME differs but the shared PostHog project key, host, and LEGACY_PARENT_PACKAGE are equal", async () => {
|
||||
const codexIdentity = await import(
|
||||
"../../../omo-codex/src/telemetry/product-identity.ts"
|
||||
)
|
||||
|
||||
// Distinct branding — must NOT collide across products.
|
||||
expect(cliIdentity.EVENT_NAME).not.toBe(codexIdentity.EVENT_NAME)
|
||||
expect(cliIdentity.EVENT_NAME).toBe("omo_claude_daily_active")
|
||||
expect(codexIdentity.EVENT_NAME).toBe("omo_codex_daily_active")
|
||||
expect(cliIdentity.PRODUCT_NAME).not.toBe(codexIdentity.PRODUCT_NAME)
|
||||
expect(cliIdentity.PACKAGE_NAME).not.toBe(codexIdentity.PACKAGE_NAME)
|
||||
expect(cliIdentity.CACHE_DIR_NAME).not.toBe(codexIdentity.CACHE_DIR_NAME)
|
||||
|
||||
// Shared PostHog project — must be byte-identical across products.
|
||||
expect(cliIdentity.DEFAULT_POSTHOG_API_KEY).toBe(codexIdentity.DEFAULT_POSTHOG_API_KEY)
|
||||
expect(cliIdentity.DEFAULT_POSTHOG_HOST).toBe(codexIdentity.DEFAULT_POSTHOG_HOST)
|
||||
expect(cliIdentity.LEGACY_PARENT_PACKAGE).toBe(codexIdentity.LEGACY_PARENT_PACKAGE)
|
||||
})
|
||||
})
|
||||
|
||||
describe("#given the omo-claude posthog module and the omo-codex posthog module", () => {
|
||||
it("#when getPostHogDistinctId is computed on each #then the distinct-id seeds differ", async () => {
|
||||
const fixedHostname = "distinctness-test-host"
|
||||
const osOverride = {
|
||||
arch: () => "arm64" as const,
|
||||
cpus: () => [],
|
||||
hostname: () => fixedHostname,
|
||||
platform: () => "darwin" as const,
|
||||
release: () => "0.0.0",
|
||||
totalmem: () => 0,
|
||||
type: () => "Darwin",
|
||||
}
|
||||
|
||||
const claudePosthog = await import("./posthog")
|
||||
const codexPosthog = await import(
|
||||
"../../../omo-codex/src/telemetry/posthog.ts"
|
||||
)
|
||||
|
||||
claudePosthog.__setOsProviderForTesting(osOverride)
|
||||
codexPosthog.__setOsProviderForTesting(osOverride)
|
||||
try {
|
||||
const claudeId = claudePosthog.getPostHogDistinctId()
|
||||
const codexId = codexPosthog.getPostHogDistinctId()
|
||||
|
||||
// Same hostname, different salt → different distinct id.
|
||||
expect(claudeId).not.toBe(codexId)
|
||||
} finally {
|
||||
claudePosthog.__resetOsProviderForTesting()
|
||||
codexPosthog.__resetOsProviderForTesting()
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,45 @@
|
||||
import { accessSync, constants, mkdirSync } from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
|
||||
import { CACHE_DIR_NAME } from "./product-identity"
|
||||
|
||||
type OsProvider = Pick<typeof os, "homedir" | "tmpdir">
|
||||
|
||||
let osProviderOverride: OsProvider | null = null
|
||||
|
||||
export function getOsProvider(): OsProvider {
|
||||
return osProviderOverride ?? os
|
||||
}
|
||||
|
||||
/** @internal test-only */
|
||||
export function __setOsProviderForTesting(provider: OsProvider): void {
|
||||
osProviderOverride = provider
|
||||
}
|
||||
|
||||
/** @internal test-only */
|
||||
export function __resetOsProviderForTesting(): void {
|
||||
osProviderOverride = null
|
||||
}
|
||||
|
||||
function resolveWritableDirectory(preferredDir: string, fallbackSuffix: string): string {
|
||||
try {
|
||||
mkdirSync(preferredDir, { recursive: true })
|
||||
accessSync(preferredDir, constants.W_OK)
|
||||
return preferredDir
|
||||
} catch {
|
||||
const fallbackDir = path.join(getOsProvider().tmpdir(), fallbackSuffix)
|
||||
mkdirSync(fallbackDir, { recursive: true })
|
||||
return fallbackDir
|
||||
}
|
||||
}
|
||||
|
||||
export function getDataDir(): string {
|
||||
const preferredDataDir =
|
||||
process.env.XDG_DATA_HOME ?? path.join(getOsProvider().homedir(), ".local", "share")
|
||||
return resolveWritableDirectory(preferredDataDir, `${CACHE_DIR_NAME}-data`)
|
||||
}
|
||||
|
||||
export function getActivityStateDir(): string {
|
||||
return path.join(getDataDir(), CACHE_DIR_NAME)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import {
|
||||
DEFAULT_POSTHOG_API_KEY,
|
||||
DEFAULT_POSTHOG_HOST,
|
||||
} from "./product-identity"
|
||||
|
||||
function normalizeEnvValue(value: string | undefined): string | undefined {
|
||||
return value?.trim().toLowerCase()
|
||||
}
|
||||
|
||||
function isDisableFlag(value: string | undefined): boolean {
|
||||
const normalized = normalizeEnvValue(value)
|
||||
return normalized === "1" || normalized === "true"
|
||||
}
|
||||
|
||||
function isTelemetryOptOutFlag(value: string | undefined): boolean {
|
||||
const normalized = normalizeEnvValue(value)
|
||||
return normalized === "0" || normalized === "false" || normalized === "no"
|
||||
}
|
||||
|
||||
export function shouldDisablePostHog(): boolean {
|
||||
return (
|
||||
isDisableFlag(process.env.OMO_DISABLE_POSTHOG) ||
|
||||
isTelemetryOptOutFlag(process.env.OMO_SEND_ANONYMOUS_TELEMETRY) ||
|
||||
isDisableFlag(process.env.OMO_CLAUDE_DISABLE_POSTHOG) ||
|
||||
isTelemetryOptOutFlag(process.env.OMO_CLAUDE_SEND_ANONYMOUS_TELEMETRY)
|
||||
)
|
||||
}
|
||||
|
||||
export function getPostHogApiKey(): string {
|
||||
const explicit = process.env.POSTHOG_API_KEY
|
||||
if (explicit === undefined) {
|
||||
return DEFAULT_POSTHOG_API_KEY
|
||||
}
|
||||
return explicit.trim()
|
||||
}
|
||||
|
||||
export function hasPostHogApiKey(): boolean {
|
||||
return getPostHogApiKey().length > 0
|
||||
}
|
||||
|
||||
export function getPostHogHost(): string {
|
||||
return process.env.POSTHOG_HOST?.trim() || DEFAULT_POSTHOG_HOST
|
||||
}
|
||||
@@ -1,4 +1,12 @@
|
||||
// Placeholder — telemetry identity, posthog client, env-flags, and data-path
|
||||
// are authored in the telemetry-fork task. Re-exported from here so
|
||||
// `@oh-my-opencode/omo-claude/telemetry` resolves throughout the build.
|
||||
export {};
|
||||
export {
|
||||
__resetActivityStateProviderForTesting,
|
||||
__resetOsProviderForTesting,
|
||||
__setActivityStateProviderForTesting,
|
||||
__setOsProviderForTesting,
|
||||
createCliPostHog,
|
||||
createInstallPostHog,
|
||||
createPluginPostHog,
|
||||
getPostHogDistinctId,
|
||||
} from "./posthog"
|
||||
|
||||
export type { PostHogActivityReason, PostHogClient } from "./posthog"
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { existsSync, mkdirSync, readFileSync } from "node:fs"
|
||||
import { join } from "node:path"
|
||||
|
||||
import { writeFileAtomically } from "./atomic-write"
|
||||
import { getActivityStateDir } from "./data-path"
|
||||
|
||||
export type PostHogActivityState = {
|
||||
readonly lastActiveDayUTC?: string
|
||||
}
|
||||
|
||||
export type PostHogActivityCaptureState = {
|
||||
readonly dayUTC: string
|
||||
readonly captureDaily: boolean
|
||||
}
|
||||
|
||||
const POSTHOG_ACTIVITY_STATE_FILE = "posthog-activity.json"
|
||||
|
||||
function getPostHogActivityStateFilePath(): string {
|
||||
return join(getActivityStateDir(), POSTHOG_ACTIVITY_STATE_FILE)
|
||||
}
|
||||
|
||||
function getUtcDayString(date: Date): string {
|
||||
return date.toISOString().slice(0, 10)
|
||||
}
|
||||
|
||||
function isPostHogActivityState(value: unknown): value is PostHogActivityState {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function readPostHogActivityState(): PostHogActivityState {
|
||||
const stateFilePath = getPostHogActivityStateFilePath()
|
||||
|
||||
if (!existsSync(stateFilePath)) {
|
||||
return {}
|
||||
}
|
||||
|
||||
try {
|
||||
const stateContent = readFileSync(stateFilePath, "utf-8")
|
||||
const stateJson: unknown = JSON.parse(stateContent)
|
||||
|
||||
if (!isPostHogActivityState(stateJson)) {
|
||||
return {}
|
||||
}
|
||||
|
||||
return stateJson
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
function writePostHogActivityState(nextState: PostHogActivityState): void {
|
||||
const stateDir = getActivityStateDir()
|
||||
const stateFilePath = getPostHogActivityStateFilePath()
|
||||
|
||||
try {
|
||||
mkdirSync(stateDir, { recursive: true })
|
||||
writeFileAtomically(stateFilePath, `${JSON.stringify(nextState, null, 2)}\n`)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
export function getPostHogActivityCaptureState(
|
||||
now: Date = new Date(),
|
||||
): PostHogActivityCaptureState {
|
||||
const state = readPostHogActivityState()
|
||||
const dayUTC = getUtcDayString(now)
|
||||
const captureDaily = state.lastActiveDayUTC !== dayUTC
|
||||
|
||||
if (captureDaily) {
|
||||
writePostHogActivityState({
|
||||
...state,
|
||||
lastActiveDayUTC: dayUTC,
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
dayUTC,
|
||||
captureDaily,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
import { createHash } from "node:crypto"
|
||||
import os from "node:os"
|
||||
|
||||
import { PostHog } from "posthog-node"
|
||||
import packageJson from "../../package.json" with { type: "json" }
|
||||
|
||||
import { getPostHogApiKey, getPostHogHost, hasPostHogApiKey, shouldDisablePostHog } from "./env-flags"
|
||||
import { getPostHogActivityCaptureState } from "./posthog-activity-state"
|
||||
import {
|
||||
DEFAULT_POSTHOG_API_KEY,
|
||||
DEFAULT_POSTHOG_HOST,
|
||||
EVENT_NAME,
|
||||
PACKAGE_NAME,
|
||||
PRODUCT_NAME,
|
||||
} from "./product-identity"
|
||||
|
||||
export { DEFAULT_POSTHOG_API_KEY, DEFAULT_POSTHOG_HOST }
|
||||
|
||||
export type PostHogSource = "cli" | "plugin" | "install"
|
||||
export type PostHogActivityReason = "install_started" | "install_completed" | "cli_run" | "session_start"
|
||||
|
||||
export type PostHogClient = {
|
||||
trackActive: (distinctId: string, reason: PostHogActivityReason) => void
|
||||
shutdown: () => Promise<void>
|
||||
}
|
||||
|
||||
type OsProvider = Pick<typeof os, "arch" | "cpus" | "hostname" | "platform" | "release" | "totalmem" | "type">
|
||||
type ActivityStateProvider = typeof getPostHogActivityCaptureState
|
||||
|
||||
let osProviderOverride: OsProvider | null = null
|
||||
let activityStateProviderOverride: ActivityStateProvider | null = null
|
||||
|
||||
const NO_OP_POSTHOG: PostHogClient = {
|
||||
trackActive: () => undefined,
|
||||
shutdown: async () => undefined,
|
||||
}
|
||||
|
||||
type PostHogCaptureEvent = Parameters<PostHog["capture"]>[0]
|
||||
|
||||
function resolveOsProvider(): OsProvider {
|
||||
return osProviderOverride ?? os
|
||||
}
|
||||
|
||||
function resolveActivityStateProvider(): ActivityStateProvider {
|
||||
return activityStateProviderOverride ?? getPostHogActivityCaptureState
|
||||
}
|
||||
|
||||
function getSafeCpuInfo(): { readonly count: number; readonly model: string | undefined } {
|
||||
try {
|
||||
const cpuInfo = resolveOsProvider().cpus()
|
||||
return {
|
||||
count: cpuInfo.length,
|
||||
model: cpuInfo[0]?.model,
|
||||
}
|
||||
} catch {
|
||||
return {
|
||||
count: 0,
|
||||
model: undefined,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getSharedProperties(source: PostHogSource): NonNullable<PostHogCaptureEvent["properties"]> {
|
||||
const osProvider = resolveOsProvider()
|
||||
const cpuInfo = getSafeCpuInfo()
|
||||
|
||||
return {
|
||||
platform: PRODUCT_NAME,
|
||||
product_name: PRODUCT_NAME,
|
||||
package_name: PACKAGE_NAME,
|
||||
package_version: packageJson.version,
|
||||
runtime: "bun",
|
||||
runtime_version: process.versions.bun ?? process.version,
|
||||
source,
|
||||
$os: osProvider.platform(),
|
||||
$os_version: osProvider.release(),
|
||||
os_arch: osProvider.arch(),
|
||||
os_type: osProvider.type(),
|
||||
cpu_count: cpuInfo.count,
|
||||
cpu_model: cpuInfo.model,
|
||||
total_memory_gb: Math.round(osProvider.totalmem() / 1024 / 1024 / 1024),
|
||||
locale: Intl.DateTimeFormat().resolvedOptions().locale,
|
||||
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||
shell: process.env.SHELL,
|
||||
ci: Boolean(process.env.CI),
|
||||
terminal: process.env.TERM_PROGRAM,
|
||||
}
|
||||
}
|
||||
|
||||
function createPostHogClient(
|
||||
source: PostHogSource,
|
||||
options: ConstructorParameters<typeof PostHog>[1],
|
||||
): PostHogClient {
|
||||
if (shouldDisablePostHog() || !hasPostHogApiKey()) {
|
||||
return NO_OP_POSTHOG
|
||||
}
|
||||
|
||||
let client: PostHog
|
||||
try {
|
||||
client = new PostHog(getPostHogApiKey(), {
|
||||
...options,
|
||||
host: getPostHogHost(),
|
||||
disableGeoip: false,
|
||||
})
|
||||
} catch {
|
||||
return NO_OP_POSTHOG
|
||||
}
|
||||
|
||||
const sharedProperties = getSharedProperties(source)
|
||||
|
||||
return {
|
||||
trackActive: (distinctId, reason) => {
|
||||
const activityState = resolveActivityStateProvider()()
|
||||
if (!activityState.captureDaily) {
|
||||
return
|
||||
}
|
||||
|
||||
client.capture({
|
||||
distinctId,
|
||||
event: EVENT_NAME,
|
||||
properties: {
|
||||
...sharedProperties,
|
||||
$process_person_profile: false,
|
||||
day_utc: activityState.dayUTC,
|
||||
reason,
|
||||
},
|
||||
})
|
||||
},
|
||||
shutdown: async () => client.shutdown(),
|
||||
}
|
||||
}
|
||||
|
||||
export function getPostHogDistinctId(): string {
|
||||
return createHash("sha256").update(`omo-claude:${resolveOsProvider().hostname()}`).digest("hex")
|
||||
}
|
||||
|
||||
export function createCliPostHog(): PostHogClient {
|
||||
return createPostHogClient("cli", {
|
||||
enableExceptionAutocapture: false,
|
||||
enableLocalEvaluation: false,
|
||||
strictLocalEvaluation: true,
|
||||
disableRemoteConfig: true,
|
||||
flushAt: 1,
|
||||
flushInterval: 0,
|
||||
})
|
||||
}
|
||||
|
||||
export function createInstallPostHog(): PostHogClient {
|
||||
return createPostHogClient("install", {
|
||||
enableExceptionAutocapture: false,
|
||||
enableLocalEvaluation: false,
|
||||
strictLocalEvaluation: true,
|
||||
disableRemoteConfig: true,
|
||||
flushAt: 1,
|
||||
flushInterval: 0,
|
||||
})
|
||||
}
|
||||
|
||||
export function createPluginPostHog(): PostHogClient {
|
||||
return createPostHogClient("plugin", {
|
||||
enableExceptionAutocapture: false,
|
||||
enableLocalEvaluation: false,
|
||||
strictLocalEvaluation: true,
|
||||
disableRemoteConfig: true,
|
||||
flushAt: 1,
|
||||
flushInterval: 0,
|
||||
})
|
||||
}
|
||||
|
||||
/** @internal test-only */
|
||||
export function __setOsProviderForTesting(provider: OsProvider): void {
|
||||
osProviderOverride = provider
|
||||
}
|
||||
|
||||
/** @internal test-only */
|
||||
export function __resetOsProviderForTesting(): void {
|
||||
osProviderOverride = null
|
||||
}
|
||||
|
||||
/** @internal test-only */
|
||||
export function __setActivityStateProviderForTesting(provider: ActivityStateProvider): void {
|
||||
activityStateProviderOverride = provider
|
||||
}
|
||||
|
||||
/** @internal test-only */
|
||||
export function __resetActivityStateProviderForTesting(): void {
|
||||
activityStateProviderOverride = null
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import packageJson from "../../package.json" with { type: "json" }
|
||||
|
||||
export const PRODUCT_NAME = "omo-claude"
|
||||
export const PACKAGE_NAME = "@oh-my-opencode/omo-claude"
|
||||
export const CACHE_DIR_NAME = "omo-claude"
|
||||
export const EVENT_NAME = "omo_claude_daily_active"
|
||||
export const LEGACY_PARENT_PACKAGE = "oh-my-opencode"
|
||||
export const DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com"
|
||||
export const DEFAULT_POSTHOG_API_KEY = "phc_CFJhj5HyvA62QPhvyaUCtaq23aUfznnijg5VaaGkNk74"
|
||||
|
||||
export function getProductVersion(): string {
|
||||
return packageJson.version
|
||||
}
|
||||
@@ -3,6 +3,8 @@
|
||||
"target": "ESNext",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"noEmit": true,
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
|
||||
Reference in New Issue
Block a user