diff --git a/spec/otlp-metrics.md b/spec/otlp-metrics.md index 24b51651c..cdacd8ef8 100644 --- a/spec/otlp-metrics.md +++ b/spec/otlp-metrics.md @@ -51,7 +51,7 @@ All metrics and events share these standard attributes: ## Core Metrics -### `continue.cli.session.count` +### ✅ `continue.cli.session.count` **Type:** Counter **Unit:** `count` @@ -65,7 +65,7 @@ All metrics and events share these standard attributes: --- -### `continue.cli.lines_of_code.count` +### ✅ `continue.cli.lines_of_code.count` **Type:** Counter **Unit:** `count` @@ -80,7 +80,7 @@ All metrics and events share these standard attributes: --- -### `continue.cli.pull_request.count` +### ✅ `continue.cli.pull_request.count` **Type:** Counter **Unit:** `count` @@ -94,7 +94,7 @@ All metrics and events share these standard attributes: --- -### `continue.cli.commit.count` +### ✅ `continue.cli.commit.count` **Type:** Counter **Unit:** `count` @@ -108,7 +108,7 @@ All metrics and events share these standard attributes: --- -### `continue.cli.cost.usage` +### ✅ `continue.cli.cost.usage` **Type:** Counter **Unit:** `USD` @@ -123,7 +123,7 @@ All metrics and events share these standard attributes: --- -### `continue.cli.token.usage` +### ✅ `continue.cli.token.usage` **Type:** Counter **Unit:** `tokens` @@ -139,7 +139,7 @@ All metrics and events share these standard attributes: --- -### `continue.cli.code_edit_tool.decision` +### ❌ `continue.cli.code_edit_tool.decision` **Type:** Counter **Unit:** `count` @@ -156,7 +156,7 @@ All metrics and events share these standard attributes: --- -### `continue.cli.active_time.total` +### ✅ `continue.cli.active_time.total` **Type:** Counter **Unit:** `s` @@ -170,7 +170,7 @@ All metrics and events share these standard attributes: ## Core Events -### User Prompt Event +### ✅ User Prompt Event **Event Name:** `continue.cli.user_prompt` @@ -186,7 +186,7 @@ All metrics and events share these standard attributes: --- -### Tool Result Event +### ✅ Tool Result Event **Event Name:** `continue.cli.tool_result` @@ -207,7 +207,7 @@ All metrics and events share these standard attributes: --- -### API Request Event +### ✅ API Request Event **Event Name:** `continue.cli.api_request` @@ -232,7 +232,7 @@ These metrics are unique to Continue CLI and provide additional insights without ### Authentication Metrics -#### `continue.cli.auth.attempts` +#### ✅ `continue.cli.auth.attempts` **Type:** Counter **Unit:** `{attempt}` @@ -248,22 +248,7 @@ These metrics are unique to Continue CLI and provide additional insights without ### Tool-Specific Metrics -#### `continue.cli.tools.file_operations` - -**Type:** Counter -**Unit:** `{operation}` -**Description:** File operations performed (more granular than lines_of_code.count) - -**Labels:** - -- All [standard attributes](#standard-attributes) -- `operation`: `read` | `write` | `list` | `search` -- `file_type`: File extension or `directory` -- `result`: `success` | `error` - -**Implementation:** Track in individual tool files (`src/tools/readFile.ts`, etc.) - -#### `continue.cli.tools.terminal_commands` +#### ✅ `continue.cli.tools.terminal_commands` **Type:** Counter **Unit:** `{command}` @@ -280,7 +265,7 @@ These metrics are unique to Continue CLI and provide additional insights without ### MCP Integration Metrics -#### `continue.cli.mcp.connections` +#### ❌ `continue.cli.mcp.connections` **Type:** Gauge **Unit:** `{connection}` @@ -296,7 +281,7 @@ These metrics are unique to Continue CLI and provide additional insights without ### Performance Metrics -#### `continue.cli.startup.time` +#### ❌ `continue.cli.startup.time` **Type:** Histogram **Unit:** `ms` @@ -310,7 +295,7 @@ These metrics are unique to Continue CLI and provide additional insights without **Implementation:** Track in `src/index.ts` and `src/commands/chat.ts` -#### `continue.cli.response_time` +#### ✅ `continue.cli.response_time` **Type:** Histogram **Unit:** `ms` @@ -357,3 +342,18 @@ All metrics should include these resource attributes: 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 diff --git a/src/commands/chat.ts b/src/commands/chat.ts index 6cf14d056..0f8549f1b 100644 --- a/src/commands/chat.ts +++ b/src/commands/chat.ts @@ -9,6 +9,7 @@ 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.js"; import { startTUIChat } from "../ui/index.js"; import { safeStdout } from "../util/consoleOverride.js"; import { formatError } from "../util/formatError.js"; @@ -43,6 +44,13 @@ async function initializeChat(options: ChatOptions) { authConfig, options.headless ?? false ); + + // Update telemetry with organization info + if (finalAuthConfig.selectedOrganization?.id) { + telemetryService.updateOrganization( + finalAuthConfig.selectedOrganization.id + ); + } } return { @@ -58,8 +66,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 +135,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 +174,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(); } } diff --git a/src/index.ts b/src/index.ts index c40db2e6f..0a9505347 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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 }); diff --git a/src/streamChatResponse.ts b/src/streamChatResponse.ts index f16d9e0ad..132e7a173 100644 --- a/src/streamChatResponse.ts +++ b/src/streamChatResponse.ts @@ -10,6 +10,8 @@ import type { } from "openai/resources.mjs"; import { parseArgs } from "./args.js"; import { MCPService } from "./mcp.js"; +import { telemetryService } from "./telemetry.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(); + 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 }; diff --git a/src/tools/index.ts b/src/tools/index.ts index b4990df2a..4edb4673c 100644 --- a/src/tools/index.ts +++ b/src/tools/index.ts @@ -1,5 +1,6 @@ import { parseArgs } from "../args.js"; import { MCPService } from "../mcp.js"; +import { telemetryService } from "../telemetry.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; }): Promise { + 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}`; } } diff --git a/src/tools/runTerminalCommand.ts b/src/tools/runTerminalCommand.ts index 2462a0207..0116a7549 100644 --- a/src/tools/runTerminalCommand.ts +++ b/src/tools/runTerminalCommand.ts @@ -1,4 +1,6 @@ import { exec } from "child_process"; +import { telemetryService } from "../telemetry.js"; +import { extractCommandType, isGitCommitCommand, isPullRequestCommand } from "../telemetry/utils.js"; import { Tool } from "./types.js"; export const runTerminalCommandTool: Tool = { @@ -14,12 +16,29 @@ export const runTerminalCommandTool: Tool = { }, readonly: false, run: async ({ command }: { command: string }): Promise => { + const commandType = extractCommandType(command); + return new Promise((resolve, reject) => { exec(command, (error, stdout, stderr) => { + const exitCode = error?.code || 0; + if (error) { + // Record failed terminal command + telemetryService.recordTerminalCommand(commandType, 'error', exitCode); reject(`Error: ${error.message}`); return; } + + // Record successful terminal command + telemetryService.recordTerminalCommand(commandType, 'success', exitCode); + + // Track specific git operations + if (isGitCommitCommand(command)) { + telemetryService.recordCommitCreated(); + } else if (isPullRequestCommand(command)) { + telemetryService.recordPullRequestCreated(); + } + if (stderr) { resolve(`Stderr: ${stderr}`); return; @@ -28,4 +47,4 @@ export const runTerminalCommandTool: Tool = { }); }); }, -}; +}; \ No newline at end of file diff --git a/src/tools/writeFile.ts b/src/tools/writeFile.ts index f432d5e79..f3a17f0c7 100644 --- a/src/tools/writeFile.ts +++ b/src/tools/writeFile.ts @@ -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.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,75 @@ 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 + telemetryService.recordFileOperation( + "write", + "success", + path.extname(args.filepath).substring(1) || "unknown" + ); + 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 + ); + + // Record file operation + telemetryService.recordFileOperation( + "write", + "success", + path.extname(args.filepath).substring(1) || "unknown" + ); + 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); + + // Record failed file operation + telemetryService.recordFileOperation( + "write", + "error", + path.extname(args.filepath).substring(1) || "unknown" + ); + + return `Error writing to file: ${errorMessage}`; } }, -}; \ No newline at end of file +}; diff --git a/src/ui/hooks/useChat.ts b/src/ui/hooks/useChat.ts index 20f45a7ed..57dd6dbc4 100644 --- a/src/ui/hooks/useChat.ts +++ b/src/ui/hooks/useChat.ts @@ -11,6 +11,7 @@ import { streamChatResponse, } from "../../streamChatResponse.js"; import { constructSystemMessage } from "../../systemMessage.js"; +import { telemetryService } from "../../telemetry.js"; import { getToolDisplayName } from "../../tools.js"; import { formatError } from "../../util/formatError.js"; import logger from "../../util/logger.js"; @@ -198,6 +199,9 @@ export function useChat({ } } + // Track user prompt + telemetryService.logUserPrompt(message.length, message); + // Add user message to history and display let messageContent = message;