Elffuss BraidHub

kikocis/continue public

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