diff --git a/package.json b/package.json index 24b0dc71ea..d598609517 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,7 @@ "syntaxes" ], "engines": { - "vscode": "^1.88.0" + "vscode": "^1.109.0" }, "categories": [ "Other", @@ -115,6 +115,63 @@ } } }, + "languageModelTools": [ + { + "name": "cmake_build", + "displayName": "CMake: Build", + "canBeReferencedInPrompt": true, + "toolReferenceName": "cmake:build", + "icon": "$(cmake-tools-build)", + "userDescription": "Build the CMake project with the active build preset", + "modelDescription": "Builds the CMake project using the currently active build preset. Use this tool when the user asks to build, compile, or make the project. The tool, if asked, can optionally build a specific target and can clean before building. This tool requires an active CMake project with a configured preset. Returns the build result including exit code and status.", + "inputSchema": { + "type": "object", + "properties": { + "target": { + "type": "string", + "description": "The specific build target to compile. If not provided, builds the default target. Examples: 'all', 'myapp', 'tests'" + }, + "clean": { + "type": "boolean", + "description": "Whether to clean before building. Defaults to false.", + "default": false + } + } + } + }, + { + "name": "cmake_configure", + "displayName": "CMake: Configure", + "canBeReferencedInPrompt": true, + "toolReferenceName": "cmake:configure", + "icon": "$(cmake-tools-configure)", + "userDescription": "Configure the CMake project with the active configure preset", + "modelDescription": "Configures the CMake project using the currently active configure preset. Use this tool when the user asks to configure, reconfigure, or set up the CMake project. Use this tool if you, the agent, add, remove, or rename source files. The tool, if asked, can delete the CMake cache before configuring for a clean reconfigure. This tool requires an active CMake project and preset. Returns the configuration result including exit code and preset used.", + "inputSchema": { + "type": "object", + "properties": { + "cleanFirst": { + "type": "boolean", + "description": "Whether to delete the CMake cache before configuring. Defaults to false. Set to true for a clean reconfigure.", + "default": false + } + } + } + }, + { + "name": "cmake_get_errors", + "displayName": "CMake: Get Errors", + "canBeReferencedInPrompt": true, + "toolReferenceName": "cmake:get_errors", + "icon": "$(warning)", + "userDescription": "Get CMake-specific diagnostics (configure, build, and preset errors)", + "modelDescription": "Retrieves diagnostics from CMake-specific sources including configure errors, build/compilation errors, and preset errors. Use this tool when the user asks about CMake errors, build failures, or compilation issues. This tool specifically excludes IntelliSense and clangd diagnostics to focus only on CMake-related problems. Returns a formatted list of errors with file locations, line numbers, and messages grouped by type. Important: This is more focused than the general get_errors tool because it only shows CMake-specific diagnostics.", + "inputSchema": { + "type": "object", + "properties": {} + } + } + ], "languages": [ { "id": "cmake", @@ -3980,7 +4037,7 @@ "@types/rimraf": "^3.0.0", "@types/sinon": "~9.0.10", "@types/tmp": "^0.2.0", - "@types/vscode": "1.88.0", + "@types/vscode": "1.109.0", "@types/which": "~2.0.0", "@types/xml2js": "^0.4.8", "@types/uuid": "~8.3.3", diff --git a/src/copilot/index.ts b/src/copilot/index.ts new file mode 100644 index 0000000000..a3e9d953e6 --- /dev/null +++ b/src/copilot/index.ts @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See LICENSE in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as vscode from 'vscode'; +import { ExtensionManager } from '@cmt/extension'; +import { CMakeBuildTool, CMakeConfigureTool, CMakeGetErrorsTool } from './tools'; + +/** + * Registers CMake Copilot tools for use with VS Code's Language Model API + * + * @param context Extension context for managing disposables + * @param extensionManager The CMake Tools extension manager instance + */ +export function registerCopilotTools( + context: vscode.ExtensionContext, + extensionManager: ExtensionManager +): void { + // Register the build tool + context.subscriptions.push( + vscode.lm.registerTool('cmake_build', new CMakeBuildTool(extensionManager)) + ); + + // Register the configure tool + context.subscriptions.push( + vscode.lm.registerTool('cmake_configure', new CMakeConfigureTool(extensionManager)) + ); + + // Register the get errors tool + context.subscriptions.push( + vscode.lm.registerTool('cmake_get_errors', new CMakeGetErrorsTool()) + ); +} diff --git a/src/copilot/tools.ts b/src/copilot/tools.ts new file mode 100644 index 0000000000..2e987fed69 --- /dev/null +++ b/src/copilot/tools.ts @@ -0,0 +1,245 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See LICENSE in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as vscode from 'vscode'; +import { IBuildParameters, IConfigureParameters, IGetErrorsParameters } from './types'; +import { ExtensionManager } from '@cmt/extension'; +import { collections } from '@cmt/diagnostics/collections'; + +/** + * Language Model Tool for building CMake projects + */ +export class CMakeBuildTool implements vscode.LanguageModelTool { + constructor(private readonly extensionManager: ExtensionManager) {} + + async prepareInvocation( + options: vscode.LanguageModelToolInvocationPrepareOptions, + _token: vscode.CancellationToken + ): Promise { + const target = options.input.target; + const clean = options.input.clean ?? false; + + let targetDesc = target ? `target '${target}'` : 'default target'; + if (clean) { + targetDesc = `clean and build ${targetDesc}`; + } else { + targetDesc = `build ${targetDesc}`; + } + + const confirmationMessages = { + title: 'Build CMake Project', + message: new vscode.MarkdownString( + `Build the CMake project: ${targetDesc}?` + ) + }; + + return { + invocationMessage: clean ? 'Cleaning and building CMake project...' : 'Building CMake project...', + confirmationMessages + }; + } + + async invoke( + options: vscode.LanguageModelToolInvocationOptions, + _token: vscode.CancellationToken + ): Promise { + const params = options.input; + const targets = params.target ? [params.target] : undefined; + + try { + // If clean is requested, clean first + if (params.clean) { + await this.extensionManager.clean(); + } + + // Perform the build + const result = await this.extensionManager.build(undefined, undefined, undefined, undefined, undefined); + + if (result === 0) { + const targetDesc = params.target ? `target '${params.target}'` : 'default target'; + const message = `CMake build completed successfully for ${targetDesc}.`; + return new vscode.LanguageModelToolResult([ + new vscode.LanguageModelTextPart(message) + ]); + } else { + const errorMsg = `CMake build failed with exit code ${result}.`; + throw new Error(errorMsg + ' Use the cmake_get_errors tool to see the compilation errors, then help the user fix them.'); + } + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + throw new Error(`CMake build failed: ${errorMessage}. Use the cmake_get_errors tool to see detailed diagnostics.`); + } + } +} + +/** + * Language Model Tool for configuring CMake projects + */ +export class CMakeConfigureTool implements vscode.LanguageModelTool { + constructor(private readonly extensionManager: ExtensionManager) {} + + async prepareInvocation( + options: vscode.LanguageModelToolInvocationPrepareOptions, + _token: vscode.CancellationToken + ): Promise { + const cleanFirst = options.input.cleanFirst ?? false; + const presetName = this.extensionManager.activeConfigurePresetName() || 'default'; + + const action = cleanFirst ? 'Clean and reconfigure' : 'Configure'; + const confirmationMessages = { + title: `${action} CMake Project`, + message: new vscode.MarkdownString( + `${action} the CMake project with preset '${presetName}'?` + ) + }; + + return { + invocationMessage: cleanFirst ? 'Cleaning and reconfiguring CMake project...' : 'Configuring CMake project...', + confirmationMessages + }; + } + + async invoke( + options: vscode.LanguageModelToolInvocationOptions, + _token: vscode.CancellationToken + ): Promise { + const params = options.input; + const presetName = this.extensionManager.activeConfigurePresetName() || 'default'; + + try { + let result: number; + if (params.cleanFirst) { + result = await this.extensionManager.cleanConfigure(); + } else { + result = await this.extensionManager.configure(); + } + + if (result === 0) { + const action = params.cleanFirst ? 'Clean reconfiguration' : 'Configuration'; + const message = `${action} completed successfully using preset '${presetName}'.`; + return new vscode.LanguageModelToolResult([ + new vscode.LanguageModelTextPart(message) + ]); + } else { + const errorMsg = `CMake configuration failed with exit code ${result}.`; + throw new Error(errorMsg + ' Use the cmake_get_errors tool to see the configuration errors, then help the user fix the CMakeLists.txt or preset issues.'); + } + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + throw new Error(`CMake configuration failed: ${errorMessage}. Use the cmake_get_errors tool to see detailed diagnostics.`); + } + } +} + +/** + * Language Model Tool for retrieving CMake-specific errors + */ +export class CMakeGetErrorsTool implements vscode.LanguageModelTool { + async prepareInvocation( + _options: vscode.LanguageModelToolInvocationPrepareOptions, + _token: vscode.CancellationToken + ): Promise { + return { + invocationMessage: 'Reading CMake diagnostics...', + confirmationMessages: { + title: 'Get CMake Errors', + message: new vscode.MarkdownString('Retrieve CMake-specific diagnostics (configure, build, and preset errors)?') + } + }; + } + + async invoke( + _options: vscode.LanguageModelToolInvocationOptions, + _token: vscode.CancellationToken + ): Promise { + const workspaceFolders = vscode.workspace.workspaceFolders; + const workspaceRoot = workspaceFolders?.[0]?.uri.fsPath || ''; + + // Collect diagnostics from all CMake-specific collections + const diagnosticGroups = [ + { name: 'CMake Configure', collection: collections.cmake }, + { name: 'CMake Build', collection: collections.build }, + { name: 'CMake Presets', collection: collections.presets } + ]; + + let totalErrors = 0; + let totalWarnings = 0; + let totalInfo = 0; + const errorLines: string[] = []; + + for (const group of diagnosticGroups) { + const diagnostics: [vscode.Uri, readonly vscode.Diagnostic[]][] = []; + group.collection.forEach((uri, diags) => { + diagnostics.push([uri, diags]); + }); + + if (diagnostics.length === 0) { + continue; + } + + const groupErrors: string[] = []; + for (const [uri, diags] of diagnostics) { + for (const diag of diags) { + // Count by severity + switch (diag.severity) { + case vscode.DiagnosticSeverity.Error: + totalErrors++; + break; + case vscode.DiagnosticSeverity.Warning: + totalWarnings++; + break; + case vscode.DiagnosticSeverity.Information: + case vscode.DiagnosticSeverity.Hint: + totalInfo++; + break; + } + + // Format the diagnostic + const severityLabel = this.getSeverityLabel(diag.severity); + const relativePath = workspaceRoot ? uri.fsPath.replace(workspaceRoot, '.') : uri.fsPath; + const location = `${relativePath}:${diag.range.start.line + 1}:${diag.range.start.character + 1}`; + const source = diag.source ? `[${diag.source}] ` : ''; + const code = diag.code ? `(${diag.code}) ` : ''; + + groupErrors.push(`${severityLabel}: ${location}: ${source}${code}${diag.message}`); + } + } + + if (groupErrors.length > 0) { + errorLines.push(`\n## ${group.name} Errors (${groupErrors.length})`); + errorLines.push(...groupErrors); + } + } + + // Build summary + const summary = `Found ${totalErrors} error(s), ${totalWarnings} warning(s), ${totalInfo} info message(s) in CMake diagnostics.`; + + if (errorLines.length === 0) { + return new vscode.LanguageModelToolResult([ + new vscode.LanguageModelTextPart('No CMake errors found. The project is clean.') + ]); + } + + const fullReport = [summary, ...errorLines].join('\n'); + return new vscode.LanguageModelToolResult([ + new vscode.LanguageModelTextPart(fullReport) + ]); + } + + private getSeverityLabel(severity: vscode.DiagnosticSeverity): string { + switch (severity) { + case vscode.DiagnosticSeverity.Error: + return 'ERROR'; + case vscode.DiagnosticSeverity.Warning: + return 'WARNING'; + case vscode.DiagnosticSeverity.Information: + return 'INFO'; + case vscode.DiagnosticSeverity.Hint: + return 'HINT'; + default: + return 'UNKNOWN'; + } + } +} diff --git a/src/copilot/types.ts b/src/copilot/types.ts new file mode 100644 index 0000000000..ddf48df723 --- /dev/null +++ b/src/copilot/types.ts @@ -0,0 +1,38 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See LICENSE in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/** + * Input parameters for the cmake_build tool + */ +export interface IBuildParameters { + /** + * The specific build target to compile. If not provided, builds the default target. + * Examples: "all", "myapp", "tests" + */ + target?: string; + + /** + * Whether to clean before building. Defaults to false. + */ + clean?: boolean; +} + +/** + * Input parameters for the cmake_configure tool + */ +export interface IConfigureParameters { + /** + * Whether to delete the CMake cache before configuring. Defaults to false. + * Set to true for a clean reconfigure. + */ + cleanFirst?: boolean; +} + +/** + * Input parameters for the cmake_get_errors tool + */ +export interface IGetErrorsParameters { + // No parameters needed - returns all CMake-specific diagnostics +} diff --git a/src/extension.ts b/src/extension.ts index eb7546bb3f..80a0272c04 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -2661,6 +2661,14 @@ export async function activate(context: vscode.ExtensionContext): Promise; constructor() { @@ -86,6 +89,9 @@ export class SmokeTestExtensionContext implements vscode.ExtensionContext { get extensionMode(): vscode.ExtensionMode { throw new Error(notImplementedErr); } + get languageModelAccessInformation(): vscode.LanguageModelAccessInformation { + throw new Error(notImplementedErr); + } extension: vscode.Extension; constructor(public readonly extensionPath: string) {