import { sha256 } from "./auth.ts"; import type { Actor, Role } from "./contract/actor.ts"; import type { Visibility } from "./contract/views.ts"; interface AnalyticsConfig { readonly POSTHOG_ENABLED?: string; readonly POSTHOG_PROJECT_TOKEN?: string; readonly POSTHOG_HOST?: string; } type AccountEvent = | { readonly name: "account.signed_up"; readonly userId: string; readonly entryPath: "open" | "admin" | "invitation" } | { readonly name: "account.approved"; readonly userId: string; readonly approvalPath: "open" | "admin" | "invitation" } | { readonly name: "account.signed_in"; readonly userId: string } | { readonly name: "member.joined"; readonly userId: string; readonly namespaceId: string; readonly role: Role; readonly joinPath: "new_account" | "existing_account" }; type RepositoryEvent = { readonly namespaceId: string; readonly namespaceKind: "user" | "org"; readonly visibility: Visibility; readonly entryPath: "new_project" | "import" | "fork"; readonly importUrl?: string; } & ( | { readonly name: "repo.created" | "repo.imported" | "repo.forked"; readonly repoId: string } | { readonly name: "repo.provision_failed"; readonly reason: "conflict" | "storage_unavailable" } ); /** Work on a branch. The branch name itself never leaves the backend. */ type Work = { readonly branch: string | null }; type WorkEvent = { readonly repoId: string; readonly namespaceId: string } & ( | { readonly name: "agent.connected" } | ({ readonly name: "task.taken" | "work.rejected" | "work.corrected" | "review.thread_resolved" | "agent.push_accepted" } & Work) | ({ readonly name: "agent.directed"; readonly channel: "pull" | "thread"; readonly assigned: boolean } & Work) | ({ readonly name: "commits.recorded"; readonly commitCount: number; readonly decisionCount: number } & Work) | ({ readonly name: "work.landed"; readonly mergeMethod: "web" | "push" } & Work) ); type EventName = AccountEvent["name"] | RepositoryEvent["name"] | WorkEvent["name"] | "$groupidentify"; const HOSTS = new Set(["https://us.i.posthog.com", "https://eu.i.posthog.com"]); export function captureAccountEvent(config: AnalyticsConfig, ctx: Pick, event: AccountEvent): void { const properties = { subject_kind: "human", is_user_activity: event.name !== "account.approved", ...(event.name === "account.signed_up" ? { entry_path: event.entryPath } : {}), ...(event.name === "account.approved" ? { approval_path: event.approvalPath } : {}), ...(event.name === "member.joined" ? { namespace_id: event.namespaceId, role: event.role, join_path: event.joinPath, $groups: { workspace: event.namespaceId } } : {}), }; if (!event.userId) return; capture(config, ctx, `human:${event.userId}`, event.name, properties); } export function captureRepositoryEvent(config: AnalyticsConfig, ctx: Pick, actor: Actor, event: RepositoryEvent): void { if (event.name !== "repo.provision_failed") { captureActorEvent(config, ctx, actor, "$groupidentify", event.namespaceId, { $group_type: "workspace", $group_key: event.namespaceId, $group_set: { kind: event.namespaceKind } }); } captureActorEvent(config, ctx, actor, event.name, event.namespaceId, { namespace_id: event.namespaceId, namespace_kind: event.namespaceKind, visibility: event.visibility, entry_path: event.entryPath, ...(event.entryPath === "import" ? { import_provider: importProvider(event.importUrl) } : {}), ...(event.name === "repo.provision_failed" ? { failure_reason: event.reason } : { repo_id: event.repoId }), }); } export function captureWorkEvent(config: AnalyticsConfig, ctx: Pick, actor: Actor, event: WorkEvent): void { const base = { namespace_id: event.namespaceId, repo_id: event.repoId, ...(event.name === "work.landed" ? { merge_method: event.mergeMethod } : {}), ...(event.name === "agent.directed" ? { channel: event.channel, assigned: event.assigned } : {}), ...(event.name === "commits.recorded" ? { commit_count: event.commitCount, decision_count: event.decisionCount } : {}), }; const properties = event.name === "agent.connected" ? base : workKey(event.repoId, event.branch).then((work_key) => ({ ...base, work_key })); captureActorEvent(config, ctx, actor, event.name, event.namespaceId, properties); } /** A stable key for the work on one branch of one repository, so a work cycle can be followed without its branch name. */ export async function workKey(repoId: string, branch: string | null): Promise { return branch === null ? null : (await sha256(`${repoId}\n${branch}`)).slice(0, 16); } function captureActorEvent(config: AnalyticsConfig, ctx: Pick, actor: Actor, name: EventName, workspaceId: string, pending: object | Promise): void { if (actor.kind === "anonymous") return; const identity = actor.kind === "human" ? `human:${actor.person.id}` : `agent:${actor.sessionId}`; const complete = (properties: object) => ({ actor_kind: actor.kind, subject_kind: actor.kind, is_user_activity: actor.kind === "human", auth_method: actor.kind === "human" ? actor.via : "agent", ...properties, $groups: { workspace: workspaceId }, ...(actor.kind === "agent" ? { owner_id: `human:${actor.onBehalfOf.id}`, $process_person_profile: false } : {}), }); capture(config, ctx, identity, name, pending instanceof Promise ? pending.then(complete) : complete(pending)); } function importProvider(url: string | undefined): "github" | "gitlab" | "bitbucket" | "other" { try { const hostname = new URL(url ?? "").hostname; if (hostname === "github.com") return "github"; if (hostname === "gitlab.com") return "gitlab"; if (hostname === "bitbucket.org") return "bitbucket"; } catch {} return "other"; } function capture(config: AnalyticsConfig, ctx: Pick, identity: string, name: EventName, properties: object | Promise): void { const host = config.POSTHOG_HOST; const token = config.POSTHOG_PROJECT_TOKEN; if (config.POSTHOG_ENABLED !== "true" || !token || !host || !HOSTS.has(host)) return; const envelope = { api_key: token, distinct_id: identity, event: name, uuid: crypto.randomUUID(), timestamp: new Date().toISOString() }; const send = (resolved: object) => deliver(`${host}/i/v0/e/`, { ...envelope, properties: { schema_version: 1, $geoip_disable: true, ...resolved } }); ctx.waitUntil(properties instanceof Promise ? properties.then(send) : send(properties)); } async function deliver(url: string, payload: object): Promise { try { const response = await fetch(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(payload), signal: AbortSignal.timeout(5000), redirect: "manual", }); if (!response.ok) console.warn("posthog_delivery_failed", { status: response.status }); await response.body?.cancel(); } catch { console.warn("posthog_delivery_failed", { reason: "transport" }); } }