diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 8a4e60a49..4a0648420 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -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, }; diff --git a/extensions/cli/src/auth/workos.helpers.ts b/extensions/cli/src/auth/workos.helpers.ts index efd2151cc..8e33b5127 100644 --- a/extensions/cli/src/auth/workos.helpers.ts +++ b/extensions/cli/src/auth/workos.helpers.ts @@ -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); diff --git a/extensions/cli/src/commands/chat.ts b/extensions/cli/src/commands/chat.ts index 96e74c9ae..61dd79c9c 100644 --- a/extensions/cli/src/commands/chat.ts +++ b/extensions/cli/src/commands/chat.ts @@ -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(); diff --git a/extensions/cli/src/commands/login.ts b/extensions/cli/src/commands/login.ts index 5786904ae..a1c6cc4f8 100644 --- a/extensions/cli/src/commands/login.ts +++ b/extensions/cli/src/commands/login.ts @@ -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); } } diff --git a/extensions/cli/src/commands/remote-test.ts b/extensions/cli/src/commands/remote-test.ts index e3404c86f..dc5e016e3 100644 --- a/extensions/cli/src/commands/remote-test.ts +++ b/extensions/cli/src/commands/remote-test.ts @@ -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); } } diff --git a/extensions/cli/src/commands/remote.ts b/extensions/cli/src/commands/remote.ts index 591c4461f..f81a2d060 100644 --- a/extensions/cli/src/commands/remote.ts +++ b/extensions/cli/src/commands/remote.ts @@ -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); } } diff --git a/extensions/cli/src/commands/serve.test.ts b/extensions/cli/src/commands/serve.test.ts index 2bc8428bd..87487dc32 100644 --- a/extensions/cli/src/commands/serve.test.ts +++ b/extensions/cli/src/commands/serve.test.ts @@ -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", () => ({ diff --git a/extensions/cli/src/commands/serve.ts b/extensions/cli/src/commands/serve.ts index 5be1eda05..bc3809e04 100644 --- a/extensions/cli/src/commands/serve.ts +++ b/extensions/cli/src/commands/serve.ts @@ -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); + }); }); }); } diff --git a/extensions/cli/src/flags/flagValidator.ts b/extensions/cli/src/flags/flagValidator.ts index fb9b29195..2c5790b5a 100644 --- a/extensions/cli/src/flags/flagValidator.ts +++ b/extensions/cli/src/flags/flagValidator.ts @@ -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"); } diff --git a/extensions/cli/src/freeTrialTransition.ts b/extensions/cli/src/freeTrialTransition.ts index 2a2514c89..5f6217345 100644 --- a/extensions/cli/src/freeTrialTransition.ts +++ b/extensions/cli/src/freeTrialTransition.ts @@ -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); } diff --git a/extensions/cli/src/index.ts b/extensions/cli/src/index.ts index 2ca524d8f..ab0c670bd 100644 --- a/extensions/cli/src/index.ts +++ b/extensions/cli/src/index.ts @@ -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 ", "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 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 ", "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); }); diff --git a/extensions/cli/src/stream/streamChatResponse.helpers.ts b/extensions/cli/src/stream/streamChatResponse.helpers.ts index 06e0a68c0..b82f63212 100644 --- a/extensions/cli/src/stream/streamChatResponse.helpers.ts +++ b/extensions/cli/src/stream/streamChatResponse.helpers.ts @@ -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; } diff --git a/extensions/cli/src/stream/streamChatResponse.ts b/extensions/cli/src/stream/streamChatResponse.ts index 95316e975..4c1c45cc5 100644 --- a/extensions/cli/src/stream/streamChatResponse.ts +++ b/extensions/cli/src/stream/streamChatResponse.ts @@ -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 { diff --git a/extensions/cli/src/telemetry/headerUtils.ts b/extensions/cli/src/telemetry/headerUtils.ts new file mode 100644 index 000000000..ae09d953b --- /dev/null +++ b/extensions/cli/src/telemetry/headerUtils.ts @@ -0,0 +1,26 @@ +export function parseOtelHeaders(headersStr: string): Record { + const headers: Record = {}; + 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; +} diff --git a/extensions/cli/src/telemetry/telemetryService.ts b/extensions/cli/src/telemetry/telemetryService.ts index bcd6f3cfe..263f21ac7 100644 --- a/extensions/cli/src/telemetry/telemetryService.ts +++ b/extensions/cli/src/telemetry/telemetryService.ts @@ -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 { - const headers: Record = {}; - 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 = { ...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()); } } diff --git a/extensions/cli/src/tools/exit.ts b/extensions/cli/src/tools/exit.ts index ebed5ecde..4c569ccca 100644 --- a/extensions/cli/src/tools/exit.ts +++ b/extensions/cli/src/tools/exit.ts @@ -9,6 +9,8 @@ export const exitTool: Tool = { readonly: false, isBuiltIn: true, run: async (): Promise => { - process.exit(1); + const { gracefulExit } = await import("../util/exit.js"); + await gracefulExit(1); + return ""; }, }; diff --git a/extensions/cli/src/ui/hooks/useChat.helpers.ts b/extensions/cli/src/ui/hooks/useChat.helpers.ts index 1c289e5c7..58be45d60 100644 --- a/extensions/cli/src/ui/hooks/useChat.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.helpers.ts @@ -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) { diff --git a/extensions/cli/src/ui/hooks/useUserInput.ts b/extensions/cli/src/ui/hooks/useUserInput.ts index c5945bbf3..334d23fc3 100644 --- a/extensions/cli/src/ui/hooks/useUserInput.ts +++ b/extensions/cli/src/ui/hooks/useUserInput.ts @@ -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) diff --git a/extensions/cli/src/util/exit.ts b/extensions/cli/src/util/exit.ts new file mode 100644 index 000000000..31ec02652 --- /dev/null +++ b/extensions/cli/src/util/exit.ts @@ -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 { + 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); +}