Elffuss BraidHub

kikocis/continue public

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

fix: OTLP reduced cardinality and other OTel improvements
Changeseta660fc8009f5d161343a1bde164cd9fa1db11445db7d617a72f94aa018b9caad
AuthorNate Sesti <33237525+sestinj@users.noreply.github.com> · 2025-09-14 20:20 -07:00
CommitterGitHub <noreply@github.com> · 2025-09-14 20:20 -07:00
Parentsc75ade3f86e5, bc35c780e873

Browse the files at this changeset

19 files changed

modified core/indexing/docs/DocsService.ts +2 −2
@@ -272,7 +272,7 @@
272272 id: doc.startUrl,
273273 isReindexing: false,
274274 title: doc.title,
275- debugInfo: `max depth: ${doc.maxDepth}`,
275+ debugInfo: `max depth: ${doc.maxDepth ?? "unlimited"}`,
276276 icon: doc.faviconUrl,
277277 url: doc.startUrl,
278278 };
@@ -468,7 +468,7 @@
468468 embeddingsProviderId: provider.embeddingId,
469469 isReindexing: forceReindex && indexExists,
470470 title: siteIndexingConfig.title,
471- debugInfo: `max depth: ${siteIndexingConfig.maxDepth}`,
471+ debugInfo: `max depth: ${siteIndexingConfig.maxDepth ?? "unlimited"}`,
472472 icon: siteIndexingConfig.faviconUrl,
473473 url: siteIndexingConfig.startUrl,
474474 };
modified extensions/cli/src/auth/workos.helpers.ts +3 −2
@@ -2,6 +2,7 @@
22
33 import { getApiClient } from "../config.js";
44 import { safeStderr } from "../init.js";
5+import { gracefulExit } from "../util/exit.js";
56
67 import type {
78 AuthConfig,
@@ -76,7 +77,7 @@
7677 "The --org flag is only supported in headless mode (with -p/--print flag)\n",
7778 ),
7879 );
79- process.exit(1);
80+ await gracefulExit(1);
8081 }
8182
8283 const apiClient = getApiClient(authConfig.accessToken);
@@ -107,7 +108,7 @@
107108 "The --org flag is only supported in headless mode (with -p/--print flag)\n",
108109 ),
109110 );
110- process.exit(1);
111+ await gracefulExit(1);
111112 }
112113
113114 const apiClient = getApiClient(authenticatedConfig.accessToken);
modified extensions/cli/src/commands/chat.ts +3 −2
@@ -22,6 +22,7 @@
2222 import { posthogService } from "../telemetry/posthogService.js";
2323 import { telemetryService } from "../telemetry/telemetryService.js";
2424 import { startTUIChat } from "../ui/index.js";
25+import { gracefulExit } from "../util/exit.js";
2526 import { formatAnthropicError, formatError } from "../util/formatError.js";
2627 import { logger } from "../util/logger.js";
2728 import {
@@ -96,7 +97,7 @@
9697 return newSession.history;
9798 } else {
9899 logger.error(chalk.red(`Session with ID "${options.fork}" not found.`));
99- process.exit(1);
100+ await gracefulExit(1);
100101 }
101102 }
102103
@@ -545,7 +546,7 @@
545546 context: "chat_command_fatal",
546547 headless: options.headless,
547548 });
548- process.exit(1);
549+ await gracefulExit(1);
549550 } finally {
550551 // Stop active time tracking
551552 telemetryService.stopActiveTime();
modified extensions/cli/src/commands/login.ts +2 −1
@@ -1,6 +1,7 @@
11 import chalk from "chalk";
22
33 import { login as workosLogin } from "../auth/workos.js";
4+import { gracefulExit } from "../util/exit.js";
45
56 export async function login() {
67 console.info(chalk.yellow("Logging in to Continue..."));
@@ -10,6 +11,6 @@
1011 console.info(chalk.green("Successfully logged in!"));
1112 } catch (error: any) {
1213 console.error(chalk.red(`Login failed: ${error.message}`));
13- process.exit(1);
14+ await gracefulExit(1);
1415 }
1516 }
modified extensions/cli/src/commands/remote-test.ts +2 −1
@@ -2,6 +2,7 @@
22
33 import { telemetryService } from "../telemetry/telemetryService.js";
44 import { startRemoteTUIChat } from "../ui/index.js";
5+import { gracefulExit } from "../util/exit.js";
56 import { logger } from "../util/logger.js";
67
78 export async function remoteTest(
@@ -25,6 +26,6 @@
2526 logger.error(
2627 chalk.red(`Failed to connect to remote environment: ${error.message}`),
2728 );
28- process.exit(1);
29+ await gracefulExit(1);
2930 }
3031 }
modified extensions/cli/src/commands/remote.ts +3 −2
@@ -4,6 +4,7 @@
44 import { env } from "../env.js";
55 import { telemetryService } from "../telemetry/telemetryService.js";
66 import { startRemoteTUIChat } from "../ui/index.js";
7+import { gracefulExit } from "../util/exit.js";
78 import { getRepoUrl } from "../util/git.js";
89 import { logger } from "../util/logger.js";
910 import { readStdinSync } from "../util/stdin.js";
@@ -75,7 +76,7 @@
7576 console.error(
7677 chalk.red("Not authenticated. Please run 'cn login' first."),
7778 );
78- process.exit(1);
79+ await gracefulExit(1);
7980 }
8081
8182 const accessToken = getAccessToken(authConfig);
@@ -157,6 +158,6 @@
157158 logger.error(
158159 chalk.red(`Failed to create remote environment: ${error.message}`),
159160 );
160- process.exit(1);
161+ await gracefulExit(1);
161162 }
162163 }
modified extensions/cli/src/commands/serve.test.ts +1 −0
@@ -25,6 +25,7 @@
2525 ensureOrganization: vi.fn(),
2626 getOrganizationId: vi.fn(),
2727 isAuthenticated: vi.fn(() => false),
28+ isAuthenticatedConfig: vi.fn(() => false),
2829 }));
2930
3031 vi.mock("../onboarding.js", () => ({
modified extensions/cli/src/commands/serve.ts +16 −5
@@ -22,6 +22,7 @@
2222 import { createSession } from "../session.js";
2323 import { constructSystemMessage } from "../systemMessage.js";
2424 import { telemetryService } from "../telemetry/telemetryService.js";
25+import { gracefulExit } from "../util/exit.js";
2526 import { formatError } from "../util/formatError.js";
2627 import { logger } from "../util/logger.js";
2728 import { readStdinSync } from "../util/stdin.js";
@@ -302,12 +303,16 @@
302303 }
303304
304305 // Give a moment for the response to be sent
305- setTimeout(() => {
306+ const handleExitResponse = () => {
306307 server.close(() => {
307308 telemetryService.stopActiveTime();
308- process.exit(0);
309+ gracefulExit(0).catch((err) => {
310+ logger.error(`Graceful exit failed: ${formatError(err)}`);
311+ process.exit(1);
312+ });
309313 });
310- }, 100);
314+ };
315+ setTimeout(handleExitResponse, 100);
311316 });
312317
313318 const server = app.listen(port, () => {
@@ -435,7 +440,10 @@
435440 state.serverRunning = false;
436441 server.close(() => {
437442 telemetryService.stopActiveTime();
438- process.exit(0);
443+ gracefulExit(0).catch((err) => {
444+ logger.error(`Graceful exit failed: ${formatError(err)}`);
445+ process.exit(1);
446+ });
439447 });
440448 if (inactivityChecker) {
441449 clearInterval(inactivityChecker);
@@ -454,7 +462,10 @@
454462 }
455463 server.close(() => {
456464 telemetryService.stopActiveTime();
457- process.exit(0);
465+ gracefulExit(0).catch((err) => {
466+ logger.error(`Graceful exit failed: ${formatError(err)}`);
467+ process.exit(1);
468+ });
458469 });
459470 });
460471 }
modified extensions/cli/src/flags/flagValidator.ts +3 −1
@@ -219,5 +219,7 @@
219219 safeStderr(`\nFound ${errors.length} validation errors.\n`);
220220 }
221221
222- process.exit(1);
222+ // Use async graceful exit without awaiting (we must satisfy never)
223+ import("../util/exit.js").then(({ gracefulExit }) => gracefulExit(1));
224+ throw new Error("Exiting due to validation errors");
223225 }
modified extensions/cli/src/freeTrialTransition.ts +5 −4
@@ -11,6 +11,7 @@
1111 isValidAnthropicApiKey,
1212 getApiKeyValidationError,
1313 } from "./util/apiKeyValidation.js";
14+import { gracefulExit } from "./util/exit.js";
1415 import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js";
1516
1617 const CONFIG_PATH = path.join(env.continueHome, "config.yaml");
@@ -81,7 +82,7 @@
8182
8283 // Wait for user to acknowledge
8384 readlineSync.question(chalk.dim("\nPress Enter to exit..."));
84- process.exit(0);
85+ await gracefulExit(0);
8586 } else if (choice === "2") {
8687 // Option 2: Enter Anthropic API key
8788 const apiKey = readlineSync.question(
@@ -93,7 +94,7 @@
9394
9495 if (!isValidAnthropicApiKey(apiKey)) {
9596 console.log(chalk.red(`❌ ${getApiKeyValidationError(apiKey)}`));
96- process.exit(1);
97+ await gracefulExit(1);
9798 }
9899
99100 try {
@@ -108,7 +109,7 @@
108109 }
109110 } catch (error) {
110111 console.log(chalk.red(`❌ Error saving API key: ${error}`));
111- process.exit(1);
112+ await gracefulExit(1);
112113 }
113114 }
114115
@@ -137,5 +138,5 @@
137138 child.unref();
138139
139140 // Exit the current process
140- process.exit(0);
141+ await gracefulExit(0);
141142 }
modified extensions/cli/src/index.ts +24 −7
@@ -19,6 +19,8 @@
1919 import { configureConsoleForHeadless, safeStderr } from "./init.js";
2020 import { sentryService } from "./sentry.js";
2121 import { addCommonOptions, mergeParentOptions } from "./shared-options.js";
22+import { posthogService } from "./telemetry/posthogService.js";
23+import { gracefulExit } from "./util/exit.js";
2224 import { logger } from "./util/logger.js";
2325 import { readStdinSync } from "./util/stdin.js";
2426 import { getVersion } from "./version.js";
@@ -62,8 +64,7 @@
6264 if (tuiUnmount) {
6365 tuiUnmount();
6466 }
65- await sentryService.flush();
66- process.exit(0);
67+ await gracefulExit(0);
6768 } else {
6869 // First Ctrl+C or too much time elapsed - show exit message
6970 lastCtrlCTime = now;
@@ -131,6 +132,8 @@
131132 .option("--resume", "Resume from last session")
132133 .option("--fork <sessionId>", "Fork from an existing session ID")
133134 .action(async (prompt, options) => {
135+ // Telemetry: record command invocation
136+ await posthogService.capture("cliCommand", { command: "cn" });
134137 // Handle piped input - detect it early and decide on mode
135138 let stdinInput = null;
136139
@@ -217,7 +220,7 @@
217220 safeStderr(' cn -p "please review my current git diff"\n');
218221 safeStderr(' echo "hello" | cn -p\n');
219222 safeStderr(' cn -p "analyze the code in src/"\n');
220- process.exit(1);
223+ await gracefulExit(1);
221224 }
222225
223226 // Map --print to headless mode
@@ -231,6 +234,8 @@
231234 .command("login")
232235 .description("Authenticate with Continue")
233236 .action(async () => {
237+ // Telemetry: record command invocation
238+ await posthogService.capture("cliCommand", { command: "login" });
234239 await login();
235240 });
236241
@@ -239,6 +244,8 @@
239244 .command("logout")
240245 .description("Log out from Continue")
241246 .action(async () => {
247+ // Telemetry: record command invocation
248+ await posthogService.capture("cliCommand", { command: "logout" });
242249 await logout();
243250 });
244251
@@ -248,6 +255,8 @@
248255 .description("List recent chat sessions and select one to resume")
249256 .option("--json", "Output in JSON format")
250257 .action(async (options) => {
258+ // Telemetry: record command invocation
259+ await posthogService.capture("cliCommand", { command: "ls" });
251260 await listSessionsCommand({
252261 format: options.json ? "json" : undefined,
253262 });
@@ -280,6 +289,11 @@
280289 "Specify the repository URL to use in the remote environment",
281290 )
282291 .action(async (prompt: string | undefined, options) => {
292+ // Telemetry: record command invocation
293+ await posthogService.capture("cliCommand", {
294+ command: "remote",
295+ flagS: options.start,
296+ });
283297 await remote(prompt, options);
284298 });
285299
@@ -294,6 +308,8 @@
294308 )
295309 .option("--port <port>", "Port to run the server on (default: 8000)", "8000")
296310 .action(async (prompt, options) => {
311+ // Telemetry: record command invocation
312+ await posthogService.capture("cliCommand", { command: "serve" });
297313 // Merge parent options with subcommand options
298314 const mergedOptions = mergeParentOptions(program, options);
299315
@@ -311,6 +327,8 @@
311327 .description("Test remote TUI mode with a local server")
312328 .option("--url <url>", "Server URL (default: http://localhost:8000)")
313329 .action(async (prompt: string | undefined, options) => {
330+ // Telemetry: record command invocation
331+ await posthogService.capture("cliCommand", { command: "remote-test" });
314332 await remoteTest(prompt, options.url);
315333 });
316334
@@ -318,7 +336,7 @@
318336 program.on("command:*", () => {
319337 console.error(`Error: Unknown command '${program.args.join(" ")}'\n`);
320338 program.outputHelp();
321- process.exit(1);
339+ void gracefulExit(1);
322340 });
323341
324342 // Parse arguments and handle errors
@@ -329,10 +347,9 @@
329347 sentryService.captureException(
330348 error instanceof Error ? error : new Error(String(error)),
331349 );
332- process.exit(1);
350+ void gracefulExit(1);
333351 }
334352
335353 process.on("SIGTERM", async () => {
336- await sentryService.flush();
337- process.exit(0);
354+ await gracefulExit(0);
338355 });
modified extensions/cli/src/stream/streamChatResponse.helpers.ts +17 −1
@@ -6,6 +6,7 @@
66 import { toolPermissionManager } from "../permissions/permissionManager.js";
77 import { ToolCallRequest } from "../permissions/types.js";
88 import { services } from "../services/index.js";
9+import { posthogService } from "../telemetry/posthogService.js";
910 import { telemetryService } from "../telemetry/telemetryService.js";
1011 import { calculateTokenCost } from "../telemetry/utils.js";
1112 import {
@@ -64,7 +65,11 @@
6465 `If you don't want the tool to be included, use --exclude ${toolName}.`,
6566 );
6667
67- process.exit(1);
68+ // Use graceful exit to flush telemetry even in headless denial
69+ // Note: We purposely trigger an async exit without awaiting in this sync path
70+ import("../util/exit.js").then(({ gracefulExit }) => gracefulExit(1));
71+ // Throw to satisfy the never return type; process will exit shortly
72+ throw new Error("Exiting due to headless permission requirement");
6873 }
6974
7075 // Helper function to request user permission
@@ -286,6 +291,17 @@
286291 costUsd: cost,
287292 });
288293
294+ // Mirror core metrics to PostHog for product analytics
295+ try {
296+ posthogService.capture("apiRequest", {
297+ model: model.model,
298+ durationMs: totalDuration,
299+ inputTokens,
300+ outputTokens,
301+ costUsd: cost,
302+ });
303+ } catch {}
304+
289305 return cost;
290306 }
291307
modified extensions/cli/src/stream/streamChatResponse.ts +10 −0
@@ -11,6 +11,7 @@
1111 import { getServiceSync, SERVICE_NAMES, services } from "../services/index.js";
1212 import { systemMessageService } from "../services/SystemMessageService.js";
1313 import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js";
14+import { posthogService } from "../telemetry/posthogService.js";
1415 import { telemetryService } from "../telemetry/telemetryService.js";
1516 import { ToolCall } from "../tools/index.js";
1617 import {
@@ -258,6 +259,15 @@
258259 error: error.message || String(error),
259260 });
260261
262+ try {
263+ posthogService.capture("apiRequest", {
264+ model: model.model,
265+ durationMs: errorDuration,
266+ success: false,
267+ error: error.message || String(error),
268+ });
269+ } catch {}
270+
261271 if (error.name === "AbortError" || abortController?.signal.aborted) {
262272 logger.debug("Stream aborted by user");
263273 return {
added extensions/cli/src/telemetry/headerUtils.ts +26 −0
@@ -0,0 +1,26 @@
1+export function parseOtelHeaders(headersStr: string): Record<string, string> {
2+ const headers: Record<string, string> = {};
3+ if (!headersStr) return headers;
4+
5+ headersStr.split(",").forEach((header) => {
6+ const [key, value] = header.split("=");
7+ if (key && value) {
8+ headers[key.trim()] = value.trim();
9+ }
10+ });
11+
12+ return headers;
13+}
14+
15+export function detectTerminalType(): string | undefined {
16+ if (process.env.TERM_PROGRAM) {
17+ return process.env.TERM_PROGRAM;
18+ }
19+ if (process.env.VSCODE_PID) {
20+ return "vscode";
21+ }
22+ if (process.env.TMUX) {
23+ return "tmux";
24+ }
25+ return undefined;
26+}
modified extensions/cli/src/telemetry/telemetryService.ts +21 −48
@@ -12,8 +12,6 @@
1212 SEMRESATTRS_DEPLOYMENT_ENVIRONMENT,
1313 SEMRESATTRS_HOST_NAME,
1414 SEMRESATTRS_OS_TYPE,
15- SEMRESATTRS_PROCESS_PID,
16- SEMRESATTRS_SERVICE_INSTANCE_ID,
1715 SEMRESATTRS_SERVICE_NAME,
1816 SEMRESATTRS_SERVICE_VERSION,
1917 } from "@opentelemetry/semantic-conventions";
@@ -24,12 +22,13 @@
2422 import { logger } from "../util/logger.js";
2523 import { getVersion } from "../version.js";
2624
25+import { detectTerminalType, parseOtelHeaders } from "./headerUtils.js";
26+
2727 export interface TelemetryConfig {
2828 enabled: boolean;
2929 sessionId: string;
3030 organizationId?: string;
3131 accountUuid?: string;
32- includeSessionId: boolean;
3332 includeVersion: boolean;
3433 includeAccountUuid: boolean;
3534 }
@@ -80,7 +79,6 @@
8079 sessionId,
8180 organizationId: process.env.ORGANIZATION_ID,
8281 accountUuid: process.env.ACCOUNT_UUID,
83- includeSessionId: process.env.OTEL_METRICS_INCLUDE_SESSION_ID !== "false",
8482 includeVersion: process.env.OTEL_METRICS_INCLUDE_VERSION === "true",
8583 includeAccountUuid:
8684 process.env.OTEL_METRICS_INCLUDE_ACCOUNT_UUID !== "false",
@@ -93,12 +91,10 @@
9391 const resource = resourceFromAttributes({
9492 [SEMRESATTRS_SERVICE_NAME]: "continue-cli",
9593 [SEMRESATTRS_SERVICE_VERSION]: getVersion(),
96- [SEMRESATTRS_SERVICE_INSTANCE_ID]: uuidv4(),
9794 [SEMRESATTRS_HOST_NAME]: os.hostname(),
9895 [SEMRESATTRS_DEPLOYMENT_ENVIRONMENT]:
9996 process.env.NODE_ENV || "development",
10097 [SEMRESATTRS_OS_TYPE]: os.type(),
101- [SEMRESATTRS_PROCESS_PID]: process.pid.toString(),
10298 });
10399
104100 // Configure exporters
@@ -113,11 +109,20 @@
113109 readers.push(
114110 new PeriodicExportingMetricReader({
115111 exporter: new OTLPMetricExporter({
116- url:
117- process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT ||
118- `${process.env.OTEL_EXPORTER_OTLP_ENDPOINT}/v1/metrics` ||
119- "http://localhost:4318/v1/metrics",
120- headers: this.parseHeaders(
112+ url: (() => {
113+ const metricsEndpoint =
114+ process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT;
115+ if (metricsEndpoint && metricsEndpoint.trim().length > 0) {
116+ return metricsEndpoint;
117+ }
118+ const base = process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
119+ if (base && base.trim().length > 0) {
120+ const normalized = base.replace(/\/$/, "");
121+ return `${normalized}/v1/metrics`;
122+ }
123+ return "http://localhost:4318/v1/metrics";
124+ })(),
125+ headers: parseOtelHeaders(
121126 process.env.OTEL_EXPORTER_OTLP_HEADERS || "",
122127 ),
123128 }),
@@ -183,20 +188,6 @@
183188 this.shutdownHandlersRegistered = true;
184189 }
185190
186- private parseHeaders(headersStr: string): Record<string, string> {
187- const headers: Record<string, string> = {};
188- if (!headersStr) return headers;
189-
190- headersStr.split(",").forEach((header) => {
191- const [key, value] = header.split("=");
192- if (key && value) {
193- headers[key.trim()] = value.trim();
194- }
195- });
196-
197- return headers;
198- }
199-
200191 private initializeMetrics() {
201192 if (!this.meter) return;
202193
@@ -308,10 +299,6 @@
308299 ) {
309300 const attributes: Record<string, string> = { ...additionalAttributes };
310301
311- if (this.config.includeSessionId) {
312- attributes["session.id"] = this.config.sessionId;
313- }
314-
315302 if (this.config.includeVersion) {
316303 attributes["app.version"] = getVersion();
317304 }
@@ -325,7 +312,7 @@
325312 }
326313
327314 // Detect terminal type
328- const terminalType = this.detectTerminalType();
315+ const terminalType = detectTerminalType();
329316 if (terminalType) {
330317 attributes["terminal.type"] = terminalType;
331318 }
@@ -333,19 +320,6 @@
333320 return attributes;
334321 }
335322
336- private detectTerminalType(): string | undefined {
337- if (process.env.TERM_PROGRAM) {
338- return process.env.TERM_PROGRAM;
339- }
340- if (process.env.VSCODE_PID) {
341- return "vscode";
342- }
343- if (process.env.TMUX) {
344- return "tmux";
345- }
346- return undefined;
347- }
348-
349323 // Public methods for tracking metrics
350324
351325 public recordSessionStart() {
@@ -435,13 +409,12 @@
435409 if (!this.isEnabled()) return;
436410
437411 if (this.activeStartTime !== null) {
438- this.totalActiveTime += Date.now() - this.activeStartTime;
412+ const deltaMs = Date.now() - this.activeStartTime;
413+ this.totalActiveTime += deltaMs;
439414 this.activeStartTime = null;
440415
441- this.activeTimeCounter.add(
442- this.totalActiveTime / 1000,
443- this.getStandardAttributes(),
444- );
416+ // Record only the delta for this active window (in seconds)
417+ this.activeTimeCounter.add(deltaMs / 1000, this.getStandardAttributes());
445418 }
446419 }
447420
modified extensions/cli/src/tools/exit.ts +3 −1
@@ -9,6 +9,8 @@
99 readonly: false,
1010 isBuiltIn: true,
1111 run: async (): Promise<string> => {
12- process.exit(1);
12+ const { gracefulExit } = await import("../util/exit.js");
13+ await gracefulExit(1);
14+ return "";
1315 },
1416 };
modified extensions/cli/src/ui/hooks/useChat.helpers.ts +1 −1
@@ -67,7 +67,7 @@
6767 onClear,
6868 }: ProcessSlashCommandResultOptions): string | null {
6969 if (result.exit) {
70- process.exit(0);
70+ import("../../util/exit.js").then(({ gracefulExit }) => gracefulExit(0));
7171 }
7272
7373 if (result.openMcpSelector) {
modified extensions/cli/src/ui/hooks/useUserInput.ts +1 −1
@@ -76,7 +76,7 @@
7676 // Handle Ctrl+D to exit
7777 if (key.ctrl && input === "d") {
7878 exit();
79- process.exit(0);
79+ import("../../util/exit.js").then(({ gracefulExit }) => gracefulExit(0));
8080 }
8181
8282 // Handle Ctrl+L to refresh screen (clear terminal artifacts)
added extensions/cli/src/util/exit.ts +27 −0
@@ -0,0 +1,27 @@
1+import { sentryService } from "../sentry.js";
2+import { telemetryService } from "../telemetry/telemetryService.js";
3+
4+import { logger } from "./logger.js";
5+
6+/**
7+ * Exit the process after flushing telemetry and error reporting.
8+ * Use this instead of process.exit() to avoid losing metrics/logs.
9+ */
10+export async function gracefulExit(code: number = 0): Promise<void> {
11+ try {
12+ // Flush metrics (forceFlush + shutdown inside service)
13+ await telemetryService.shutdown();
14+ } catch (err) {
15+ logger.debug("Telemetry shutdown error (ignored)", err as any);
16+ }
17+
18+ try {
19+ // Flush Sentry (best effort)
20+ await sentryService.flush();
21+ } catch (err) {
22+ logger.debug("Sentry flush error (ignored)", err as any);
23+ }
24+
25+ // Exit the process
26+ process.exit(code);
27+}