Merge pull request #7728 from continuedev/nate/telemetry-updates

fix: OTLP reduced cardinality and other OTel improvements
This commit is contained in:
Nate Sesti 2025-09-14 20:20:31 -07:00 • committed by GitHub
commit 0040290328
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
19 changed files with 170 additions and 79 deletions

View file

@ -272,7 +272,7 @@ export default class DocsService {
id: doc.startUrl,
isReindexing: false,
title: doc.title,
debugInfo: `max depth: ${doc.maxDepth}`,
debugInfo: `max depth: ${doc.maxDepth ?? "unlimited"}`,
icon: doc.faviconUrl,
url: doc.startUrl,
};
@ -468,7 +468,7 @@ export default class DocsService {
embeddingsProviderId: provider.embeddingId,
isReindexing: forceReindex && indexExists,
title: siteIndexingConfig.title,
debugInfo: `max depth: ${siteIndexingConfig.maxDepth}`,
debugInfo: `max depth: ${siteIndexingConfig.maxDepth ?? "unlimited"}`,
icon: siteIndexingConfig.faviconUrl,
url: siteIndexingConfig.startUrl,
};

View file

@ -2,6 +2,7 @@ import chalk from "chalk";
import { getApiClient } from "../config.js";
import { safeStderr } from "../init.js";
import { gracefulExit } from "../util/exit.js";
import type {
AuthConfig,
@ -76,7 +77,7 @@ export async function handleCliOrgForEnvironmentAuth(
"The --org flag is only supported in headless mode (with -p/--print flag)\n",
),
);
process.exit(1);
await gracefulExit(1);
}
const apiClient = getApiClient(authConfig.accessToken);
@ -107,7 +108,7 @@ export async function handleCliOrgForAuthenticatedConfig(
"The --org flag is only supported in headless mode (with -p/--print flag)\n",
),
);
process.exit(1);
await gracefulExit(1);
}
const apiClient = getApiClient(authenticatedConfig.accessToken);

View file

@ -22,6 +22,7 @@ import { streamChatResponse } from "../stream/streamChatResponse.js";
import { posthogService } from "../telemetry/posthogService.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { startTUIChat } from "../ui/index.js";
import { gracefulExit } from "../util/exit.js";
import { formatAnthropicError, formatError } from "../util/formatError.js";
import { logger } from "../util/logger.js";
import {
@ -96,7 +97,7 @@ export async function initializeChatHistory(
return newSession.history;
} else {
logger.error(chalk.red(`Session with ID "${options.fork}" not found.`));
process.exit(1);
await gracefulExit(1);
}
}
@ -545,7 +546,7 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
context: "chat_command_fatal",
headless: options.headless,
});
process.exit(1);
await gracefulExit(1);
} finally {
// Stop active time tracking
telemetryService.stopActiveTime();

View file

@ -1,6 +1,7 @@
import chalk from "chalk";
import { login as workosLogin } from "../auth/workos.js";
import { gracefulExit } from "../util/exit.js";
export async function login() {
console.info(chalk.yellow("Logging in to Continue..."));
@ -10,6 +11,6 @@ export async function login() {
console.info(chalk.green("Successfully logged in!"));
} catch (error: any) {
console.error(chalk.red(`Login failed: ${error.message}`));
process.exit(1);
await gracefulExit(1);
}
}

View file

@ -2,6 +2,7 @@ import chalk from "chalk";
import { telemetryService } from "../telemetry/telemetryService.js";
import { startRemoteTUIChat } from "../ui/index.js";
import { gracefulExit } from "../util/exit.js";
import { logger } from "../util/logger.js";
export async function remoteTest(
@ -25,6 +26,6 @@ export async function remoteTest(
logger.error(
chalk.red(`Failed to connect to remote environment: ${error.message}`),
);
process.exit(1);
await gracefulExit(1);
}
}

View file

@ -4,6 +4,7 @@ import { getAccessToken, loadAuthConfig } from "../auth/workos.js";
import { env } from "../env.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { startRemoteTUIChat } from "../ui/index.js";
import { gracefulExit } from "../util/exit.js";
import { getRepoUrl } from "../util/git.js";
import { logger } from "../util/logger.js";
import { readStdinSync } from "../util/stdin.js";
@ -75,7 +76,7 @@ export async function remote(
console.error(
chalk.red("Not authenticated. Please run 'cn login' first."),
);
process.exit(1);
await gracefulExit(1);
}
const accessToken = getAccessToken(authConfig);
@ -157,6 +158,6 @@ export async function remote(
logger.error(
chalk.red(`Failed to create remote environment: ${error.message}`),
);
process.exit(1);
await gracefulExit(1);
}
}

View file

@ -25,6 +25,7 @@ describe("serve command", () => {
ensureOrganization: vi.fn(),
getOrganizationId: vi.fn(),
isAuthenticated: vi.fn(() => false),
isAuthenticatedConfig: vi.fn(() => false),
}));
vi.mock("../onboarding.js", () => ({

View file

@ -22,6 +22,7 @@ import {
import { createSession } from "../session.js";
import { constructSystemMessage } from "../systemMessage.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { gracefulExit } from "../util/exit.js";
import { formatError } from "../util/formatError.js";
import { logger } from "../util/logger.js";
import { readStdinSync } from "../util/stdin.js";
@ -302,12 +303,16 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
}
// Give a moment for the response to be sent
setTimeout(() => {
const handleExitResponse = () => {
server.close(() => {
telemetryService.stopActiveTime();
process.exit(0);
gracefulExit(0).catch((err) => {
logger.error(`Graceful exit failed: ${formatError(err)}`);
process.exit(1);
});
});
}, 100);
};
setTimeout(handleExitResponse, 100);
});
const server = app.listen(port, () => {
@ -435,7 +440,10 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
state.serverRunning = false;
server.close(() => {
telemetryService.stopActiveTime();
process.exit(0);
gracefulExit(0).catch((err) => {
logger.error(`Graceful exit failed: ${formatError(err)}`);
process.exit(1);
});
});
if (inactivityChecker) {
clearInterval(inactivityChecker);
@ -454,7 +462,10 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
}
server.close(() => {
telemetryService.stopActiveTime();
process.exit(0);
gracefulExit(0).catch((err) => {
logger.error(`Graceful exit failed: ${formatError(err)}`);
process.exit(1);
});
});
});
}

View file

@ -219,5 +219,7 @@ export function handleValidationErrors(errors: ValidationError[]): never {
safeStderr(`\nFound ${errors.length} validation errors.\n`);
}
process.exit(1);
// Use async graceful exit without awaiting (we must satisfy never)
import("../util/exit.js").then(({ gracefulExit }) => gracefulExit(1));
throw new Error("Exiting due to validation errors");
}

View file

@ -11,6 +11,7 @@ import {
isValidAnthropicApiKey,
getApiKeyValidationError,
} from "./util/apiKeyValidation.js";
import { gracefulExit } from "./util/exit.js";
import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js";
const CONFIG_PATH = path.join(env.continueHome, "config.yaml");
@ -81,7 +82,7 @@ export async function handleMaxedOutFreeTrial(
// Wait for user to acknowledge
readlineSync.question(chalk.dim("\nPress Enter to exit..."));
process.exit(0);
await gracefulExit(0);
} else if (choice === "2") {
// Option 2: Enter Anthropic API key
const apiKey = readlineSync.question(
@ -93,7 +94,7 @@ export async function handleMaxedOutFreeTrial(
if (!isValidAnthropicApiKey(apiKey)) {
console.log(chalk.red(`❌ ${getApiKeyValidationError(apiKey)}`));
process.exit(1);
await gracefulExit(1);
}
try {
@ -108,7 +109,7 @@ export async function handleMaxedOutFreeTrial(
}
} catch (error) {
console.log(chalk.red(`❌ Error saving API key: ${error}`));
process.exit(1);
await gracefulExit(1);
}
}
@ -137,5 +138,5 @@ export async function handleMaxedOutFreeTrial(
child.unref();
// Exit the current process
process.exit(0);
await gracefulExit(0);
}

View file

@ -19,6 +19,8 @@ import {
import { configureConsoleForHeadless, safeStderr } from "./init.js";
import { sentryService } from "./sentry.js";
import { addCommonOptions, mergeParentOptions } from "./shared-options.js";
import { posthogService } from "./telemetry/posthogService.js";
import { gracefulExit } from "./util/exit.js";
import { logger } from "./util/logger.js";
import { readStdinSync } from "./util/stdin.js";
import { getVersion } from "./version.js";
@ -62,8 +64,7 @@ export function enableSigintHandler() {
if (tuiUnmount) {
tuiUnmount();
}
await sentryService.flush();
process.exit(0);
await gracefulExit(0);
} else {
// First Ctrl+C or too much time elapsed - show exit message
lastCtrlCTime = now;
@ -131,6 +132,8 @@ addCommonOptions(program)
.option("--resume", "Resume from last session")
.option("--fork <sessionId>", "Fork from an existing session ID")
.action(async (prompt, options) => {
// Telemetry: record command invocation
await posthogService.capture("cliCommand", { command: "cn" });
// Handle piped input - detect it early and decide on mode
let stdinInput = null;
@ -217,7 +220,7 @@ addCommonOptions(program)
safeStderr(' cn -p "please review my current git diff"\n');
safeStderr(' echo "hello" | cn -p\n');
safeStderr(' cn -p "analyze the code in src/"\n');
process.exit(1);
await gracefulExit(1);
}
// Map --print to headless mode
@ -231,6 +234,8 @@ program
.command("login")
.description("Authenticate with Continue")
.action(async () => {
// Telemetry: record command invocation
await posthogService.capture("cliCommand", { command: "login" });
await login();
});
@ -239,6 +244,8 @@ program
.command("logout")
.description("Log out from Continue")
.action(async () => {
// Telemetry: record command invocation
await posthogService.capture("cliCommand", { command: "logout" });
await logout();
});
@ -248,6 +255,8 @@ program
.description("List recent chat sessions and select one to resume")
.option("--json", "Output in JSON format")
.action(async (options) => {
// Telemetry: record command invocation
await posthogService.capture("cliCommand", { command: "ls" });
await listSessionsCommand({
format: options.json ? "json" : undefined,
});
@ -280,6 +289,11 @@ addCommonOptions(
"Specify the repository URL to use in the remote environment",
)
.action(async (prompt: string | undefined, options) => {
// Telemetry: record command invocation
await posthogService.capture("cliCommand", {
command: "remote",
flagS: options.start,
});
await remote(prompt, options);
});
@ -294,6 +308,8 @@ program
)
.option("--port <port>", "Port to run the server on (default: 8000)", "8000")
.action(async (prompt, options) => {
// Telemetry: record command invocation
await posthogService.capture("cliCommand", { command: "serve" });
// Merge parent options with subcommand options
const mergedOptions = mergeParentOptions(program, options);
@ -311,6 +327,8 @@ program
.description("Test remote TUI mode with a local server")
.option("--url <url>", "Server URL (default: http://localhost:8000)")
.action(async (prompt: string | undefined, options) => {
// Telemetry: record command invocation
await posthogService.capture("cliCommand", { command: "remote-test" });
await remoteTest(prompt, options.url);
});
@ -318,7 +336,7 @@ program
program.on("command:*", () => {
console.error(`Error: Unknown command '${program.args.join(" ")}'\n`);
program.outputHelp();
process.exit(1);
void gracefulExit(1);
});
// Parse arguments and handle errors
@ -329,10 +347,9 @@ try {
sentryService.captureException(
error instanceof Error ? error : new Error(String(error)),
);
process.exit(1);
void gracefulExit(1);
}
process.on("SIGTERM", async () => {
await sentryService.flush();
process.exit(0);
await gracefulExit(0);
});

View file

@ -6,6 +6,7 @@ import { checkToolPermission } from "../permissions/permissionChecker.js";
import { toolPermissionManager } from "../permissions/permissionManager.js";
import { ToolCallRequest } from "../permissions/types.js";
import { services } from "../services/index.js";
import { posthogService } from "../telemetry/posthogService.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { calculateTokenCost } from "../telemetry/utils.js";
import {
@ -64,7 +65,11 @@ export function handleHeadlessPermission(
`If you don't want the tool to be included, use --exclude ${toolName}.`,
);
process.exit(1);
// Use graceful exit to flush telemetry even in headless denial
// Note: We purposely trigger an async exit without awaiting in this sync path
import("../util/exit.js").then(({ gracefulExit }) => gracefulExit(1));
// Throw to satisfy the never return type; process will exit shortly
throw new Error("Exiting due to headless permission requirement");
}
// Helper function to request user permission
@ -286,6 +291,17 @@ export function recordStreamTelemetry(options: {
costUsd: cost,
});
// Mirror core metrics to PostHog for product analytics
try {
posthogService.capture("apiRequest", {
model: model.model,
durationMs: totalDuration,
inputTokens,
outputTokens,
costUsd: cost,
});
} catch {}
return cost;
}

View file

@ -11,6 +11,7 @@ import type {
import { getServiceSync, SERVICE_NAMES, services } from "../services/index.js";
import { systemMessageService } from "../services/SystemMessageService.js";
import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js";
import { posthogService } from "../telemetry/posthogService.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { ToolCall } from "../tools/index.js";
import {
@ -258,6 +259,15 @@ export async function processStreamingResponse(
error: error.message || String(error),
});
try {
posthogService.capture("apiRequest", {
model: model.model,
durationMs: errorDuration,
success: false,
error: error.message || String(error),
});
} catch {}
if (error.name === "AbortError" || abortController?.signal.aborted) {
logger.debug("Stream aborted by user");
return {

View file

@ -0,0 +1,26 @@
export function parseOtelHeaders(headersStr: string): Record<string, string> {
const headers: Record<string, string> = {};
if (!headersStr) return headers;
headersStr.split(",").forEach((header) => {
const [key, value] = header.split("=");
if (key && value) {
headers[key.trim()] = value.trim();
}
});
return headers;
}
export function detectTerminalType(): string | undefined {
if (process.env.TERM_PROGRAM) {
return process.env.TERM_PROGRAM;
}
if (process.env.VSCODE_PID) {
return "vscode";
}
if (process.env.TMUX) {
return "tmux";
}
return undefined;
}

View file

@ -12,8 +12,6 @@ import {
SEMRESATTRS_DEPLOYMENT_ENVIRONMENT,
SEMRESATTRS_HOST_NAME,
SEMRESATTRS_OS_TYPE,
SEMRESATTRS_PROCESS_PID,
SEMRESATTRS_SERVICE_INSTANCE_ID,
SEMRESATTRS_SERVICE_NAME,
SEMRESATTRS_SERVICE_VERSION,
} from "@opentelemetry/semantic-conventions";
@ -24,12 +22,13 @@ import { isContinueRemoteAgent, isGitHubActions } from "../util/git.js";
import { logger } from "../util/logger.js";
import { getVersion } from "../version.js";
import { detectTerminalType, parseOtelHeaders } from "./headerUtils.js";
export interface TelemetryConfig {
enabled: boolean;
sessionId: string;
organizationId?: string;
accountUuid?: string;
includeSessionId: boolean;
includeVersion: boolean;
includeAccountUuid: boolean;
}
@ -80,7 +79,6 @@ class TelemetryService {
sessionId,
organizationId: process.env.ORGANIZATION_ID,
accountUuid: process.env.ACCOUNT_UUID,
includeSessionId: process.env.OTEL_METRICS_INCLUDE_SESSION_ID !== "false",
includeVersion: process.env.OTEL_METRICS_INCLUDE_VERSION === "true",
includeAccountUuid:
process.env.OTEL_METRICS_INCLUDE_ACCOUNT_UUID !== "false",
@ -93,12 +91,10 @@ class TelemetryService {
const resource = resourceFromAttributes({
[SEMRESATTRS_SERVICE_NAME]: "continue-cli",
[SEMRESATTRS_SERVICE_VERSION]: getVersion(),
[SEMRESATTRS_SERVICE_INSTANCE_ID]: uuidv4(),
[SEMRESATTRS_HOST_NAME]: os.hostname(),
[SEMRESATTRS_DEPLOYMENT_ENVIRONMENT]:
process.env.NODE_ENV || "development",
[SEMRESATTRS_OS_TYPE]: os.type(),
[SEMRESATTRS_PROCESS_PID]: process.pid.toString(),
});
// Configure exporters
@ -113,11 +109,20 @@ class TelemetryService {
readers.push(
new PeriodicExportingMetricReader({
exporter: new OTLPMetricExporter({
url:
process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT ||
`${process.env.OTEL_EXPORTER_OTLP_ENDPOINT}/v1/metrics` ||
"http://localhost:4318/v1/metrics",
headers: this.parseHeaders(
url: (() => {
const metricsEndpoint =
process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT;
if (metricsEndpoint && metricsEndpoint.trim().length > 0) {
return metricsEndpoint;
}
const base = process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
if (base && base.trim().length > 0) {
const normalized = base.replace(/\/$/, "");
return `${normalized}/v1/metrics`;
}
return "http://localhost:4318/v1/metrics";
})(),
headers: parseOtelHeaders(
process.env.OTEL_EXPORTER_OTLP_HEADERS || "",
),
}),
@ -183,20 +188,6 @@ class TelemetryService {
this.shutdownHandlersRegistered = true;
}
private parseHeaders(headersStr: string): Record<string, string> {
const headers: Record<string, string> = {};
if (!headersStr) return headers;
headersStr.split(",").forEach((header) => {
const [key, value] = header.split("=");
if (key && value) {
headers[key.trim()] = value.trim();
}
});
return headers;
}
private initializeMetrics() {
if (!this.meter) return;
@ -308,10 +299,6 @@ class TelemetryService {
) {
const attributes: Record<string, string> = { ...additionalAttributes };
if (this.config.includeSessionId) {
attributes["session.id"] = this.config.sessionId;
}
if (this.config.includeVersion) {
attributes["app.version"] = getVersion();
}
@ -325,7 +312,7 @@ class TelemetryService {
}
// Detect terminal type
const terminalType = this.detectTerminalType();
const terminalType = detectTerminalType();
if (terminalType) {
attributes["terminal.type"] = terminalType;
}
@ -333,19 +320,6 @@ class TelemetryService {
return attributes;
}
private detectTerminalType(): string | undefined {
if (process.env.TERM_PROGRAM) {
return process.env.TERM_PROGRAM;
}
if (process.env.VSCODE_PID) {
return "vscode";
}
if (process.env.TMUX) {
return "tmux";
}
return undefined;
}
// Public methods for tracking metrics
public recordSessionStart() {
@ -435,13 +409,12 @@ class TelemetryService {
if (!this.isEnabled()) return;
if (this.activeStartTime !== null) {
this.totalActiveTime += Date.now() - this.activeStartTime;
const deltaMs = Date.now() - this.activeStartTime;
this.totalActiveTime += deltaMs;
this.activeStartTime = null;
this.activeTimeCounter.add(
this.totalActiveTime / 1000,
this.getStandardAttributes(),
);
// Record only the delta for this active window (in seconds)
this.activeTimeCounter.add(deltaMs / 1000, this.getStandardAttributes());
}
}

View file

@ -9,6 +9,8 @@ export const exitTool: Tool = {
readonly: false,
isBuiltIn: true,
run: async (): Promise<string> => {
process.exit(1);
const { gracefulExit } = await import("../util/exit.js");
await gracefulExit(1);
return "";
},
};

View file

@ -67,7 +67,7 @@ export function processSlashCommandResult({
onClear,
}: ProcessSlashCommandResultOptions): string | null {
if (result.exit) {
process.exit(0);
import("../../util/exit.js").then(({ gracefulExit }) => gracefulExit(0));
}
if (result.openMcpSelector) {

View file

@ -76,7 +76,7 @@ export function handleControlKeys(options: ControlKeysOptions): boolean {
// Handle Ctrl+D to exit
if (key.ctrl && input === "d") {
exit();
process.exit(0);
import("../../util/exit.js").then(({ gracefulExit }) => gracefulExit(0));
}
// Handle Ctrl+L to refresh screen (clear terminal artifacts)

View file

@ -0,0 +1,27 @@
import { sentryService } from "../sentry.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { logger } from "./logger.js";
/**
* Exit the process after flushing telemetry and error reporting.
* Use this instead of process.exit() to avoid losing metrics/logs.
*/
export async function gracefulExit(code: number = 0): Promise<void> {
try {
// Flush metrics (forceFlush + shutdown inside service)
await telemetryService.shutdown();
} catch (err) {
logger.debug("Telemetry shutdown error (ignored)", err as any);
}
try {
// Flush Sentry (best effort)
await sentryService.flush();
} catch (err) {
logger.debug("Sentry flush error (ignored)", err as any);
}
// Exit the process
process.exit(code);
}