Elffuss BraidHub

kikocis/continue public

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