Elffuss BraidHub

kikocis/continue public

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