Elffuss BraidHub

kikocis/continue public

main · 17.2 KiBRawPermalink
1import os from "os";
2
3import { metrics } from "@opentelemetry/api";
4import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http";
5import { resourceFromAttributes } from "@opentelemetry/resources";
6import {
7 ConsoleMetricExporter,
8 MeterProvider,
9 PeriodicExportingMetricReader,
10} from "@opentelemetry/sdk-metrics";
11import {
12 SEMRESATTRS_DEPLOYMENT_ENVIRONMENT,
13 SEMRESATTRS_HOST_NAME,
14 SEMRESATTRS_OS_TYPE,
15 SEMRESATTRS_SERVICE_NAME,
16 SEMRESATTRS_SERVICE_VERSION,
17} from "@opentelemetry/semantic-conventions";
18import { v4 as uuidv4 } from "uuid";
19
20import { isHeadlessMode } from "../util/cli.js";
21import { isContinueRemoteAgent, isGitHubActions } from "../util/git.js";
22import { logger } from "../util/logger.js";
23import { getVersion } from "../version.js";
24
25import { detectTerminalType, parseOtelHeaders } from "./headerUtils.js";
26
27export interface TelemetryConfig {
28 enabled: boolean;
29 sessionId: string;
30 organizationId?: string;
31 accountUuid?: string;
32 includeVersion: boolean;
33 includeAccountUuid: boolean;
34}
35
36class TelemetryService {
37 private meterProvider: MeterProvider | null = null;
38 private meter: any = null;
39 private config: TelemetryConfig;
40 private startTime = Date.now();
41 private activeStartTime: number | null = null;
42 private totalActiveTime = 0;
43 private shutdownHandlersRegistered = false;
44
45 // Metrics
46 private sessionCounter: any = null;
47 private linesOfCodeCounter: any = null;
48 private pullRequestCounter: any = null;
49 private commitCounter: any = null;
50 private costCounter: any = null;
51 private tokenCounter: any = null;
52 private codeEditDecisionCounter: any = null;
53 private activeTimeCounter: any = null;
54 private authAttemptsCounter: any = null;
55 private mcpConnectionsGauge: any = null;
56 private startupTimeHistogram: any = null;
57 private responseTimeHistogram: any = null;
58 private slashCommandCounter: any = null;
59
60 constructor() {
61 this.config = this.loadConfig();
62 if (this.config.enabled) {
63 this.initialize();
64 }
65 }
66
67 private loadConfig(): TelemetryConfig {
68 const hasOtelConfig = !!(
69 process.env.OTEL_EXPORTER_OTLP_ENDPOINT ||
70 process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT ||
71 process.env.OTEL_METRICS_EXPORTER
72 );
73 const enabled =
74 process.env.CONTINUE_CLI_ENABLE_TELEMETRY !== "0" && hasOtelConfig;
75 const sessionId = uuidv4();
76
77 return {
78 enabled,
79 sessionId,
80 organizationId: process.env.ORGANIZATION_ID,
81 accountUuid: process.env.ACCOUNT_UUID,
82 includeVersion: process.env.OTEL_METRICS_INCLUDE_VERSION === "true",
83 includeAccountUuid:
84 process.env.OTEL_METRICS_INCLUDE_ACCOUNT_UUID !== "false",
85 };
86 }
87
88 private initialize() {
89 try {
90 // Create resource
91 const resource = resourceFromAttributes({
92 [SEMRESATTRS_SERVICE_NAME]: "continue-cli",
93 [SEMRESATTRS_SERVICE_VERSION]: getVersion(),
94 [SEMRESATTRS_HOST_NAME]: os.hostname(),
95 [SEMRESATTRS_DEPLOYMENT_ENVIRONMENT]:
96 process.env.NODE_ENV || "development",
97 [SEMRESATTRS_OS_TYPE]: os.type(),
98 });
99
100 // Configure exporters
101 const readers: any[] = [];
102 const metricsExporters = (
103 process.env.OTEL_METRICS_EXPORTER || "console"
104 ).split(",");
105
106 for (const exporterType of metricsExporters) {
107 switch (exporterType.trim()) {
108 case "otlp":
109 readers.push(
110 new PeriodicExportingMetricReader({
111 exporter: new OTLPMetricExporter({
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(
126 process.env.OTEL_EXPORTER_OTLP_HEADERS || "",
127 ),
128 }),
129 exportIntervalMillis: parseInt(
130 process.env.OTEL_METRIC_EXPORT_INTERVAL || "20000",
131 ),
132 }),
133 );
134 break;
135 case "console":
136 readers.push(
137 new PeriodicExportingMetricReader({
138 exporter: new ConsoleMetricExporter(),
139 exportIntervalMillis: parseInt(
140 process.env.OTEL_METRIC_EXPORT_INTERVAL || "20000",
141 ),
142 }),
143 );
144 break;
145 }
146 }
147
148 // Create meter provider
149 this.meterProvider = new MeterProvider({
150 resource,
151 readers,
152 });
153
154 metrics.setGlobalMeterProvider(this.meterProvider);
155 this.meter = metrics.getMeter("continue-cli", getVersion());
156
157 this.initializeMetrics();
158
159 // Set up graceful shutdown handlers
160 this.setupShutdownHandlers();
161
162 logger.info("Telemetry service initialized", {
163 sessionId: this.config.sessionId,
164 exporters: metricsExporters,
165 exportInterval: process.env.OTEL_METRIC_EXPORT_INTERVAL || "20000",
166 });
167 } catch (error) {
168 logger.error("Failed to initialize telemetry", error);
169 }
170 }
171
172 /**
173 * Set up process handlers to ensure metrics are flushed on shutdown
174 */
175 private setupShutdownHandlers() {
176 if (this.shutdownHandlersRegistered) return;
177
178 const shutdownHandler = async () => {
179 logger.debug("Process shutdown detected, flushing telemetry...");
180 await this.shutdown();
181 };
182
183 // Handle graceful shutdown - use once() to avoid duplicate handlers
184 process.once("beforeExit", shutdownHandler);
185 process.once("SIGINT", shutdownHandler);
186 process.once("SIGTERM", shutdownHandler);
187
188 this.shutdownHandlersRegistered = true;
189 }
190
191 private initializeMetrics() {
192 if (!this.meter) return;
193
194 // Core metrics (Claude Code compatible)
195 this.sessionCounter = this.meter.createCounter(
196 "continue_cli_session_count",
197 {
198 description: "Count of CLI sessions started",
199 unit: "count",
200 },
201 );
202
203 this.linesOfCodeCounter = this.meter.createCounter(
204 "continue_cli_lines_of_code_count",
205 {
206 description: "Count of lines of code modified",
207 unit: "count",
208 },
209 );
210
211 this.pullRequestCounter = this.meter.createCounter(
212 "continue_cli_pull_request_count",
213 {
214 description: "Number of pull requests created",
215 unit: "count",
216 },
217 );
218
219 this.commitCounter = this.meter.createCounter("continue_cli_commit_count", {
220 description: "Number of git commits created",
221 unit: "count",
222 });
223
224 this.costCounter = this.meter.createCounter("continue_cli_cost_usage", {
225 description: "Cost of the Continue CLI session",
226 unit: "USD",
227 });
228
229 this.tokenCounter = this.meter.createCounter("continue_cli_token_usage", {
230 description: "Number of tokens used",
231 unit: "tokens",
232 });
233
234 this.codeEditDecisionCounter = this.meter.createCounter(
235 "continue_cli_code_edit_tool_decision",
236 {
237 description: "Count of code editing tool permission decisions",
238 unit: "count",
239 },
240 );
241
242 this.activeTimeCounter = this.meter.createCounter(
243 "continue_cli_active_time_total",
244 {
245 description: "Total active time in seconds",
246 unit: "s",
247 },
248 );
249
250 // Additional Continue CLI specific metrics
251 this.authAttemptsCounter = this.meter.createCounter(
252 "continue_cli_auth_attempts",
253 {
254 description: "Authentication attempts",
255 unit: "{attempt}",
256 },
257 );
258
259 this.mcpConnectionsGauge = this.meter.createObservableGauge(
260 "continue_cli_mcp_connections",
261 {
262 description: "Active MCP connections",
263 unit: "{connection}",
264 },
265 );
266
267 this.startupTimeHistogram = this.meter.createHistogram(
268 "continue_cli_startup_time",
269 {
270 description: "Time from CLI start to ready state",
271 unit: "ms",
272 },
273 );
274
275 this.responseTimeHistogram = this.meter.createHistogram(
276 "continue_cli_response_time",
277 {
278 description: "LLM response time metrics",
279 unit: "ms",
280 },
281 );
282
283 this.slashCommandCounter = this.meter.createCounter(
284 "continue_cli_slash_command_usage",
285 {
286 description: "Count of slash commands used",
287 unit: "count",
288 },
289 );
290 }
291
292 // Check if telemetry is enabled - this is the single point of checking
293 private isEnabled(): boolean {
294 return this.config.enabled && this.meter !== null;
295 }
296
297 private getStandardAttributes(
298 additionalAttributes: Record<string, string> = {},
299 ) {
300 const attributes: Record<string, string> = { ...additionalAttributes };
301
302 if (this.config.includeVersion) {
303 attributes["app.version"] = getVersion();
304 }
305
306 if (this.config.organizationId) {
307 attributes["organization.id"] = this.config.organizationId;
308 }
309
310 if (this.config.includeAccountUuid && this.config.accountUuid) {
311 attributes["user.account_uuid"] = this.config.accountUuid;
312 }
313
314 // Detect terminal type
315 const terminalType = detectTerminalType();
316 if (terminalType) {
317 attributes["terminal.type"] = terminalType;
318 }
319
320 return attributes;
321 }
322
323 // Public methods for tracking metrics
324
325 public recordSessionStart() {
326 if (!this.isEnabled()) return;
327
328 logger.debug("Recording session start with telemetry");
329
330 // Add extra metadata for session breakdown
331 const isGitHubActionsEnv = isGitHubActions();
332 const sessionAttributes = this.getStandardAttributes({
333 is_headless: isHeadlessMode().toString(),
334 is_github_actions: isGitHubActionsEnv.toString(),
335 is_continue_remote_agent: isContinueRemoteAgent().toString(),
336 });
337
338 this.sessionCounter.add(1, sessionAttributes);
339 this.recordStartupTime(Date.now() - this.startTime);
340 }
341
342 public recordLinesOfCodeModified(
343 type: "added" | "removed",
344 count: number,
345 language?: string,
346 ) {
347 if (!this.isEnabled()) return;
348
349 const attributes = this.getStandardAttributes({ type });
350 if (language) {
351 attributes.language = language;
352 }
353
354 this.linesOfCodeCounter.add(count, attributes);
355 }
356
357 public recordPullRequestCreated() {
358 if (!this.isEnabled()) return;
359
360 this.pullRequestCounter.add(1, this.getStandardAttributes());
361 }
362
363 public recordCommitCreated() {
364 if (!this.isEnabled()) return;
365
366 this.commitCounter.add(1, this.getStandardAttributes());
367 }
368
369 public recordCost(cost: number, model: string) {
370 if (!this.isEnabled()) return;
371
372 this.costCounter.add(cost, this.getStandardAttributes({ model }));
373 }
374
375 public recordTokenUsage(
376 tokens: number,
377 type: "input" | "output" | "cacheRead" | "cacheCreation",
378 model: string,
379 ) {
380 if (!this.isEnabled()) return;
381
382 this.tokenCounter.add(tokens, this.getStandardAttributes({ type, model }));
383 }
384
385 public recordCodeEditDecision(
386 tool: string,
387 decision: "accept" | "reject",
388 language?: string,
389 ) {
390 if (!this.isEnabled()) return;
391
392 const attributes = this.getStandardAttributes({ tool, decision });
393 if (language) {
394 attributes.language = language;
395 }
396
397 this.codeEditDecisionCounter.add(1, attributes);
398 }
399
400 public startActiveTime() {
401 if (!this.isEnabled()) return;
402
403 if (this.activeStartTime === null) {
404 this.activeStartTime = Date.now();
405 }
406 }
407
408 public stopActiveTime() {
409 if (!this.isEnabled()) return;
410
411 if (this.activeStartTime !== null) {
412 const deltaMs = Date.now() - this.activeStartTime;
413 this.totalActiveTime += deltaMs;
414 this.activeStartTime = null;
415
416 // Record only the delta for this active window (in seconds)
417 this.activeTimeCounter.add(deltaMs / 1000, this.getStandardAttributes());
418 }
419 }
420
421 public recordAuthAttempt(
422 result: "success" | "failure" | "cancelled",
423 method: "workos" | "token",
424 ) {
425 if (!this.isEnabled()) return;
426
427 this.authAttemptsCounter.add(
428 1,
429 this.getStandardAttributes({ result, method }),
430 );
431 }
432
433 public recordMCPConnection(
434 serverName: string,
435 status: "connected" | "disconnected" | "error",
436 ) {
437 if (!this.isEnabled()) return;
438
439 const value = status === "connected" ? 1 : 0;
440 // Note: Observable gauge callback will be implemented when MCP monitoring is added
441 if (this.mcpConnectionsGauge) {
442 // This is a placeholder - observable gauges work differently
443 logger.debug("MCP connection status", { serverName, status, value });
444 }
445 }
446
447 public recordStartupTime(
448 timeMs: number,
449 mode?: "tui" | "headless" | "standard",
450 coldStart?: boolean,
451 ) {
452 if (!this.isEnabled()) return;
453
454 const attributes = this.getStandardAttributes();
455 if (mode) attributes.mode = mode;
456 if (coldStart !== undefined) attributes.cold_start = coldStart.toString();
457
458 this.startupTimeHistogram.record(timeMs, attributes);
459 }
460
461 public recordResponseTime(
462 timeMs: number,
463 model: string,
464 metricType: "time_to_first_token" | "total_response_time",
465 hasTools?: boolean,
466 ) {
467 if (!this.isEnabled()) return;
468
469 const attributes = this.getStandardAttributes({
470 model,
471 metric_type: metricType,
472 });
473 if (hasTools !== undefined) attributes.has_tools = hasTools.toString();
474
475 this.responseTimeHistogram.record(timeMs, attributes);
476 }
477
478 // Event logging methods (these will be implemented when OTLP logs support is added)
479 public logUserPrompt(promptLength: number, prompt?: string) {
480 if (!this.isEnabled()) return;
481
482 const attributes = this.getStandardAttributes({
483 "event.name": "user_prompt",
484 "event.timestamp": new Date().toISOString(),
485 prompt_length: promptLength.toString(),
486 });
487
488 if (process.env.OTEL_LOG_USER_PROMPTS === "1" && prompt) {
489 attributes.prompt = prompt;
490 }
491
492 // TODO: Implement OTLP logs export
493 logger.debug("User prompt event", attributes);
494 }
495
496 public logToolResult(options: {
497 toolName: string;
498 success: boolean;
499 durationMs: number;
500 error?: string;
501 errorReason?: string;
502 decision?: "accept" | "reject";
503 source?: string;
504 toolParameters?: string;
505 // modelName: string;
506 }) {
507 if (!this.isEnabled()) return;
508
509 const attributes = this.getStandardAttributes({
510 "event.name": "tool_result",
511 "event.timestamp": new Date().toISOString(),
512 tool_name: options.toolName,
513 success: options.success.toString(),
514 duration_ms: options.durationMs.toString(),
515 });
516
517 if (options.error) attributes.error = options.error;
518 if (options.decision) attributes.decision = options.decision;
519 if (options.source) attributes.source = options.source;
520 if (options.toolParameters)
521 attributes.tool_parameters = options.toolParameters;
522 if (options.errorReason) {
523 attributes.error_reason = options.errorReason;
524 }
525 if (options.error) {
526 attributes.error = options.error;
527 }
528
529 // TODO: Implement OTLP logs export
530 logger.debug("Tool result event", attributes);
531 }
532
533 public logApiRequest(options: {
534 model: string;
535 durationMs: number;
536 success: boolean;
537 error?: string;
538 inputTokens?: number;
539 outputTokens?: number;
540 costUsd?: number;
541 }) {
542 if (!this.isEnabled()) return;
543
544 const attributes = this.getStandardAttributes({
545 "event.name": "api_request",
546 "event.timestamp": new Date().toISOString(),
547 model: options.model,
548 duration_ms: options.durationMs.toString(),
549 success: options.success.toString(),
550 });
551
552 if (options.error) attributes.error = options.error;
553 if (options.inputTokens)
554 attributes.input_tokens = options.inputTokens.toString();
555 if (options.outputTokens)
556 attributes.output_tokens = options.outputTokens.toString();
557 if (options.costUsd) attributes.cost_usd = options.costUsd.toString();
558
559 // TODO: Implement OTLP logs export
560 logger.debug("API request event", attributes);
561 }
562
563 public updateOrganization(organizationId: string) {
564 this.config.organizationId = organizationId;
565 }
566
567 public updateAccountUuid(accountUuid: string) {
568 this.config.accountUuid = accountUuid;
569 }
570
571 public getSessionId(): string {
572 return this.config.sessionId;
573 }
574
575 public recordSlashCommand(commandName: string) {
576 if (!this.isEnabled()) return;
577
578 this.slashCommandCounter.add(
579 1,
580 this.getStandardAttributes({ command: commandName }),
581 );
582 }
583
584 /**
585 * Shutdown telemetry service and ensure all metrics are flushed
586 */
587 public async shutdown(): Promise<void> {
588 this.stopActiveTime();
589
590 if (this.meterProvider) {
591 try {
592 logger.debug("Flushing telemetry metrics before shutdown...");
593 // Force flush any pending metrics before shutdown
594 await this.meterProvider.forceFlush();
595 logger.debug("Telemetry metrics flushed successfully");
596
597 // Now shutdown the provider
598 await this.meterProvider.shutdown();
599 logger.debug("Telemetry service shut down successfully");
600 } catch (error) {
601 logger.error("Failed to shutdown telemetry service", error);
602 }
603 }
604 }
605}
606
607// Export the singleton instance directly
608export const telemetryService = new TelemetryService();