Elffuss BraidHub

kikocis/continue public

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