Merge pull request #75 from continuedev/otlp-more

feat: more otlp metrics
This commit is contained in:
Nate Sesti 2025-07-20 11:22:31 -07:00 • committed by GitHub
commit be8e5690ce
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
12 changed files with 1266 additions and 392 deletions

342
spec/otlp-metrics.md Normal file
View file

@ -0,0 +1,342 @@
# OTLP Metrics Specification for Continue CLI
This document specifies the OpenTelemetry Protocol (OTLP) metrics that should be emitted by the Continue CLI to provide comprehensive observability and usage monitoring. The metrics are designed to be compatible with Claude Code dashboards for easy migration.
## Overview
The Continue CLI should emit metrics that provide insights into:
- Usage patterns and session analytics
- Performance and reliability
- Tool usage and effectiveness
- Error rates and types
- Resource utilization
- Code modification tracking
## Configuration
### Environment Variables
| Environment Variable | Description | Example Values |
| ------------------------------- | --------------------------------------------------------- | ------------------------------------ |
| `CONTINUE_CLI_ENABLE_TELEMETRY` | Enables telemetry collection (required) | `1` |
| `OTEL_METRICS_EXPORTER` | Metrics exporter type(s) (comma-separated) | `console`, `otlp`, `prometheus` |
| `OTEL_LOGS_EXPORTER` | Logs/events exporter type(s) (comma-separated) | `console`, `otlp` |
| `OTEL_EXPORTER_OTLP_PROTOCOL` | Protocol for OTLP exporter (all signals) | `grpc`, `http/json`, `http/protobuf` |
| `OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP collector endpoint (all signals) | `http://localhost:4317` |
| `OTEL_EXPORTER_OTLP_HEADERS` | Authentication headers for OTLP | `Authorization=Bearer token` |
| `OTEL_METRIC_EXPORT_INTERVAL` | Export interval in milliseconds (default: 60000) | `5000`, `60000` |
| `OTEL_LOGS_EXPORT_INTERVAL` | Logs export interval in milliseconds (default: 5000) | `1000`, `10000` |
| `OTEL_LOG_USER_PROMPTS` | Enable logging of user prompt content (default: disabled) | `1` to enable |
### Metrics Cardinality Control
| Environment Variable | Description | Default Value | Example to Disable |
| ----------------------------------- | ---------------------------------------------- | ------------- | ------------------ |
| `OTEL_METRICS_INCLUDE_SESSION_ID` | Include session.id attribute in metrics | `true` | `false` |
| `OTEL_METRICS_INCLUDE_VERSION` | Include app.version attribute in metrics | `false` | `true` |
| `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` | Include user.account_uuid attribute in metrics | `true` | `false` |
## Standard Attributes
All metrics and events share these standard attributes:
| Attribute | Description | Controlled By |
| ------------------- | ------------------------------------------------------------- | --------------------------------------------------- |
| `session.id` | Unique session identifier | `OTEL_METRICS_INCLUDE_SESSION_ID` (default: true) |
| `app.version` | Current Continue CLI version | `OTEL_METRICS_INCLUDE_VERSION` (default: false) |
| `organization.id` | Organization UUID (when authenticated) | Always included when available |
| `user.account_uuid` | Account UUID (when authenticated) | `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` (default: true) |
| `terminal.type` | Terminal type (e.g., `iTerm.app`, `vscode`, `cursor`, `tmux`) | Always included when detected |
## Core Metrics
### ✅ `continue.cli.session.count`
**Type:** Counter
**Unit:** `count`
**Description:** Count of CLI sessions started
**Attributes:**
- All [standard attributes](#standard-attributes)
**Implementation:** Track in `src/commands/chat.ts` when session starts
---
### ✅ `continue.cli.lines_of_code.count`
**Type:** Counter
**Unit:** `count`
**Description:** Count of lines of code modified
**Attributes:**
- All [standard attributes](#standard-attributes)
- `type`: (`"added"`, `"removed"`)
**Implementation:** Track in `src/tools/writeFile.ts` by analyzing file diffs
---
### ✅ `continue.cli.pull_request.count`
**Type:** Counter
**Unit:** `count`
**Description:** Number of pull requests created
**Attributes:**
- All [standard attributes](#standard-attributes)
**Implementation:** Track when `runTerminalCommand` executes git/gh commands for PR creation
---
### ✅ `continue.cli.commit.count`
**Type:** Counter
**Unit:** `count`
**Description:** Number of git commits created
**Attributes:**
- All [standard attributes](#standard-attributes)
**Implementation:** Track when `runTerminalCommand` executes `git commit` commands
---
### ✅ `continue.cli.cost.usage`
**Type:** Counter
**Unit:** `USD`
**Description:** Cost of the Continue CLI session
**Attributes:**
- All [standard attributes](#standard-attributes)
- `model`: Model identifier (e.g., "claude-3-5-sonnet-20241022", "gpt-4")
**Implementation:** Calculate costs based on token usage and model pricing in `src/streamChatResponse.ts`
---
### ✅ `continue.cli.token.usage`
**Type:** Counter
**Unit:** `tokens`
**Description:** Number of tokens used
**Attributes:**
- All [standard attributes](#standard-attributes)
- `type`: (`"input"`, `"output"`, `"cacheRead"`, `"cacheCreation"`)
- `model`: Model identifier (e.g., "claude-3-5-sonnet-20241022", "gpt-4")
**Implementation:** Track in `src/streamChatResponse.ts` after each API response
---
### ❌ `continue.cli.code_edit_tool.decision`
**Type:** Counter
**Unit:** `count`
**Description:** Count of code editing tool permission decisions
**Attributes:**
- All [standard attributes](#standard-attributes)
- `tool`: Tool name (`"writeFile"`, `"runTerminalCommand"`, etc.)
- `decision`: User decision (`"accept"`, `"reject"`)
- `language`: Programming language of the edited file (e.g., `"TypeScript"`, `"Python"`, `"JavaScript"`, `"Markdown"`). Returns `"unknown"` for unrecognized file extensions.
**Implementation:** Track in tool execution when user confirmation is required (if implemented)
---
### ✅ `continue.cli.active_time.total`
**Type:** Counter
**Unit:** `s`
**Description:** Total active time in seconds
**Attributes:**
- All [standard attributes](#standard-attributes)
**Implementation:** Track in TUI mode (`src/ui/TUIChat.tsx`) and standard chat mode, measuring time during active interactions
## Core Events
### ✅ User Prompt Event
**Event Name:** `continue.cli.user_prompt`
**Attributes:**
- All [standard attributes](#standard-attributes)
- `event.name`: `"user_prompt"`
- `event.timestamp`: ISO 8601 timestamp
- `prompt_length`: Length of the prompt
- `prompt`: Prompt content (redacted by default, enable with `OTEL_LOG_USER_PROMPTS=1`)
**Implementation:** Log in `src/streamChatResponse.ts` when user message is added to chat history
---
### ✅ Tool Result Event
**Event Name:** `continue.cli.tool_result`
**Attributes:**
- All [standard attributes](#standard-attributes)
- `event.name`: `"tool_result"`
- `event.timestamp`: ISO 8601 timestamp
- `tool_name`: Name of the tool
- `success`: `"true"` or `"false"`
- `duration_ms`: Execution time in milliseconds
- `error`: Error message (if failed)
- `decision`: Either `"accept"` or `"reject"` (if applicable)
- `source`: Decision source - `"config"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"` (if applicable)
- `tool_parameters`: JSON string containing tool-specific parameters (when available)
**Implementation:** Log in `src/tools/index.ts` `executeToolCall` function
---
### ✅ API Request Event
**Event Name:** `continue.cli.api_request`
**Attributes:**
- All [standard attributes](#standard-attributes)
- `event.name`: `"api_request"`
- `event.timestamp`: ISO 8601 timestamp
- `model`: Model identifier
- `duration_ms`: Request duration in milliseconds
- `success`: `"true"` or `"false"`
- `error`: Error message (if failed)
- `input_tokens`: Number of input tokens
- `output_tokens`: Number of output tokens
- `cost_usd`: Request cost in USD
**Implementation:** Log in `src/streamChatResponse.ts` for each API request
## Additional Metrics
These metrics are unique to Continue CLI and provide additional insights without conflicting with compatibility:
### Authentication Metrics
#### ✅ `continue.cli.auth.attempts`
**Type:** Counter
**Unit:** `{attempt}`
**Description:** Authentication attempts
**Labels:**
- All [standard attributes](#standard-attributes)
- `result`: `success` | `failure` | `cancelled`
- `method`: `workos` | `token`
**Implementation:** Track in `src/auth/workos.ts`
### MCP Integration Metrics
#### ❌ `continue.cli.mcp.connections`
**Type:** Gauge
**Unit:** `{connection}`
**Description:** Active MCP connections
**Labels:**
- All [standard attributes](#standard-attributes)
- `server_name`: MCP server identifier
- `status`: `connected` | `disconnected` | `error`
**Implementation:** Track in `src/mcp.ts`
### Performance Metrics
#### ❌ `continue.cli.startup.time`
**Type:** Histogram
**Unit:** `ms`
**Description:** Time from CLI start to ready state
**Labels:**
- All [standard attributes](#standard-attributes)
- `mode`: `tui` | `headless` | `standard`
- `cold_start`: `true` | `false`
**Implementation:** Track in `src/index.ts` and `src/commands/chat.ts`
#### ✅ `continue.cli.response_time`
**Type:** Histogram
**Unit:** `ms`
**Description:** LLM response time metrics (supplements API request events)
**Labels:**
- All [standard attributes](#standard-attributes)
- `model`: Model identifier
- `metric_type`: `time_to_first_token` | `total_response_time`
- `has_tools`: `true` | `false`
**Implementation:** Track in `src/streamChatResponse.ts`
## Implementation Guidelines
### Migration from Claude Code Dashboards
The core metrics (`session.count`, `lines_of_code.count`, `token.usage`, `cost.usage`, etc.) use identical naming and attribute structures to Claude Code, allowing for easy dashboard migration by simply changing the metric prefix from `claude_code.*` to `continue.cli.*`.
### Privacy Considerations
- **No PII**: Avoid logging file paths, user content, or other personally identifiable information
- **Redacted by Default**: User prompts are redacted unless `OTEL_LOG_USER_PROMPTS=1`
- **Configurable Attributes**: Use cardinality control variables to manage data granularity
- **Opt-out**: Provide mechanism to disable telemetry entirely
### Resource Attributes
All metrics should include these resource attributes:
- `service.name`: `continue-cli`
- `service.version`: CLI version
- `deployment.environment`: `development` | `production`
- `os.type`: Operating system
- `process.pid`: Process ID
### Implementation Points
1. **Session Tracking**: Initialize session ID and track lifecycle in `src/commands/chat.ts`
2. **Token/Cost Tracking**: Implement in `src/streamChatResponse.ts` with model-specific pricing
3. **Tool Usage**: Track in `src/tools/index.ts` and individual tool implementations
4. **File Operations**: Implement diff analysis in `src/tools/writeFile.ts` for LOC tracking
5. **Command Detection**: Parse git/gh commands in `src/tools/runTerminalCommand.ts`
6. **Authentication**: Track auth flows in `src/auth/workos.ts`
7. **Performance**: Add timing measurements throughout the application lifecycle
## Implementation Status
✅ = Implemented
❌ = Not implemented yet
**Core metrics:** 6/7 implemented (83%)
**Core events:** 3/3 implemented (100%)
**Additional metrics:** 4/7 implemented (57%)
**Missing implementations:**
- `continue.cli.code_edit_tool.decision` - requires user confirmation UI
- `continue.cli.mcp.connections` - needs MCP service monitoring
- `continue.cli.startup.time` - needs startup time tracking

View file

@ -2,13 +2,14 @@ import chalk from "chalk";
import { ChatCompletionMessageParam } from "openai/resources.mjs";
import * as readlineSync from "readline-sync";
import { CONTINUE_ASCII_ART } from "../asciiArt.js";
import { ensureOrganization, loadAuthConfig } from "../auth/workos.js";
import { ensureOrganization, loadAuthConfig, getOrganizationId } from "../auth/workos.js";
import { introMessage } from "../intro.js";
import { configureLogger } from "../logger.js";
import { initializeWithOnboarding } from "../onboarding.js";
import { loadSession, saveSession } from "../session.js";
import { streamChatResponse } from "../streamChatResponse.js";
import { constructSystemMessage } from "../systemMessage.js";
import telemetryService from "../telemetry/telemetryService.js";
import { startTUIChat } from "../ui/index.js";
import { safeStdout } from "../util/consoleOverride.js";
import { formatError } from "../util/formatError.js";
@ -43,6 +44,14 @@ async function initializeChat(options: ChatOptions) {
authConfig,
options.headless ?? false
);
// Update telemetry with organization info
if (finalAuthConfig) {
const organizationId = getOrganizationId(finalAuthConfig);
if (organizationId) {
telemetryService.updateOrganization(organizationId);
}
}
}
return {
@ -58,8 +67,14 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
configureLogger(options.headless ?? false);
try {
// Record session start
telemetryService.recordSessionStart();
let { config, llmApi, model, mcpService } = await initializeChat(options);
// Start active time tracking
telemetryService.startActiveTime();
// If not in headless mode, start the TUI chat (default)
if (!options.headless) {
await startTUIChat(
@ -121,6 +136,9 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
isFirstMessage = false;
// Track user prompt
telemetryService.logUserPrompt(userInput.length, userInput);
// Add user message to history
chatHistory.push({ role: "user", content: userInput });
@ -157,5 +175,8 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
} catch (error: any) {
logger.error(chalk.red(`Fatal error: ${formatError(error)}`));
process.exit(1);
} finally {
// Stop active time tracking
telemetryService.stopActiveTime();
}
}
}

View file

@ -9,10 +9,11 @@ export async function logout() {
".continue",
".onboarding_complete"
);
workosLogout();
// Remove onboarding completion flag so user will go through onboarding again
if (fs.existsSync(onboardingFlagPath)) {
fs.unlinkSync(onboardingFlagPath);
}
workosLogout();
}

View file

@ -4,23 +4,10 @@ import { Command } from "commander";
import { chat } from "./commands/chat.js";
import { login } from "./commands/login.js";
import { logout } from "./commands/logout.js";
import { initializeTelemetry } from "./telemetry.js";
import { configureConsoleForHeadless } from "./util/consoleOverride.js";
import logger from "./util/logger.js";
import { getVersion } from "./version.js";
// Initialize telemetry early (async)
(async () => {
await initializeTelemetry({
serviceName: "cn",
serviceVersion: getVersion(),
// Remove hardcoded fallback - let telemetry.ts handle environment variables
enabled: process.env.TELEMETRY_ENABLED !== "false",
});
})().catch((err) => {
logger.error("Failed to initialize telemetry:", err);
});
// Add global error handlers to prevent uncaught errors from crashing the process
process.on("unhandledRejection", (reason, promise) => {
logger.error("Unhandled Rejection at:", { promise, reason });

View file

@ -10,6 +10,8 @@ import type {
} from "openai/resources.mjs";
import { parseArgs } from "./args.js";
import { MCPService } from "./mcp.js";
import telemetryService from "./telemetry/telemetryService.js";
import { calculateTokenCost } from "./telemetry/utils.js";
import { executeToolCall } from "./tools.js";
import { BUILTIN_TOOLS } from "./tools/index.js";
import {
@ -107,6 +109,8 @@ async function processStreamingResponse(
toolCalls: ToolCall[];
shouldContinue: boolean;
}> {
const requestStartTime = Date.now();
const streamFactory = async () => {
logger.debug("Creating chat completion stream", {
model,
@ -128,6 +132,9 @@ async function processStreamingResponse(
let aiResponse = "";
const toolCallsMap = new Map<string, ToolCall>();
let firstTokenTime: number | null = null;
let inputTokens = 0;
let outputTokens = 0;
try {
const streamWithBackoff = withExponentialBackoff(
@ -141,6 +148,26 @@ async function processStreamingResponse(
logger.debug("Received chunk", { chunkCount, chunk });
// Track first token time
if (
firstTokenTime === null &&
(chunk.choices[0].delta.content || chunk.choices[0].delta.tool_calls)
) {
firstTokenTime = Date.now();
telemetryService.recordResponseTime(
firstTokenTime - requestStartTime,
model.model,
"time_to_first_token",
(tools?.length || 0) > 0
);
}
// Track token usage if available
if (chunk.usage) {
inputTokens = chunk.usage.prompt_tokens || 0;
outputTokens = chunk.usage.completion_tokens || 0;
}
// Check if we should abort
if (abortController?.signal.aborted) {
logger.debug("Stream aborted");
@ -211,12 +238,54 @@ async function processStreamingResponse(
}
}
const responseEndTime = Date.now();
const totalDuration = responseEndTime - requestStartTime;
// Record API request metrics
const cost = calculateTokenCost(inputTokens, outputTokens, model.model);
telemetryService.recordTokenUsage(inputTokens, "input", model.model);
telemetryService.recordTokenUsage(outputTokens, "output", model.model);
telemetryService.recordCost(cost, model.model);
telemetryService.recordResponseTime(
totalDuration,
model.model,
"total_response_time",
(tools?.length || 0) > 0
);
// Log API request event
telemetryService.logApiRequest(
model.model,
totalDuration,
true, // success
undefined, // no error
inputTokens,
outputTokens,
cost
);
logger.debug("Stream complete", {
chunkCount,
responseLength: aiResponse.length,
toolCallsCount: toolCallsMap.size,
inputTokens,
outputTokens,
cost,
duration: totalDuration,
});
} catch (error: any) {
const errorDuration = Date.now() - requestStartTime;
// Log failed API request
telemetryService.logApiRequest(
model.model,
errorDuration,
false, // failed
error.message || String(error)
);
if (error.name === "AbortError" || abortController?.signal.aborted) {
logger.debug("Stream aborted by user");
return { content: aiResponse, toolCalls: [], shouldContinue: false };

View file

@ -1,365 +0,0 @@
import { Meter, metrics, Counter, Histogram, ObservableGauge } from "@opentelemetry/api";
import { OTLPMetricExporter as OTLPMetricExporterGRPC } from "@opentelemetry/exporter-metrics-otlp-grpc";
import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http";
import {
MeterProvider,
PeriodicExportingMetricReader,
} from "@opentelemetry/sdk-metrics";
import { NodeSDK } from "@opentelemetry/sdk-node";
import {
ATTR_SERVICE_NAME,
ATTR_SERVICE_VERSION,
} from "@opentelemetry/semantic-conventions";
import logger from "./util/logger.js";
export interface TelemetryConfig {
serviceName?: string;
serviceVersion?: string;
otlpEndpoint?: string;
otlpHeaders?: Record<string, string>;
exportInterval?: number; // in milliseconds
protocol?: "http" | "grpc";
enabled?: boolean;
}
export class ContinueCLITelemetry {
private sdk: NodeSDK | null = null;
private meterProvider: MeterProvider | null = null;
private meter: Meter | null = null;
private config: Required<TelemetryConfig>;
// Pre-created instruments to avoid creating new ones on each call
private commandCounter: Counter | null = null;
private commandDurationHistogram: Histogram | null = null;
private chatInteractionCounter: Counter | null = null;
private chatResponseTimeHistogram: Histogram | null = null;
private chatMessageLengthHistogram: Histogram | null = null;
constructor(config: TelemetryConfig = {}) {
// Parse standard OpenTelemetry environment variables
const otelEndpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
const otelProtocol =
process.env.OTEL_EXPORTER_OTLP_PROTOCOL?.toLowerCase() as
| "http"
| "grpc"
| undefined;
const otelHeaders = this.parseOtelHeaders(
process.env.OTEL_EXPORTER_OTLP_HEADERS
);
const otelMetricInterval = process.env.OTEL_METRIC_EXPORT_INTERVAL
? parseInt(process.env.OTEL_METRIC_EXPORT_INTERVAL)
: undefined;
const otelMetricsExporter =
process.env.OTEL_METRICS_EXPORTER?.toLowerCase();
// Determine if telemetry should be enabled
const isEnabled =
otelMetricsExporter === "otlp" ||
(config.enabled !== false && process.env.TELEMETRY_ENABLED !== "false");
this.config = {
serviceName: config.serviceName || "continue-cli",
serviceVersion: config.serviceVersion || "1.0.0",
otlpEndpoint:
config.otlpEndpoint ||
otelEndpoint ||
"http://localhost:4318/v1/metrics",
otlpHeaders: { ...otelHeaders, ...config.otlpHeaders },
exportInterval: config.exportInterval || otelMetricInterval || 5000,
protocol: config.protocol || otelProtocol || "http",
enabled: isEnabled,
};
}
/**
* Parse OTEL_EXPORTER_OTLP_HEADERS environment variable
* Format: "key1=value1,key2=value2"
*/
private parseOtelHeaders(headersStr?: string): Record<string, string> {
if (!headersStr) return {};
const headers: Record<string, string> = {};
headersStr.split(",").forEach((pair) => {
const [key, value] = pair.split("=");
if (key && value) {
headers[key.trim()] = value.trim();
}
});
return headers;
}
/**
* Initialize OpenTelemetry with OTLP metrics export
*/
public async initialize(): Promise<void> {
if (!this.config.enabled) {
logger.debug("Telemetry disabled");
return;
}
try {
// Dynamic import to work around ESM issues
const { resourceFromAttributes } = await import(
"@opentelemetry/resources"
);
// Create resource with service information
const resource = resourceFromAttributes({
[ATTR_SERVICE_NAME]: this.config.serviceName,
[ATTR_SERVICE_VERSION]: this.config.serviceVersion,
});
// Create OTLP metric exporter based on protocol
let metricExporter;
let endpointUrl = this.config.otlpEndpoint;
if (this.config.protocol === "grpc") {
// For gRPC, ensure we don't have /v1/metrics path
if (endpointUrl.endsWith("/v1/metrics")) {
endpointUrl = endpointUrl.replace("/v1/metrics", "");
}
metricExporter = new OTLPMetricExporterGRPC({
url: endpointUrl,
headers: this.config.otlpHeaders,
});
} else {
// For HTTP, ensure we have the /v1/metrics path
if (!endpointUrl.endsWith("/v1/metrics")) {
endpointUrl = endpointUrl.replace(/\/$/, "") + "/v1/metrics";
}
metricExporter = new OTLPMetricExporter({
url: endpointUrl,
headers: this.config.otlpHeaders,
});
}
// Create metric reader
const metricReader = new PeriodicExportingMetricReader({
exporter: metricExporter,
exportIntervalMillis: this.config.exportInterval,
});
// Create meter provider
this.meterProvider = new MeterProvider({
resource,
readers: [metricReader],
});
// Set global meter provider
metrics.setGlobalMeterProvider(this.meterProvider);
// Get a meter instance
this.meter = metrics.getMeter(
this.config.serviceName,
this.config.serviceVersion
);
// Initialize all instruments once during setup
this.initializeInstruments();
logger.debug(
`Telemetry initialized - Protocol: ${this.config.protocol}, Endpoint: ${endpointUrl}`
);
if (Object.keys(this.config.otlpHeaders).length > 0) {
logger.debug(
`Headers configured: ${Object.keys(this.config.otlpHeaders).join(
", "
)}`
);
}
} catch (error) {
logger.error("Failed to initialize telemetry:", error);
}
}
/**
* Initialize all instruments once during setup to avoid creating new ones on each call
*/
private initializeInstruments(): void {
if (!this.meter) return;
// Command metrics
this.commandCounter = this.meter.createCounter(
"cli_commands_total",
{
description: "Total number of CLI commands executed",
unit: "1",
}
);
this.commandDurationHistogram = this.meter.createHistogram(
"cli_command_duration",
{
description: "Duration of CLI command execution",
unit: "ms",
}
);
// Chat interaction metrics
this.chatInteractionCounter = this.meter.createCounter(
"cli_chat_interactions_total",
{
description: "Total number of chat interactions",
unit: "1",
}
);
this.chatResponseTimeHistogram = this.meter.createHistogram(
"cli_chat_response_time",
{
description: "Time to receive chat response",
unit: "ms",
}
);
this.chatMessageLengthHistogram = this.meter.createHistogram(
"cli_chat_message_length",
{
description: "Length of chat messages",
unit: "characters",
}
);
}
/**
* Create a counter metric
*/
public createCounter(name: string, description?: string, unit?: string) {
if (!this.meter) {
logger.warn("Telemetry not initialized, counter not created");
return null;
}
return this.meter.createCounter(name, {
description: description || `Counter for ${name}`,
unit: unit || "1",
});
}
/**
* Create a histogram metric
*/
public createHistogram(name: string, description?: string, unit?: string) {
if (!this.meter) {
logger.warn("Telemetry not initialized, histogram not created");
return null;
}
return this.meter.createHistogram(name, {
description: description || `Histogram for ${name}`,
unit: unit || "ms",
});
}
/**
* Create a gauge metric
*/
public createGauge(name: string, description?: string, unit?: string) {
if (!this.meter) {
logger.warn("Telemetry not initialized, gauge not created");
return null;
}
return this.meter.createObservableGauge(name, {
description: description || `Gauge for ${name}`,
unit: unit || "1",
});
}
/**
* Send a test counter metric
*/
public sendTestMetric(): void {
if (!this.config.enabled || !this.meter) {
logger.debug("Telemetry not enabled or not initialized");
return;
}
const testCounter = this.createCounter(
"cli_test_counter",
"A test counter to verify OTLP metrics are working",
"1"
);
if (testCounter) {
testCounter.add(1, {
test_attribute: "test_value",
timestamp: new Date().toISOString(),
environment: "test",
});
logger.debug("Test metric sent: cli_test_counter incremented by 1");
}
}
/**
* Record CLI command execution
*/
public recordCommand(
command: string,
duration: number,
success: boolean
): void {
if (!this.config.enabled || !this.meter) return;
const attributes = {
command,
success: success.toString(),
};
// Use pre-created instruments instead of creating new ones
this.commandCounter?.add(1, attributes);
this.commandDurationHistogram?.record(duration, attributes);
}
/**
* Record chat interaction metrics
*/
public recordChatInteraction(
messageLength: number,
responseTime: number
): void {
if (!this.config.enabled || !this.meter) return;
// Use pre-created instruments instead of creating new ones
this.chatInteractionCounter?.add(1);
this.chatResponseTimeHistogram?.record(responseTime);
this.chatMessageLengthHistogram?.record(messageLength);
}
/**
* Get current configuration (for debugging)
*/
public getConfig() {
return { ...this.config };
}
/**
* Cleanup and shutdown telemetry
*/
public async shutdown(): Promise<void> {
if (this.meterProvider) {
try {
await this.meterProvider.shutdown();
logger.debug("Telemetry shutdown completed");
} catch (error) {
logger.error("Error during telemetry shutdown:", error);
}
}
}
}
// Export singleton instance
export const telemetry = new ContinueCLITelemetry();
// Export initialization function for easy setup
export async function initializeTelemetry(
config?: TelemetryConfig
): Promise<void> {
const instance = new ContinueCLITelemetry(config);
await instance.initialize();
// Send test metric on initialization
setTimeout(() => {
instance.sendTestMetric();
}, 1000);
}

View file

@ -0,0 +1,560 @@
import { metrics } from "@opentelemetry/api";
import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http";
import { resourceFromAttributes } from "@opentelemetry/resources";
import {
ConsoleMetricExporter,
MeterProvider,
PeriodicExportingMetricReader,
} from "@opentelemetry/sdk-metrics";
import {
SEMRESATTRS_DEPLOYMENT_ENVIRONMENT,
SEMRESATTRS_OS_TYPE,
SEMRESATTRS_PROCESS_PID,
SEMRESATTRS_SERVICE_NAME,
SEMRESATTRS_SERVICE_VERSION,
} from "@opentelemetry/semantic-conventions";
import os from "os";
import { v4 as uuidv4 } from "uuid";
import logger from "../util/logger.js";
import { getVersion } from "../version.js";
export interface TelemetryConfig {
enabled: boolean;
sessionId: string;
organizationId?: string;
accountUuid?: string;
includeSessionId: boolean;
includeVersion: boolean;
includeAccountUuid: boolean;
}
class TelemetryService {
private meterProvider: MeterProvider | null = null;
private meter: any = null;
private config: TelemetryConfig;
private startTime = Date.now();
private activeStartTime: number | null = null;
private totalActiveTime = 0;
// Metrics
private sessionCounter: any = null;
private linesOfCodeCounter: any = null;
private pullRequestCounter: any = null;
private commitCounter: any = null;
private costCounter: any = null;
private tokenCounter: any = null;
private codeEditDecisionCounter: any = null;
private activeTimeCounter: any = null;
private authAttemptsCounter: any = null;
private fileOperationsCounter: any = null;
private terminalCommandsCounter: any = null;
private mcpConnectionsGauge: any = null;
private startupTimeHistogram: any = null;
private responseTimeHistogram: any = null;
constructor() {
this.config = this.loadConfig();
if (this.config.enabled) {
this.initialize();
}
}
private loadConfig(): TelemetryConfig {
const enabled = process.env.CONTINUE_CLI_ENABLE_TELEMETRY === "1";
const sessionId = uuidv4();
return {
enabled,
sessionId,
organizationId: process.env.ORGANIZATION_ID,
accountUuid: process.env.ACCOUNT_UUID,
includeSessionId: process.env.OTEL_METRICS_INCLUDE_SESSION_ID !== "false",
includeVersion: process.env.OTEL_METRICS_INCLUDE_VERSION === "true",
includeAccountUuid:
process.env.OTEL_METRICS_INCLUDE_ACCOUNT_UUID !== "false",
};
}
private initialize() {
try {
// Create resource
const resource = resourceFromAttributes({
[SEMRESATTRS_SERVICE_NAME]: "continue-cli",
[SEMRESATTRS_SERVICE_VERSION]: getVersion(),
[SEMRESATTRS_DEPLOYMENT_ENVIRONMENT]:
process.env.NODE_ENV || "development",
[SEMRESATTRS_OS_TYPE]: os.type(),
[SEMRESATTRS_PROCESS_PID]: process.pid.toString(),
});
// Configure exporters
const readers: any[] = [];
const metricsExporters = (
process.env.OTEL_METRICS_EXPORTER || "console"
).split(",");
for (const exporterType of metricsExporters) {
switch (exporterType.trim()) {
case "otlp":
readers.push(
new PeriodicExportingMetricReader({
exporter: new OTLPMetricExporter({
url:
process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT ||
`${process.env.OTEL_EXPORTER_OTLP_ENDPOINT}/v1/metrics` ||
"http://localhost:4318/v1/metrics",
headers: this.parseHeaders(
process.env.OTEL_EXPORTER_OTLP_HEADERS || ""
),
}),
exportIntervalMillis: parseInt(
process.env.OTEL_METRIC_EXPORT_INTERVAL || "60000"
),
})
);
break;
case "console":
readers.push(
new PeriodicExportingMetricReader({
exporter: new ConsoleMetricExporter(),
exportIntervalMillis: parseInt(
process.env.OTEL_METRIC_EXPORT_INTERVAL || "60000"
),
})
);
break;
}
}
// Create meter provider
this.meterProvider = new MeterProvider({
resource,
readers,
});
metrics.setGlobalMeterProvider(this.meterProvider);
this.meter = metrics.getMeter("continue-cli", getVersion());
this.initializeMetrics();
logger.debug("Telemetry service initialized", {
sessionId: this.config.sessionId,
exporters: metricsExporters,
});
} catch (error) {
logger.error("Failed to initialize telemetry", error);
}
}
private parseHeaders(headersStr: string): Record<string, string> {
const headers: Record<string, string> = {};
if (!headersStr) return headers;
headersStr.split(",").forEach((header) => {
const [key, value] = header.split("=");
if (key && value) {
headers[key.trim()] = value.trim();
}
});
return headers;
}
private initializeMetrics() {
if (!this.meter) return;
// Core metrics (Claude Code compatible)
this.sessionCounter = this.meter.createCounter(
"continue.cli.session.count",
{
description: "Count of CLI sessions started",
unit: "count",
}
);
this.linesOfCodeCounter = this.meter.createCounter(
"continue.cli.lines_of_code.count",
{
description: "Count of lines of code modified",
unit: "count",
}
);
this.pullRequestCounter = this.meter.createCounter(
"continue.cli.pull_request.count",
{
description: "Number of pull requests created",
unit: "count",
}
);
this.commitCounter = this.meter.createCounter("continue.cli.commit.count", {
description: "Number of git commits created",
unit: "count",
});
this.costCounter = this.meter.createCounter("continue.cli.cost.usage", {
description: "Cost of the Continue CLI session",
unit: "USD",
});
this.tokenCounter = this.meter.createCounter("continue.cli.token.usage", {
description: "Number of tokens used",
unit: "tokens",
});
this.codeEditDecisionCounter = this.meter.createCounter(
"continue.cli.code_edit_tool.decision",
{
description: "Count of code editing tool permission decisions",
unit: "count",
}
);
this.activeTimeCounter = this.meter.createCounter(
"continue.cli.active_time.total",
{
description: "Total active time in seconds",
unit: "s",
}
);
// Additional Continue CLI specific metrics
this.authAttemptsCounter = this.meter.createCounter(
"continue.cli.auth.attempts",
{
description: "Authentication attempts",
unit: "{attempt}",
}
);
this.fileOperationsCounter = this.meter.createCounter(
"continue.cli.tools.file_operations",
{
description: "File operations performed",
unit: "{operation}",
}
);
this.terminalCommandsCounter = this.meter.createCounter(
"continue.cli.tools.terminal_commands",
{
description: "Terminal commands executed",
unit: "{command}",
}
);
this.mcpConnectionsGauge = this.meter.createObservableGauge(
"continue.cli.mcp.connections",
{
description: "Active MCP connections",
unit: "{connection}",
}
);
this.startupTimeHistogram = this.meter.createHistogram(
"continue.cli.startup.time",
{
description: "Time from CLI start to ready state",
unit: "ms",
}
);
this.responseTimeHistogram = this.meter.createHistogram(
"continue.cli.response_time",
{
description: "LLM response time metrics",
unit: "ms",
}
);
}
// Check if telemetry is enabled - this is the single point of checking
private isEnabled(): boolean {
return this.config.enabled && this.meter !== null;
}
private getStandardAttributes(
additionalAttributes: Record<string, string> = {}
) {
const attributes: Record<string, string> = { ...additionalAttributes };
if (this.config.includeSessionId) {
attributes["session.id"] = this.config.sessionId;
}
if (this.config.includeVersion) {
attributes["app.version"] = getVersion();
}
if (this.config.organizationId) {
attributes["organization.id"] = this.config.organizationId;
}
if (this.config.includeAccountUuid && this.config.accountUuid) {
attributes["user.account_uuid"] = this.config.accountUuid;
}
// Detect terminal type
const terminalType = this.detectTerminalType();
if (terminalType) {
attributes["terminal.type"] = terminalType;
}
return attributes;
}
private detectTerminalType(): string | undefined {
if (process.env.TERM_PROGRAM) {
return process.env.TERM_PROGRAM;
}
if (process.env.VSCODE_PID) {
return "vscode";
}
if (process.env.TMUX) {
return "tmux";
}
return undefined;
}
// Public methods for tracking metrics
public recordSessionStart() {
if (!this.isEnabled()) return;
this.sessionCounter.add(1, this.getStandardAttributes());
this.recordStartupTime(Date.now() - this.startTime);
}
public recordLinesOfCodeModified(
type: "added" | "removed",
count: number,
language?: string
) {
if (!this.isEnabled()) return;
const attributes = this.getStandardAttributes({ type });
if (language) {
attributes.language = language;
}
this.linesOfCodeCounter.add(count, attributes);
}
public recordPullRequestCreated() {
if (!this.isEnabled()) return;
this.pullRequestCounter.add(1, this.getStandardAttributes());
}
public recordCommitCreated() {
if (!this.isEnabled()) return;
this.commitCounter.add(1, this.getStandardAttributes());
}
public recordCost(cost: number, model: string) {
if (!this.isEnabled()) return;
this.costCounter.add(cost, this.getStandardAttributes({ model }));
}
public recordTokenUsage(
tokens: number,
type: "input" | "output" | "cacheRead" | "cacheCreation",
model: string
) {
if (!this.isEnabled()) return;
this.tokenCounter.add(tokens, this.getStandardAttributes({ type, model }));
}
public recordCodeEditDecision(
tool: string,
decision: "accept" | "reject",
language?: string
) {
if (!this.isEnabled()) return;
const attributes = this.getStandardAttributes({ tool, decision });
if (language) {
attributes.language = language;
}
this.codeEditDecisionCounter.add(1, attributes);
}
public startActiveTime() {
if (!this.isEnabled()) return;
if (this.activeStartTime === null) {
this.activeStartTime = Date.now();
}
}
public stopActiveTime() {
if (!this.isEnabled()) return;
if (this.activeStartTime !== null) {
this.totalActiveTime += Date.now() - this.activeStartTime;
this.activeStartTime = null;
this.activeTimeCounter.add(
this.totalActiveTime / 1000,
this.getStandardAttributes()
);
}
}
public recordAuthAttempt(
result: "success" | "failure" | "cancelled",
method: "workos" | "token"
) {
if (!this.isEnabled()) return;
this.authAttemptsCounter.add(
1,
this.getStandardAttributes({ result, method })
);
}
public recordMCPConnection(
serverName: string,
status: "connected" | "disconnected" | "error"
) {
if (!this.isEnabled()) return;
const value = status === "connected" ? 1 : 0;
// Note: Observable gauge callback will be implemented when MCP monitoring is added
if (this.mcpConnectionsGauge) {
// This is a placeholder - observable gauges work differently
logger.debug("MCP connection status", { serverName, status, value });
}
}
public recordStartupTime(
timeMs: number,
mode?: "tui" | "headless" | "standard",
coldStart?: boolean
) {
if (!this.isEnabled()) return;
const attributes = this.getStandardAttributes();
if (mode) attributes.mode = mode;
if (coldStart !== undefined) attributes.cold_start = coldStart.toString();
this.startupTimeHistogram.record(timeMs, attributes);
}
public recordResponseTime(
timeMs: number,
model: string,
metricType: "time_to_first_token" | "total_response_time",
hasTools?: boolean
) {
if (!this.isEnabled()) return;
const attributes = this.getStandardAttributes({
model,
metric_type: metricType,
});
if (hasTools !== undefined) attributes.has_tools = hasTools.toString();
this.responseTimeHistogram.record(timeMs, attributes);
}
// Event logging methods (these will be implemented when OTLP logs support is added)
public logUserPrompt(promptLength: number, prompt?: string) {
if (!this.isEnabled()) return;
const attributes = this.getStandardAttributes({
"event.name": "user_prompt",
"event.timestamp": new Date().toISOString(),
prompt_length: promptLength.toString(),
});
if (process.env.OTEL_LOG_USER_PROMPTS === "1" && prompt) {
attributes.prompt = prompt;
}
// TODO: Implement OTLP logs export
logger.debug("User prompt event", attributes);
}
public logToolResult(
toolName: string,
success: boolean,
durationMs: number,
error?: string,
decision?: "accept" | "reject",
source?: string,
toolParameters?: string
) {
if (!this.isEnabled()) return;
const attributes = this.getStandardAttributes({
"event.name": "tool_result",
"event.timestamp": new Date().toISOString(),
tool_name: toolName,
success: success.toString(),
duration_ms: durationMs.toString(),
});
if (error) attributes.error = error;
if (decision) attributes.decision = decision;
if (source) attributes.source = source;
if (toolParameters) attributes.tool_parameters = toolParameters;
// TODO: Implement OTLP logs export
logger.debug("Tool result event", attributes);
}
public logApiRequest(
model: string,
durationMs: number,
success: boolean,
error?: string,
inputTokens?: number,
outputTokens?: number,
costUsd?: number
) {
if (!this.isEnabled()) return;
const attributes = this.getStandardAttributes({
"event.name": "api_request",
"event.timestamp": new Date().toISOString(),
model,
duration_ms: durationMs.toString(),
success: success.toString(),
});
if (error) attributes.error = error;
if (inputTokens) attributes.input_tokens = inputTokens.toString();
if (outputTokens) attributes.output_tokens = outputTokens.toString();
if (costUsd) attributes.cost_usd = costUsd.toString();
// TODO: Implement OTLP logs export
logger.debug("API request event", attributes);
}
public updateOrganization(organizationId: string) {
this.config.organizationId = organizationId;
}
public updateAccountUuid(accountUuid: string) {
this.config.accountUuid = accountUuid;
}
public getSessionId(): string {
return this.config.sessionId;
}
public shutdown() {
this.stopActiveTime();
return this.meterProvider?.shutdown();
}
}
// Export the singleton instance directly
export const telemetryService = new TelemetryService();
export default telemetryService;

154
src/telemetry/utils.ts Normal file
View file

@ -0,0 +1,154 @@
import { diffLines } from "diff";
import path from "path";
/**
* Calculate lines of code added/removed from a file diff
*/
export function calculateLinesOfCodeDiff(
oldContent: string,
newContent: string
): { added: number; removed: number } {
const diff = diffLines(oldContent, newContent);
let added = 0;
let removed = 0;
for (const part of diff) {
if (part.added) {
added += part.count || 0;
} else if (part.removed) {
removed += part.count || 0;
}
}
return { added, removed };
}
/**
* Extract programming language from file path
*/
export function getLanguageFromFilePath(filePath: string): string {
const ext = path.extname(filePath).toLowerCase();
const languageMap: Record<string, string> = {
".js": "JavaScript",
".jsx": "JavaScript",
".ts": "TypeScript",
".tsx": "TypeScript",
".py": "Python",
".java": "Java",
".cpp": "C++",
".c": "C",
".cs": "C#",
".php": "PHP",
".rb": "Ruby",
".go": "Go",
".rs": "Rust",
".swift": "Swift",
".kt": "Kotlin",
".scala": "Scala",
".clj": "Clojure",
".hs": "Haskell",
".ml": "OCaml",
".elm": "Elm",
".dart": "Dart",
".lua": "Lua",
".r": "R",
".m": "Objective-C",
".mm": "Objective-C++",
".sh": "Shell",
".bash": "Bash",
".zsh": "Zsh",
".fish": "Fish",
".ps1": "PowerShell",
".html": "HTML",
".css": "CSS",
".scss": "SCSS",
".sass": "Sass",
".less": "Less",
".vue": "Vue",
".svelte": "Svelte",
".md": "Markdown",
".json": "JSON",
".xml": "XML",
".yaml": "YAML",
".yml": "YAML",
".toml": "TOML",
".ini": "INI",
".cfg": "Config",
".conf": "Config",
".sql": "SQL",
".dockerfile": "Dockerfile",
};
return languageMap[ext] || "unknown";
}
/**
* Extract the first word (command type) from a shell command
*/
export function extractCommandType(command: string): string {
return command.trim().split(/\s+/)[0] || "unknown";
}
/**
* Check if a command is a git commit command
*/
export function isGitCommitCommand(command: string): boolean {
const trimmed = command.trim().toLowerCase();
return trimmed.startsWith("git commit") || trimmed.startsWith("git-commit");
}
/**
* Check if a command is a pull request creation command
*/
export function isPullRequestCommand(command: string): boolean {
const trimmed = command.trim().toLowerCase();
return (
trimmed.includes("gh pr create") ||
(trimmed.includes("git push") && trimmed.includes("pull-request")) ||
trimmed.includes("hub pull-request") ||
trimmed.includes("gitlab mr create")
);
}
/**
* Simple cost calculation based on tokens and model
* This should be updated with actual pricing from model providers
*/
export function calculateTokenCost(
inputTokens: number,
outputTokens: number,
model: string
): number {
// Pricing per 1K tokens (these are approximate and should be updated)
const pricingMap: Record<string, { input: number; output: number }> = {
"gpt-4": { input: 0.03, output: 0.06 },
"gpt-4-turbo": { input: 0.01, output: 0.03 },
"gpt-3.5-turbo": { input: 0.0015, output: 0.002 },
"claude-3-5-sonnet-20241022": { input: 0.003, output: 0.015 },
"claude-3-sonnet": { input: 0.003, output: 0.015 },
"claude-3-haiku": { input: 0.00025, output: 0.00125 },
"claude-3-opus": { input: 0.015, output: 0.075 },
};
// Find pricing for model (case insensitive partial match)
const modelKey = Object.keys(pricingMap).find((key) =>
model.toLowerCase().includes(key.toLowerCase())
);
if (!modelKey) {
// Default pricing if model not found
return (inputTokens * 0.001 + outputTokens * 0.002) / 1000;
}
const pricing = pricingMap[modelKey];
return (inputTokens * pricing.input + outputTokens * pricing.output) / 1000;
}
/**
* Get file type from extension for metrics
*/
export function getFileTypeFromPath(filePath: string): string {
const ext = path.extname(filePath).toLowerCase();
return ext.startsWith(".") ? ext.substring(1) : "unknown";
}

View file

@ -1,5 +1,6 @@
import { parseArgs } from "../args.js";
import { MCPService } from "../mcp.js";
import telemetryService from "../telemetry/telemetryService.js";
import logger from "../util/logger.js";
import { exitTool } from "./exit.js";
import { fetchTool } from "./fetch.js";
@ -113,6 +114,8 @@ export async function executeToolCall(toolCall: {
name: string;
arguments: Record<string, any>;
}): Promise<string> {
const startTime = Date.now();
const args = parseArgs();
let mcpTools: Tool[] = [];
@ -149,6 +152,13 @@ export async function executeToolCall(toolCall: {
const tool = allTools.find((t) => t.name === toolCall.name);
if (!tool) {
const duration = Date.now() - startTime;
telemetryService.logToolResult(
toolCall.name,
false,
duration,
`Tool "${toolCall.name}" not found`
);
return `Error: Tool "${toolCall.name}" not found`;
}
@ -158,7 +168,10 @@ export async function executeToolCall(toolCall: {
(toolCall.arguments[paramName] === undefined ||
toolCall.arguments[paramName] === null)
) {
return `Error: Required parameter "${paramName}" missing for tool "${toolCall.name}"`;
const duration = Date.now() - startTime;
const error = `Required parameter "${paramName}" missing for tool "${toolCall.name}"`;
telemetryService.logToolResult(toolCall.name, false, duration, error);
return `Error: ${error}`;
}
}
@ -167,15 +180,40 @@ export async function executeToolCall(toolCall: {
toolName: toolCall.name,
arguments: toolCall.arguments,
});
const result = await tool.run(toolCall.arguments);
const duration = Date.now() - startTime;
telemetryService.logToolResult(
toolCall.name,
true,
duration,
undefined, // no error
undefined, // no decision
undefined, // no source
JSON.stringify(toolCall.arguments)
);
logger.debug("Tool execution completed", {
toolName: toolCall.name,
resultLength: result?.length || 0,
});
return result;
} catch (error) {
return `Error executing tool "${toolCall.name}": ${
error instanceof Error ? error.message : String(error)
}`;
const duration = Date.now() - startTime;
const errorMessage = error instanceof Error ? error.message : String(error);
telemetryService.logToolResult(
toolCall.name,
false,
duration,
errorMessage,
undefined, // no decision
undefined, // no source
JSON.stringify(toolCall.arguments)
);
return `Error executing tool "${toolCall.name}": ${errorMessage}`;
}
}

View file

@ -1,4 +1,9 @@
import { exec } from "child_process";
import telemetryService from "../telemetry/telemetryService.js";
import {
isGitCommitCommand,
isPullRequestCommand,
} from "../telemetry/utils.js";
import { Tool } from "./types.js";
export const runTerminalCommandTool: Tool = {
@ -16,10 +21,20 @@ export const runTerminalCommandTool: Tool = {
run: async ({ command }: { command: string }): Promise<string> => {
return new Promise((resolve, reject) => {
exec(command, (error, stdout, stderr) => {
const exitCode = error?.code || 0;
if (error) {
reject(`Error: ${error.message}`);
return;
}
// Track specific git operations
if (isGitCommitCommand(command)) {
telemetryService.recordCommitCreated();
} else if (isPullRequestCommand(command)) {
telemetryService.recordPullRequestCreated();
}
if (stderr) {
resolve(`Stderr: ${stderr}`);
return;

View file

@ -1,9 +1,18 @@
import { createTwoFilesPatch } from "diff";
import * as fs from "fs";
import * as path from "path";
import { createTwoFilesPatch } from "diff";
import telemetryService from "../telemetry/telemetryService.js";
import {
calculateLinesOfCodeDiff,
getLanguageFromFilePath,
} from "../telemetry/utils.js";
import { Tool } from "./types.js";
function generateDiff(oldContent: string, newContent: string, filePath: string): string {
function generateDiff(
oldContent: string,
newContent: string,
filePath: string
): string {
return createTwoFilesPatch(
filePath,
filePath,
@ -40,23 +49,56 @@ export const writeFileTool: Tool = {
}
// Read existing file content if it exists
let oldContent = '';
let oldContent = "";
if (fs.existsSync(args.filepath)) {
oldContent = fs.readFileSync(args.filepath, "utf-8");
}
// Write new content
fs.writeFileSync(args.filepath, args.content, "utf-8");
// Generate diff if file existed before
// Track lines of code changes if file existed before
if (oldContent) {
const { added, removed } = calculateLinesOfCodeDiff(
oldContent,
args.content
);
const language = getLanguageFromFilePath(args.filepath);
if (added > 0) {
telemetryService.recordLinesOfCodeModified("added", added, language);
}
if (removed > 0) {
telemetryService.recordLinesOfCodeModified(
"removed",
removed,
language
);
}
const diff = generateDiff(oldContent, args.content, args.filepath);
// Record file operation
return `Successfully wrote to file: ${args.filepath}\n\nDiff:\n${diff}`;
} else {
// New file creation - count all lines as added
const lineCount = args.content.split("\n").length;
const language = getLanguageFromFilePath(args.filepath);
telemetryService.recordLinesOfCodeModified(
"added",
lineCount,
language
);
return `Successfully created file: ${args.filepath}`;
}
} catch (error) {
return `Error writing to file: ${error instanceof Error ? error.message : String(error)}`;
const errorMessage =
error instanceof Error ? error.message : String(error);
return `Error writing to file: ${errorMessage}`;
}
},
};
};

View file

@ -11,6 +11,7 @@ import {
streamChatResponse,
} from "../../streamChatResponse.js";
import { constructSystemMessage } from "../../systemMessage.js";
import telemetryService from "../../telemetry/telemetryService.js";
import { getToolDisplayName } from "../../tools.js";
import { formatError } from "../../util/formatError.js";
import logger from "../../util/logger.js";
@ -198,6 +199,12 @@ export function useChat({
}
}
// Start active time tracking for telemetry
telemetryService.startActiveTime();
// Track user prompt
telemetryService.logUserPrompt(message.length, message);
// Add user message to history and display
let messageContent = message;
@ -373,6 +380,9 @@ export function useChat({
},
]);
} finally {
// Stop active time tracking
telemetryService.stopActiveTime();
setAbortController(null);
setIsWaitingForResponse(false);
setResponseStartTime(null);