import { createHash, randomUUID } from "node:crypto"; import { readFileSync } from "node:fs"; import { getBuiltinModel, getBuiltinProviders, type BuiltinProvider, } from "@earendil-works/pi-ai/providers/all"; import { asStringIdentifier, type TelemetryCorrelationId, } from "./identifier-types"; import { sanitizeTelemetryParentMux, sanitizeTelemetryTerminalProgram, } from "./environment"; import { parseJsonRecord } from "./json-input"; import { assertNever } from "./assert-never"; export const TELEMETRY_ENDPOINT = "https://us.i.posthog.com/i/v0/e/"; export const TELEMETRY_SCHEMA_VERSION = 10; const TELEMETRY_PROJECT_TOKEN = "phc_B4H7xPiFbwPJmKbdeQtk7FeP3PnQF5AMpQJXCgGYeqFR"; const TELEMETRY_TIMEOUT_MS = 1_500; export const MAX_TELEMETRY_DEDUPE_KEYS = 2_048; const MAX_TELEMETRY_DEDUPE_KEY_LENGTH = 128; const MAX_TELEMETRY_DEPTH = 64; const MAX_TELEMETRY_DURATION_MS = 30 * 24 * 60 * 60 * 1_000; export type TelemetryMode = "straight" | "orchestrator" | "orchestrator_v2"; export type TelemetrySessionHost = "agterm" | "orca" | "unknown"; export type TelemetryExecution = "in-process" | "interactive"; export type TelemetryMux = | "none" | "tmux" | "zellij" | "herdr" | "rex" | "herdr-core" | "wezterm" | "cmux"; export type TelemetryTrafficOrigin = | "usage" | "development" | "test" | "unknown"; export const TELEMETRY_ORIGIN_ENV = "PI_SUBAGENTURA_TELEMETRY_ORIGIN"; export type TelemetryLaunchOutcome = | "started" | "recovered" | "rejected" | "cancelled"; export type TelemetryRequestedExecution = TelemetryExecution; export type TelemetryRequestedMux = | "herdr-core" | "wezterm" | "none" | "auto" | "tmux" | "zellij" | "herdr" | "rex" | "cmux"; export type TelemetrySpawnFailureMux = TelemetryMux | "unknown"; export type TelemetryInvocationSource = | "with_context" | "isolated" | "interactive" | "workflow"; export type TelemetryCompletionPolicy = "inline" | "each" | "group"; export type TelemetryAgentStatus = "success" | "error" | "cancelled"; export type TelemetryResultSource = "in-process" | "interactive" | "workflow"; export type TelemetryDelivery = "manifest" | "notification"; export type TelemetryCompletionFailureStage = | "notice_persistence" | "manifest_dispatch" | "retry_exhausted" | "consumption_persistence" | "notification_dispatch" | "completion_publication"; export type TelemetryWorkflowInvocation = "tool" | "saved_command"; export type TelemetryWorkflowStatus = | "success" | "partial" | "error" | "cancelled"; export type TelemetryRecoveryReason = "startup" | "reload" | "resume"; export type TelemetryResultReadOutcome = | "consumed" | "already_consumed" | "empty" | "running" | "error" | "cancelled" | "wait_timeout" | "wait_cancelled" | "unavailable"; export type TelemetrySpawnFailureStage = | "depth_limit" | "capacity" | "context" | "model_resolution" | "session_creation" | "mux_resolution" | "pane_launch" | "state_persistence" | "registration" | "parent_shutdown" | "unknown"; export type TelemetrySpawnFailureOperation = | "lineage_bootstrap_check" | "routing_metadata_validation" | "explicit_context_limit" | "completion_policy_validation" | "parent_context_serialization" | "cwd_validation" | "persona_limit" | "interactive_path_creation" | "lineage_store_resolution" | "artifact_write" | "system_prompt_write" | "mux_resolution" | "model_resolution" | "pane_launch" | "interactive_state_write" | "lineage_manifest_write" | "child_command_build" | "lineage_bootstrap_write" | "launch_script_write" | "completion_registration"; export interface TelemetryLaunchResolution { outcome: TelemetryLaunchOutcome; requested_execution: TelemetryRequestedExecution; requested_mux: TelemetryRequestedMux; execution?: TelemetryExecution; mux: TelemetrySpawnFailureMux; invocation_source: TelemetryInvocationSource; async: boolean; depth?: number; depth_bucket: TelemetryDepthBucket; completion_policy: TelemetryCompletionPolicy; duration_ms?: number; fallback_attempted: boolean; initial_failure_stage?: TelemetrySpawnFailureStage; initial_failure_operation?: TelemetrySpawnFailureOperation; final_failure_stage?: TelemetrySpawnFailureStage; final_failure_operation?: TelemetrySpawnFailureOperation; } export type TelemetryAgentLaunchResolvedEvent = { event: "agent_launch_resolved"; } & TelemetryLaunchResolution; export type TelemetryTerminalReason = | "completed" | "agent_error" | "process_exit" | "timeout" | "explicit_cancel" | "parent_cancelled" | "session_shutdown" | "fresh_session" | "unknown"; export type TelemetryDepthBucket = "1" | "2" | "3" | "4-7" | "8+" | "unknown"; export type TelemetryDurationBucket = | "<1s" | "1-5s" | "5-30s" | "30s-2m" | "2-10m" | "10m+" | "unknown"; export type TelemetryErrorCategory = | "provider" | "timeout" | "schema" | "capacity" | "session" | "mux" | "transport" | "artifact" | "internal" | "unknown"; export type TelemetryErrorStage = | "spawn" | "turn" | "provider" | "completion" | "polling" | "delivery" | "schema_validation" | "workflow"; export type TelemetryAgentStopReason = "error" | "aborted"; export type TelemetryExitCodeBucket = "zero" | "nonzero" | "unknown"; export type TelemetryRuntimeFailureKind = | "artifact_unreadable" | "artifact_malformed" | "artifact_oversized" | "mux_probe" | "workflow_capacity" | "consumption_persistence" | "notification_dispatch" | "completion_publication"; export type TelemetryRuntimeFailureReporter = | "artifact_poller" | "workflow_waiter" | "workflow_runner"; export type TelemetryRuntimeFailureImpact = "degraded" | "blocked" | "unknown"; export type TelemetryRuntimeExecution = TelemetryExecution; export type TelemetryRuntimeMux = TelemetrySpawnFailureMux; export type TelemetryRuntimeImpact = TelemetryRuntimeFailureImpact; export interface TelemetryRuntimeFailureDimensions { execution?: TelemetryRuntimeExecution; mux?: TelemetryRuntimeMux; reporter?: TelemetryRuntimeFailureReporter; impact?: TelemetryRuntimeImpact; } export type TelemetryErrorCountBucket = "0" | "1" | "2+" | "unknown"; export const TELEMETRY_OPERATION_NAMES = { tool: [ "subagent_with_context", "subagent_isolated", "subagent_interactive", "get_subagent_status", "get_subagent_result", "cancel_subagent", "prune_subagent_jobs", "list_available_models", "cleanup_subagent_artifacts", "get_current_pane_activity", "get_interactive_subagent_status", "cancel_interactive_subagent", "send_interactive_subagent_message", "read_subagent_artifact", "list_subagent_artifacts", "list_orchestrator_agents", "update_orchestrator_agent_description", "resolve_orchestrator_route", "workflow", "get_workflow_status", "get_workflow_result", "cancel_workflow", "save_workflow", "list_workflows", "delete_workflow", ], command: [ "workflow", "workflows", "list-workflows", "workflow-status", "workflow-tree", "delete-workflow", "subagents", "cancel-all-flows", ], shortcut: ["ctrl+alt+a", "ctrl+alt+x"], } as const; export type TelemetrySurface = keyof typeof TELEMETRY_OPERATION_NAMES; export type TelemetryOperation = (typeof TELEMETRY_OPERATION_NAMES)[TelemetrySurface][number]; export type TelemetryOperationOutcome = | "returned" | "reported_error" | "threw" | "aborted"; export type TelemetryOperationResultStatus = | "ok" | "started" | "running" | "completed" | "cancelled" | "wait_timeout" | "wait_cancelled" | "unavailable" | "invalid_input" | "confirmation_required" | "degraded" | "error" | "unknown"; export type TelemetrySessionFailureStage = | "telemetry_persistence" | "routing_recovery" | "state_recovery" | "wake_recovery"; export function telemetryOperationName( surface: TelemetrySurface, name: string, ): TelemetryOperation | undefined { return (TELEMETRY_OPERATION_NAMES[surface] as readonly string[]).includes( name, ) ? (name as TelemetryOperation) : undefined; } interface TelemetryAgentDimensions { execution: TelemetryExecution; mux: TelemetryMux; invocation_source: TelemetryInvocationSource; model: string | undefined; async: boolean; depth: number | undefined; depth_bucket: TelemetryDepthBucket; completion_policy: TelemetryCompletionPolicy; } type TelemetrySpawnFailureDimensions = Omit & { mux: TelemetrySpawnFailureMux; }; export type TelemetryEvent = | { event: "session_started"; session_host?: TelemetrySessionHost; terminal_program?: TelemetryTerminalProgram; parent_mux?: TelemetryParentMux; } | { event: "session_setup_failed"; failure_stage: TelemetrySessionFailureStage; } | { event: "operation_started"; surface: TelemetrySurface; operation: TelemetryOperation; session_role: "root" | "child"; } | { event: "operation_completed"; surface: TelemetrySurface; operation: TelemetryOperation; session_role: "root" | "child"; outcome: TelemetryOperationOutcome; result_status: TelemetryOperationResultStatus; duration_ms?: number; } | ({ event: "agent_created"; spawn_duration_ms?: number; } & TelemetryAgentDimensions) | ({ event: "agent_spawn_failed"; failure_stage: TelemetrySpawnFailureStage; failure_operation?: TelemetrySpawnFailureOperation; spawn_duration_ms?: number; } & TelemetrySpawnFailureDimensions) | TelemetryAgentLaunchResolvedEvent | ({ event: "task_started"; unit: "job" | "turn" } & TelemetryAgentDimensions) | { event: "interactive_message_sent"; direction: "parent_to_child"; count: number; } | ({ event: "task_completed"; unit: "job" | "turn"; status: TelemetryAgentStatus; terminal_reason: TelemetryTerminalReason; error_category?: TelemetryErrorCategory; error_stage?: TelemetryErrorStage; agent_stop_reason?: TelemetryAgentStopReason; exit_code_bucket?: TelemetryExitCodeBucket; duration_ms: number | undefined; child_conversation_message_count: number | undefined; } & TelemetryAgentDimensions) | { event: "workflow_started"; invocation: TelemetryWorkflowInvocation; async: boolean; completion_policy: TelemetryCompletionPolicy; } | { event: "workflow_completed"; invocation: TelemetryWorkflowInvocation; async: boolean; completion_policy: TelemetryCompletionPolicy; status: TelemetryWorkflowStatus; terminal_reason: TelemetryTerminalReason; agents_spawned: number; error_count: number; error_category?: TelemetryErrorCategory; error_stage?: TelemetryErrorStage; duration_ms?: number; } | { event: "session_recovered"; reason: TelemetryRecoveryReason; total_count: number; alive_count: number; terminal_count: number; unknown_count: number; } | { event: "completion_delivered"; delivery: TelemetryDelivery; count: number; delivery_latency_ms?: number; } | { event: "completion_delivery_failed"; failure_stage: TelemetryCompletionFailureStage; retry_attempt: number; } | ({ event: "runtime_failure"; error_category: TelemetryErrorCategory; error_stage: TelemetryErrorStage; failure_kind: TelemetryRuntimeFailureKind; } & TelemetryRuntimeFailureDimensions) | { event: "result_read"; source: TelemetryResultSource; outcome: TelemetryResultReadOutcome; read_latency_ms?: number; }; export interface TelemetrySession { readonly enabled: boolean; readonly mode: TelemetryMode; readonly correlationId: string; readonly trafficOrigin: TelemetryTrafficOrigin; readonly capturedKeys: Set; active: boolean; } export interface AgentTelemetryContext { session: TelemetrySession; invocationSource: TelemetryInvocationSource; async: boolean; depth: number | undefined; completionPolicy: TelemetryCompletionPolicy; } interface CaptureOptions { allowInactive?: boolean; dedupeKey?: string; fetchImpl?: typeof fetch; } export interface TelemetryPayload { api_key: string; event: `pi_subagentura_${TelemetryEvent["event"]}`; distinct_id: string; properties: Record; } const packageVersion = readPackageVersion(); function readPackageVersion(): string { try { const packageJson = parseJsonRecord( readFileSync(new URL("../package.json", import.meta.url), "utf8"), ); return typeof packageJson?.version === "string" ? packageJson.version : "unknown"; } catch { // Missing version metadata must never prevent the extension from loading. return "unknown"; } } function validCorrelationId( value: string | undefined, ): TelemetryCorrelationId | undefined { return value && /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test( value, ) ? asStringIdentifier<"telemetry-correlation">(value.toLowerCase()) : undefined; } export function createTelemetrySession( enabled: boolean, mode: TelemetryMode | "manual" = "straight", inheritedCorrelationId?: string, trafficOrigin?: TelemetryTrafficOrigin, ): TelemetrySession { return { enabled, mode: mode === "manual" ? "straight" : mode, correlationId: validCorrelationId(inheritedCorrelationId) ?? asStringIdentifier<"telemetry-correlation">(randomUUID()), trafficOrigin: trafficOrigin === undefined ? resolveTelemetryTrafficOrigin() : sanitizeTelemetryTrafficOrigin(trafficOrigin), capturedKeys: new Set(), active: true, }; } export function resolveTelemetryMode( orchestratorMode: boolean, orchestratorV2Mode: boolean, ): TelemetryMode { if (orchestratorV2Mode) return "orchestrator_v2"; return orchestratorMode ? "orchestrator" : "straight"; } /** * One dedupe key for a manifest delivery, shared by every emit site so two * callers cannot double-count the same manifest, and hashed past a bound so a * large manifest cannot grow the retained key set without limit. */ export function manifestDeliveryDedupeKey( completionIds: readonly string[], ): string { const joined = completionIds.join(":"); if (joined.length <= MAX_TELEMETRY_DEDUPE_KEY_LENGTH) { return `manifest:${joined}`; } const digest = createHash("sha256").update(joined).digest("hex"); return `manifest:${completionIds.length}:${digest}`; } export function retireTelemetrySession( session: TelemetrySession | undefined, ): void { if (session) session.active = false; } function builtInModel(provider: string, modelId: string): boolean { try { return ( getBuiltinModel(provider as BuiltinProvider, modelId as never) !== undefined ); } catch { return false; } } /** Never forward arbitrary model-generated strings into telemetry. */ export function sanitizeTelemetryModel(model: string | undefined): string { if (model === undefined || model === "") return "default"; if (model === "default" || model === "custom") return model; const separator = model.indexOf("/"); if (separator > 0) { const provider = model.slice(0, separator); const modelId = model.slice(separator + 1); return builtInModel(provider, modelId) ? model : "custom"; } // The generated provider catalog is used only to label telemetry. Any // lookup failure must degrade this dimension, not fail sub-agent launch. try { for (const provider of getBuiltinProviders()) { if (builtInModel(provider, model)) return model; } } catch { return "custom"; } return "custom"; } const TELEMETRY_ERROR_CATEGORIES: readonly TelemetryErrorCategory[] = [ "provider", "timeout", "schema", "capacity", "session", "mux", "transport", "artifact", "internal", "unknown", ]; const TELEMETRY_ERROR_STAGES: readonly TelemetryErrorStage[] = [ "spawn", "turn", "provider", "completion", "polling", "delivery", "schema_validation", "workflow", ]; const TELEMETRY_AGENT_STOP_REASONS: readonly TelemetryAgentStopReason[] = [ "error", "aborted", ]; const TELEMETRY_EXIT_CODE_BUCKETS: readonly TelemetryExitCodeBucket[] = [ "zero", "nonzero", "unknown", ]; const TELEMETRY_RUNTIME_FAILURE_KINDS: readonly TelemetryRuntimeFailureKind[] = [ "artifact_unreadable", "artifact_malformed", "artifact_oversized", "mux_probe", "workflow_capacity", "consumption_persistence", "notification_dispatch", "completion_publication", ]; const TELEMETRY_COMPLETION_FAILURE_STAGES: readonly TelemetryCompletionFailureStage[] = [ "notice_persistence", "manifest_dispatch", "retry_exhausted", "consumption_persistence", "notification_dispatch", "completion_publication", ]; const TELEMETRY_SPAWN_FAILURE_OPERATIONS: readonly TelemetrySpawnFailureOperation[] = [ "lineage_bootstrap_check", "routing_metadata_validation", "explicit_context_limit", "completion_policy_validation", "parent_context_serialization", "cwd_validation", "persona_limit", "interactive_path_creation", "lineage_store_resolution", "artifact_write", "system_prompt_write", "mux_resolution", "model_resolution", "pane_launch", "interactive_state_write", "lineage_manifest_write", "child_command_build", "lineage_bootstrap_write", "launch_script_write", "completion_registration", ]; const TELEMETRY_SPAWN_FAILURE_STAGES: readonly TelemetrySpawnFailureStage[] = [ "depth_limit", "capacity", "context", "model_resolution", "session_creation", "mux_resolution", "pane_launch", "state_persistence", "registration", "parent_shutdown", "unknown", ]; const TELEMETRY_TRAFFIC_ORIGINS: readonly TelemetryTrafficOrigin[] = [ "usage", "development", "test", "unknown", ]; const TELEMETRY_LAUNCH_OUTCOMES: readonly TelemetryLaunchOutcome[] = [ "started", "recovered", "rejected", "cancelled", ]; const TELEMETRY_EXECUTIONS: readonly TelemetryExecution[] = [ "in-process", "interactive", ]; const TELEMETRY_MUXES: readonly TelemetrySpawnFailureMux[] = [ "none", "unknown", "tmux", "zellij", "herdr", "rex", "herdr-core", "wezterm", "cmux", ]; const TELEMETRY_REQUESTED_MUXES: readonly TelemetryRequestedMux[] = [ "none", "auto", "tmux", "zellij", "herdr", "rex", "herdr-core", "wezterm", "cmux", ]; const TELEMETRY_INVOCATION_SOURCES: readonly TelemetryInvocationSource[] = [ "with_context", "isolated", "interactive", "workflow", ]; const TELEMETRY_COMPLETION_POLICIES: readonly TelemetryCompletionPolicy[] = [ "inline", "each", "group", ]; const TELEMETRY_RUNTIME_FAILURE_REPORTERS: readonly TelemetryRuntimeFailureReporter[] = ["artifact_poller", "workflow_waiter", "workflow_runner"]; const TELEMETRY_RUNTIME_FAILURE_IMPACTS: readonly TelemetryRuntimeFailureImpact[] = ["degraded", "blocked", "unknown"]; export function sanitizeTelemetryTrafficOrigin( value: unknown, ): TelemetryTrafficOrigin { return typeof value === "string" && TELEMETRY_TRAFFIC_ORIGINS.includes(value as TelemetryTrafficOrigin) ? (value as TelemetryTrafficOrigin) : "unknown"; } export function resolveTelemetryTrafficOrigin( value: unknown = process.env[TELEMETRY_ORIGIN_ENV], ): TelemetryTrafficOrigin { const normalizedValue = typeof value === "string" ? value.trim().toLowerCase() : value; return sanitizeTelemetryTrafficOrigin(normalizedValue); } export function sanitizeTelemetryLaunchOutcome( value: unknown, ): TelemetryLaunchOutcome | undefined { return typeof value === "string" && TELEMETRY_LAUNCH_OUTCOMES.includes(value as TelemetryLaunchOutcome) ? (value as TelemetryLaunchOutcome) : undefined; } export function sanitizeTelemetryExecution( value: unknown, ): TelemetryExecution | undefined { return typeof value === "string" && TELEMETRY_EXECUTIONS.includes(value as TelemetryExecution) ? (value as TelemetryExecution) : undefined; } export function sanitizeTelemetrySpawnFailureStage( value: unknown, ): TelemetrySpawnFailureStage | undefined { return typeof value === "string" && TELEMETRY_SPAWN_FAILURE_STAGES.includes(value as TelemetrySpawnFailureStage) ? (value as TelemetrySpawnFailureStage) : undefined; } export function sanitizeTelemetryRequestedMux( value: unknown, ): TelemetryRequestedMux | undefined { return typeof value === "string" && TELEMETRY_REQUESTED_MUXES.includes(value as TelemetryRequestedMux) ? (value as TelemetryRequestedMux) : undefined; } export function sanitizeTelemetryInvocationSource( value: unknown, ): TelemetryInvocationSource | undefined { return typeof value === "string" && TELEMETRY_INVOCATION_SOURCES.includes(value as TelemetryInvocationSource) ? (value as TelemetryInvocationSource) : undefined; } export function sanitizeTelemetryCompletionPolicy( value: unknown, ): TelemetryCompletionPolicy | undefined { return typeof value === "string" && TELEMETRY_COMPLETION_POLICIES.includes(value as TelemetryCompletionPolicy) ? (value as TelemetryCompletionPolicy) : undefined; } export function sanitizeTelemetrySpawnFailureMux( value: unknown, ): TelemetrySpawnFailureMux | undefined { return typeof value === "string" && TELEMETRY_MUXES.includes(value as TelemetrySpawnFailureMux) ? (value as TelemetrySpawnFailureMux) : undefined; } export function sanitizeTelemetryRuntimeFailureExecution( value: unknown, ): TelemetryExecution | undefined { return sanitizeTelemetryExecution(value); } export function sanitizeTelemetryRuntimeFailureMux( value: unknown, ): TelemetrySpawnFailureMux | undefined { return sanitizeTelemetrySpawnFailureMux(value); } export function sanitizeTelemetryRuntimeFailureReporter( value: unknown, ): TelemetryRuntimeFailureReporter | undefined { return typeof value === "string" && TELEMETRY_RUNTIME_FAILURE_REPORTERS.includes( value as TelemetryRuntimeFailureReporter, ) ? (value as TelemetryRuntimeFailureReporter) : undefined; } export function sanitizeTelemetryRuntimeFailureImpact( value: unknown, ): TelemetryRuntimeFailureImpact | undefined { return typeof value === "string" && TELEMETRY_RUNTIME_FAILURE_IMPACTS.includes( value as TelemetryRuntimeFailureImpact, ) ? (value as TelemetryRuntimeFailureImpact) : undefined; } /** Never forward arbitrary error categories into telemetry. */ export function sanitizeTelemetryErrorCategory( value: unknown, ): TelemetryErrorCategory { return typeof value === "string" && TELEMETRY_ERROR_CATEGORIES.includes(value as TelemetryErrorCategory) ? (value as TelemetryErrorCategory) : "unknown"; } /** Never forward arbitrary error stages into telemetry. */ export function sanitizeTelemetryErrorStage( value: unknown, ): TelemetryErrorStage | undefined { return typeof value === "string" && TELEMETRY_ERROR_STAGES.includes(value as TelemetryErrorStage) ? (value as TelemetryErrorStage) : undefined; } /** Never forward arbitrary stop reasons into telemetry. */ export function sanitizeTelemetryAgentStopReason( value: unknown, ): TelemetryAgentStopReason | undefined { return typeof value === "string" && TELEMETRY_AGENT_STOP_REASONS.includes(value as TelemetryAgentStopReason) ? (value as TelemetryAgentStopReason) : undefined; } /** Never forward arbitrary process exit buckets into telemetry. */ export function sanitizeTelemetryExitCodeBucket( value: unknown, ): TelemetryExitCodeBucket | undefined { return typeof value === "string" && TELEMETRY_EXIT_CODE_BUCKETS.includes(value as TelemetryExitCodeBucket) ? (value as TelemetryExitCodeBucket) : undefined; } /** Never forward arbitrary runtime failure kinds into telemetry. */ export function sanitizeTelemetryRuntimeFailureKind( value: unknown, ): TelemetryRuntimeFailureKind | undefined { return typeof value === "string" && TELEMETRY_RUNTIME_FAILURE_KINDS.includes( value as TelemetryRuntimeFailureKind, ) ? (value as TelemetryRuntimeFailureKind) : undefined; } /** Never forward arbitrary completion failure stages into telemetry. */ export function sanitizeTelemetryCompletionFailureStage( value: unknown, ): TelemetryCompletionFailureStage | undefined { return typeof value === "string" && TELEMETRY_COMPLETION_FAILURE_STAGES.includes( value as TelemetryCompletionFailureStage, ) ? (value as TelemetryCompletionFailureStage) : undefined; } /** Never forward arbitrary spawn-operation labels into telemetry. */ export function sanitizeTelemetrySpawnFailureOperation( value: unknown, ): TelemetrySpawnFailureOperation | undefined { return typeof value === "string" && TELEMETRY_SPAWN_FAILURE_OPERATIONS.includes( value as TelemetrySpawnFailureOperation, ) ? (value as TelemetrySpawnFailureOperation) : undefined; } export function telemetryErrorCountBucket( value: number | undefined, ): TelemetryErrorCountBucket { if (value === undefined || !Number.isFinite(value) || value < 0) { return "unknown"; } const count = Math.trunc(value); return count === 0 ? "0" : count === 1 ? "1" : "2+"; } export function telemetryDepthBucket( depth: number | undefined, ): TelemetryDepthBucket { if (!Number.isSafeInteger(depth) || depth === undefined || depth < 1) { return "unknown"; } if (depth <= 3) return String(depth) as "1" | "2" | "3"; return depth <= 7 ? "4-7" : "8+"; } export function telemetryDepth(depth: number | undefined): number | undefined { return Number.isSafeInteger(depth) && depth !== undefined && depth >= 1 && depth <= MAX_TELEMETRY_DEPTH ? depth : undefined; } export function telemetryDurationBucket( durationMs: number | undefined, ): TelemetryDurationBucket { if ( durationMs === undefined || !Number.isFinite(durationMs) || durationMs < 0 || durationMs > MAX_TELEMETRY_DURATION_MS ) { return "unknown"; } if (durationMs < 1_000) return "<1s"; if (durationMs < 5_000) return "1-5s"; if (durationMs < 30_000) return "5-30s"; if (durationMs < 120_000) return "30s-2m"; if (durationMs < 600_000) return "2-10m"; return "10m+"; } /** * Round away meaningless precision and drop implausible timers. A recovered or * corrupt start timestamp produces a duration no analysis should trust, so it * is reported as unknown rather than clamped to a bogus-but-plausible number. */ export function telemetryDurationMs( durationMs: number | undefined, ): number | undefined { if ( durationMs === undefined || !Number.isFinite(durationMs) || durationMs < 0 || durationMs > MAX_TELEMETRY_DURATION_MS ) { return undefined; } return Math.round(durationMs / 100) * 100; } function depthProperty(depth: number | undefined): { depth?: number } { const boundedDepth = telemetryDepth(depth); return boundedDepth === undefined ? {} : { depth: boundedDepth }; } type TelemetryDurationPropertyPrefix = | "spawn_duration" | "duration" | "delivery_latency" | "read_latency"; function durationProperties( prefix: TelemetryDurationPropertyPrefix, durationMs: number | undefined, ): Record { const boundedDuration = telemetryDurationMs(durationMs); return { [`${prefix}_bucket`]: telemetryDurationBucket(durationMs), ...(boundedDuration === undefined ? {} : { [`${prefix}_ms`]: boundedDuration }), }; } function boundedCount(value: number | undefined, max: number): number { if (!Number.isFinite(value)) return 0; return Math.min(Math.max(Math.trunc(value!), 0), max); } export function buildTelemetryPayload( session: TelemetrySession, event: TelemetryEvent, ): TelemetryPayload { const common = { $process_person_profile: false, $geoip_disable: true, $ip: "0.0.0.0", $lib: "pi-subagentura", $lib_version: packageVersion, schema_version: TELEMETRY_SCHEMA_VERSION, telemetry_session_id: session.correlationId, mode: session.mode, traffic_origin: sanitizeTelemetryTrafficOrigin(session.trafficOrigin), }; let properties: TelemetryPayload["properties"]; switch (event.event) { case "session_started": properties = { ...common, session_host: event.session_host === "agterm" ? "agterm" : event.session_host === "orca" ? "orca" : "unknown", terminal_program: sanitizeTelemetryTerminalProgram( event.terminal_program, ), parent_mux: sanitizeTelemetryParentMux(event.parent_mux), }; break; case "session_setup_failed": properties = { ...common, failure_stage: event.failure_stage }; break; case "operation_started": properties = { ...common, surface: event.surface, operation: event.operation, session_role: event.session_role, }; break; case "operation_completed": properties = { ...common, surface: event.surface, operation: event.operation, session_role: event.session_role, outcome: event.outcome, result_status: event.result_status, ...durationProperties("duration", event.duration_ms), }; break; case "agent_created": properties = { ...common, execution: event.execution, mux: event.mux, invocation_source: event.invocation_source, model: sanitizeTelemetryModel(event.model), async: event.async, ...depthProperty(event.depth), depth_bucket: event.depth_bucket, completion_policy: event.completion_policy, ...durationProperties("spawn_duration", event.spawn_duration_ms), }; break; case "agent_spawn_failed": { const failureOperation = sanitizeTelemetrySpawnFailureOperation( event.failure_operation, ); properties = { ...common, execution: event.execution, mux: event.mux, invocation_source: event.invocation_source, model: sanitizeTelemetryModel(event.model), async: event.async, ...depthProperty(event.depth), depth_bucket: event.depth_bucket, completion_policy: event.completion_policy, failure_stage: event.failure_stage, ...(failureOperation === undefined ? {} : { failure_operation: failureOperation }), ...durationProperties("spawn_duration", event.spawn_duration_ms), }; break; } case "agent_launch_resolved": { const outcome = sanitizeTelemetryLaunchOutcome(event.outcome); const requestedExecution = sanitizeTelemetryExecution( event.requested_execution, ); const requestedMux = sanitizeTelemetryRequestedMux(event.requested_mux); const execution = outcome === "started" || outcome === "recovered" ? sanitizeTelemetryExecution(event.execution) : undefined; const mux = sanitizeTelemetrySpawnFailureMux(event.mux) ?? "unknown"; const initialFailureStage = sanitizeTelemetrySpawnFailureStage( event.initial_failure_stage, ); const initialFailureOperation = sanitizeTelemetrySpawnFailureOperation( event.initial_failure_operation, ); const finalFailureStage = sanitizeTelemetrySpawnFailureStage( event.final_failure_stage, ); const finalFailureOperation = sanitizeTelemetrySpawnFailureOperation( event.final_failure_operation, ); const failureDimensions = { ...(initialFailureStage === undefined ? {} : { initial_failure_stage: initialFailureStage }), ...(initialFailureOperation === undefined ? {} : { initial_failure_operation: initialFailureOperation }), ...(finalFailureStage === undefined ? {} : { final_failure_stage: finalFailureStage }), ...(finalFailureOperation === undefined ? {} : { final_failure_operation: finalFailureOperation }), }; const invocationSource = sanitizeTelemetryInvocationSource( event.invocation_source, ); const completionPolicy = sanitizeTelemetryCompletionPolicy( event.completion_policy, ); properties = { ...common, ...(outcome === undefined ? {} : { outcome }), ...(requestedExecution === undefined ? {} : { requested_execution: requestedExecution }), ...(requestedMux === undefined ? {} : { requested_mux: requestedMux }), ...(execution === undefined ? {} : { execution }), mux, ...(invocationSource === undefined ? {} : { invocation_source: invocationSource }), async: event.async === true, ...depthProperty(event.depth), depth_bucket: telemetryDepthBucket(telemetryDepth(event.depth)), ...(completionPolicy === undefined ? {} : { completion_policy: completionPolicy }), ...durationProperties("duration", event.duration_ms), fallback_attempted: event.fallback_attempted === true, ...failureDimensions, }; break; } case "task_started": properties = { ...common, execution: event.execution, mux: event.mux, unit: event.unit, invocation_source: event.invocation_source, model: sanitizeTelemetryModel(event.model), async: event.async, ...depthProperty(event.depth), depth_bucket: event.depth_bucket, completion_policy: event.completion_policy, }; break; case "interactive_message_sent": properties = { ...common, direction: event.direction, count: boundedCount(event.count, 128), }; break; case "task_completed": { const errorStage = event.status === "error" ? sanitizeTelemetryErrorStage(event.error_stage) : undefined; const agentStopReason = event.status === "error" || event.status === "cancelled" ? sanitizeTelemetryAgentStopReason(event.agent_stop_reason) : undefined; const exitCodeBucket = event.terminal_reason === "process_exit" ? sanitizeTelemetryExitCodeBucket(event.exit_code_bucket) : undefined; properties = { ...common, execution: event.execution, mux: event.mux, unit: event.unit, invocation_source: event.invocation_source, model: sanitizeTelemetryModel(event.model), async: event.async, ...depthProperty(event.depth), depth_bucket: event.depth_bucket, completion_policy: event.completion_policy, status: event.status, terminal_reason: event.terminal_reason, ...(event.status === "error" ? { error_category: sanitizeTelemetryErrorCategory( event.error_category, ), ...(errorStage === undefined ? {} : { error_stage: errorStage }), } : {}), ...(agentStopReason === undefined ? {} : { agent_stop_reason: agentStopReason }), ...(exitCodeBucket === undefined ? {} : { exit_code_bucket: exitCodeBucket }), ...durationProperties("duration", event.duration_ms), ...(event.child_conversation_message_count === undefined ? {} : { child_conversation_message_count: boundedCount( event.child_conversation_message_count, 1_000, ), }), }; break; } case "workflow_started": properties = { ...common, invocation: event.invocation, async: event.async, completion_policy: event.completion_policy, }; break; case "workflow_completed": { const diagnosticStatus = event.status === "error" || event.status === "partial"; const errorCategory = diagnosticStatus ? sanitizeTelemetryErrorCategory(event.error_category) : undefined; const errorStage = diagnosticStatus ? sanitizeTelemetryErrorStage(event.error_stage) : undefined; properties = { ...common, invocation: event.invocation, async: event.async, completion_policy: event.completion_policy, status: event.status, terminal_reason: event.terminal_reason, ...(errorCategory === undefined ? {} : { error_category: errorCategory }), ...(errorStage === undefined ? {} : { error_stage: errorStage }), ...durationProperties("duration", event.duration_ms), agents_spawned: boundedCount(event.agents_spawned, 1_000), error_count_bucket: telemetryErrorCountBucket(event.error_count), }; break; } case "session_recovered": properties = { ...common, reason: event.reason, total_count: boundedCount(event.total_count, 1_000), alive_count: boundedCount(event.alive_count, 1_000), terminal_count: boundedCount(event.terminal_count, 1_000), unknown_count: boundedCount(event.unknown_count, 1_000), }; break; case "completion_delivered": properties = { ...common, delivery: event.delivery, count: boundedCount(event.count, 128), ...durationProperties("delivery_latency", event.delivery_latency_ms), }; break; case "completion_delivery_failed": { const failureStage = sanitizeTelemetryCompletionFailureStage( event.failure_stage, ); properties = { ...common, delivery: "manifest", ...(failureStage === undefined ? {} : { failure_stage: failureStage }), retry_attempt: boundedCount(event.retry_attempt, 32), }; break; } case "runtime_failure": { const errorCategory = sanitizeTelemetryErrorCategory( event.error_category, ); const errorStage = sanitizeTelemetryErrorStage(event.error_stage); const failureKind = sanitizeTelemetryRuntimeFailureKind( event.failure_kind, ); const execution = sanitizeTelemetryRuntimeFailureExecution( event.execution, ); const mux = sanitizeTelemetryRuntimeFailureMux(event.mux); const reporter = sanitizeTelemetryRuntimeFailureReporter(event.reporter); const impact = sanitizeTelemetryRuntimeFailureImpact(event.impact); properties = { ...common, error_category: errorCategory, ...(errorStage === undefined ? {} : { error_stage: errorStage }), ...(failureKind === undefined ? {} : { failure_kind: failureKind }), ...(execution === undefined ? {} : { execution }), ...(mux === undefined ? {} : { mux }), ...(reporter === undefined ? {} : { reporter }), ...(impact === undefined ? {} : { impact }), }; break; } case "result_read": properties = { ...common, source: event.source, outcome: event.outcome, ...durationProperties("read_latency", event.read_latency_ms), }; break; default: return assertNever(event); } return { api_key: TELEMETRY_PROJECT_TOKEN, event: `pi_subagentura_${event.event}`, distinct_id: session.correlationId, properties, }; } export function captureTelemetry( session: TelemetrySession | undefined, event: TelemetryEvent, options: CaptureOptions = {}, ): void { if ( !session?.enabled || (!session.active && !options.allowInactive) || (session.trafficOrigin === "test" && options.fetchImpl === undefined) ) { return; } if (options.dedupeKey) { if (session.capturedKeys.has(options.dedupeKey)) return; // Retain recent retry protection without making a long session stop // reporting authoritative lifecycle events after the memory bound. if (session.capturedKeys.size >= MAX_TELEMETRY_DEDUPE_KEYS) { const oldest = session.capturedKeys.values().next().value; if (oldest !== undefined) session.capturedKeys.delete(oldest); } session.capturedKeys.add(options.dedupeKey); } const fetchImpl = options.fetchImpl ?? fetch; // An unref'd controller instead of AbortSignal.timeout: a pending capture must // never hold the event loop open for up to 1.5s while the process is exiting. const controller = new AbortController(); const timeout = setTimeout( () => controller.abort(), TELEMETRY_TIMEOUT_MS, ) as ReturnType & { unref?: () => void }; timeout.unref?.(); try { const request = fetchImpl(TELEMETRY_ENDPOINT, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(buildTelemetryPayload(session, event)), signal: controller.signal, }); // Promise.resolve tolerates a patched fetch that returns a non-thenable, and // the attach stays inside the guard so no rejection escapes to the caller. // Offline, blocked, and timed-out requests are intentionally not retried. // Telemetry never consumes the payload, so release the unused response body // before considering the capture settled. Missing bodies are harmless. void Promise.resolve(request) .then((response) => response?.body?.cancel()) .catch(() => {}) .finally(() => clearTimeout(timeout)); } catch { // Best-effort analytics must never affect extension behavior. clearTimeout(timeout); } } export type TelemetryTerminalProgram = | "agterm" | "ghostty" | "iterm2" | "apple_terminal" | "vscode" | "wezterm" | "kitty" | "unknown"; export type TelemetryParentMux = | "tmux" | "zellij" | "herdr" | "rex" | "herdr-core" | "wezterm" | "cmux" | "unknown";