Skip to content

Commit ad0a86a

Browse files
author
Brad Phelan
committed
Initial commit for cmake:build cmake:configure cmake:get_errors
1 parent ca28e03 commit ad0a86a

6 files changed

Lines changed: 390 additions & 2 deletions

File tree

package.json

Lines changed: 59 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
"syntaxes"
2323
],
2424
"engines": {
25-
"vscode": "^1.88.0"
25+
"vscode": "^1.109.0"
2626
},
2727
"categories": [
2828
"Other",
@@ -115,6 +115,63 @@
115115
}
116116
}
117117
},
118+
"languageModelTools": [
119+
{
120+
"name": "cmake_build",
121+
"displayName": "CMake: Build",
122+
"canBeReferencedInPrompt": true,
123+
"toolReferenceName": "cmake:build",
124+
"icon": "$(cmake-tools-build)",
125+
"userDescription": "Build the CMake project with the active build preset",
126+
"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.",
127+
"inputSchema": {
128+
"type": "object",
129+
"properties": {
130+
"target": {
131+
"type": "string",
132+
"description": "The specific build target to compile. If not provided, builds the default target. Examples: 'all', 'myapp', 'tests'"
133+
},
134+
"clean": {
135+
"type": "boolean",
136+
"description": "Whether to clean before building. Defaults to false.",
137+
"default": false
138+
}
139+
}
140+
}
141+
},
142+
{
143+
"name": "cmake_configure",
144+
"displayName": "CMake: Configure",
145+
"canBeReferencedInPrompt": true,
146+
"toolReferenceName": "cmake:configure",
147+
"icon": "$(cmake-tools-configure)",
148+
"userDescription": "Configure the CMake project with the active configure preset",
149+
"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.",
150+
"inputSchema": {
151+
"type": "object",
152+
"properties": {
153+
"cleanFirst": {
154+
"type": "boolean",
155+
"description": "Whether to delete the CMake cache before configuring. Defaults to false. Set to true for a clean reconfigure.",
156+
"default": false
157+
}
158+
}
159+
}
160+
},
161+
{
162+
"name": "cmake_get_errors",
163+
"displayName": "CMake: Get Errors",
164+
"canBeReferencedInPrompt": true,
165+
"toolReferenceName": "cmake:get_errors",
166+
"icon": "$(warning)",
167+
"userDescription": "Get CMake-specific diagnostics (configure, build, and preset errors)",
168+
"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.",
169+
"inputSchema": {
170+
"type": "object",
171+
"properties": {}
172+
}
173+
}
174+
],
118175
"languages": [
119176
{
120177
"id": "cmake",
@@ -3980,7 +4037,7 @@
39804037
"@types/rimraf": "^3.0.0",
39814038
"@types/sinon": "~9.0.10",
39824039
"@types/tmp": "^0.2.0",
3983-
"@types/vscode": "1.88.0",
4040+
"@types/vscode": "1.109.0",
39844041
"@types/which": "~2.0.0",
39854042
"@types/xml2js": "^0.4.8",
39864043
"@types/uuid": "~8.3.3",

src/copilot/index.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/*---------------------------------------------------------------------------------------------
2+
* Copyright (c) Microsoft Corporation. All rights reserved.
3+
* Licensed under the MIT License. See LICENSE in the project root for license information.
4+
*--------------------------------------------------------------------------------------------*/
5+
6+
import * as vscode from 'vscode';
7+
import { ExtensionManager } from '@cmt/extension';
8+
import { CMakeBuildTool, CMakeConfigureTool, CMakeGetErrorsTool } from './tools';
9+
10+
/**
11+
* Registers CMake Copilot tools for use with VS Code's Language Model API
12+
*
13+
* @param context Extension context for managing disposables
14+
* @param extensionManager The CMake Tools extension manager instance
15+
*/
16+
export function registerCopilotTools(
17+
context: vscode.ExtensionContext,
18+
extensionManager: ExtensionManager
19+
): void {
20+
// Register the build tool
21+
context.subscriptions.push(
22+
vscode.lm.registerTool('cmake_build', new CMakeBuildTool(extensionManager))
23+
);
24+
25+
// Register the configure tool
26+
context.subscriptions.push(
27+
vscode.lm.registerTool('cmake_configure', new CMakeConfigureTool(extensionManager))
28+
);
29+
30+
// Register the get errors tool
31+
context.subscriptions.push(
32+
vscode.lm.registerTool('cmake_get_errors', new CMakeGetErrorsTool())
33+
);
34+
}

src/copilot/tools.ts

Lines changed: 245 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,245 @@
1+
/*---------------------------------------------------------------------------------------------
2+
* Copyright (c) Microsoft Corporation. All rights reserved.
3+
* Licensed under the MIT License. See LICENSE in the project root for license information.
4+
*--------------------------------------------------------------------------------------------*/
5+
6+
import * as vscode from 'vscode';
7+
import { IBuildParameters, IConfigureParameters, IGetErrorsParameters } from './types';
8+
import { ExtensionManager } from '@cmt/extension';
9+
import { collections } from '@cmt/diagnostics/collections';
10+
11+
/**
12+
* Language Model Tool for building CMake projects
13+
*/
14+
export class CMakeBuildTool implements vscode.LanguageModelTool<IBuildParameters> {
15+
constructor(private readonly extensionManager: ExtensionManager) {}
16+
17+
async prepareInvocation(
18+
options: vscode.LanguageModelToolInvocationPrepareOptions<IBuildParameters>,
19+
_token: vscode.CancellationToken
20+
): Promise<vscode.PreparedToolInvocation> {
21+
const target = options.input.target;
22+
const clean = options.input.clean ?? false;
23+
24+
let targetDesc = target ? `target '${target}'` : 'default target';
25+
if (clean) {
26+
targetDesc = `clean and build ${targetDesc}`;
27+
} else {
28+
targetDesc = `build ${targetDesc}`;
29+
}
30+
31+
const confirmationMessages = {
32+
title: 'Build CMake Project',
33+
message: new vscode.MarkdownString(
34+
`Build the CMake project: ${targetDesc}?`
35+
)
36+
};
37+
38+
return {
39+
invocationMessage: clean ? 'Cleaning and building CMake project...' : 'Building CMake project...',
40+
confirmationMessages
41+
};
42+
}
43+
44+
async invoke(
45+
options: vscode.LanguageModelToolInvocationOptions<IBuildParameters>,
46+
_token: vscode.CancellationToken
47+
): Promise<vscode.LanguageModelToolResult> {
48+
const params = options.input;
49+
const targets = params.target ? [params.target] : undefined;
50+
51+
try {
52+
// If clean is requested, clean first
53+
if (params.clean) {
54+
await this.extensionManager.clean();
55+
}
56+
57+
// Perform the build
58+
const result = await this.extensionManager.build(undefined, undefined, undefined, undefined, undefined);
59+
60+
if (result === 0) {
61+
const targetDesc = params.target ? `target '${params.target}'` : 'default target';
62+
const message = `CMake build completed successfully for ${targetDesc}.`;
63+
return new vscode.LanguageModelToolResult([
64+
new vscode.LanguageModelTextPart(message)
65+
]);
66+
} else {
67+
const errorMsg = `CMake build failed with exit code ${result}.`;
68+
throw new Error(errorMsg + ' Use the cmake_get_errors tool to see the compilation errors, then help the user fix them.');
69+
}
70+
} catch (error) {
71+
const errorMessage = error instanceof Error ? error.message : String(error);
72+
throw new Error(`CMake build failed: ${errorMessage}. Use the cmake_get_errors tool to see detailed diagnostics.`);
73+
}
74+
}
75+
}
76+
77+
/**
78+
* Language Model Tool for configuring CMake projects
79+
*/
80+
export class CMakeConfigureTool implements vscode.LanguageModelTool<IConfigureParameters> {
81+
constructor(private readonly extensionManager: ExtensionManager) {}
82+
83+
async prepareInvocation(
84+
options: vscode.LanguageModelToolInvocationPrepareOptions<IConfigureParameters>,
85+
_token: vscode.CancellationToken
86+
): Promise<vscode.PreparedToolInvocation> {
87+
const cleanFirst = options.input.cleanFirst ?? false;
88+
const presetName = this.extensionManager.activeConfigurePresetName() || 'default';
89+
90+
const action = cleanFirst ? 'Clean and reconfigure' : 'Configure';
91+
const confirmationMessages = {
92+
title: `${action} CMake Project`,
93+
message: new vscode.MarkdownString(
94+
`${action} the CMake project with preset '${presetName}'?`
95+
)
96+
};
97+
98+
return {
99+
invocationMessage: cleanFirst ? 'Cleaning and reconfiguring CMake project...' : 'Configuring CMake project...',
100+
confirmationMessages
101+
};
102+
}
103+
104+
async invoke(
105+
options: vscode.LanguageModelToolInvocationOptions<IConfigureParameters>,
106+
_token: vscode.CancellationToken
107+
): Promise<vscode.LanguageModelToolResult> {
108+
const params = options.input;
109+
const presetName = this.extensionManager.activeConfigurePresetName() || 'default';
110+
111+
try {
112+
let result: number;
113+
if (params.cleanFirst) {
114+
result = await this.extensionManager.cleanConfigure();
115+
} else {
116+
result = await this.extensionManager.configure();
117+
}
118+
119+
if (result === 0) {
120+
const action = params.cleanFirst ? 'Clean reconfiguration' : 'Configuration';
121+
const message = `${action} completed successfully using preset '${presetName}'.`;
122+
return new vscode.LanguageModelToolResult([
123+
new vscode.LanguageModelTextPart(message)
124+
]);
125+
} else {
126+
const errorMsg = `CMake configuration failed with exit code ${result}.`;
127+
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.');
128+
}
129+
} catch (error) {
130+
const errorMessage = error instanceof Error ? error.message : String(error);
131+
throw new Error(`CMake configuration failed: ${errorMessage}. Use the cmake_get_errors tool to see detailed diagnostics.`);
132+
}
133+
}
134+
}
135+
136+
/**
137+
* Language Model Tool for retrieving CMake-specific errors
138+
*/
139+
export class CMakeGetErrorsTool implements vscode.LanguageModelTool<IGetErrorsParameters> {
140+
async prepareInvocation(
141+
_options: vscode.LanguageModelToolInvocationPrepareOptions<IGetErrorsParameters>,
142+
_token: vscode.CancellationToken
143+
): Promise<vscode.PreparedToolInvocation> {
144+
return {
145+
invocationMessage: 'Reading CMake diagnostics...',
146+
confirmationMessages: {
147+
title: 'Get CMake Errors',
148+
message: new vscode.MarkdownString('Retrieve CMake-specific diagnostics (configure, build, and preset errors)?')
149+
}
150+
};
151+
}
152+
153+
async invoke(
154+
_options: vscode.LanguageModelToolInvocationOptions<IGetErrorsParameters>,
155+
_token: vscode.CancellationToken
156+
): Promise<vscode.LanguageModelToolResult> {
157+
const workspaceFolders = vscode.workspace.workspaceFolders;
158+
const workspaceRoot = workspaceFolders?.[0]?.uri.fsPath || '';
159+
160+
// Collect diagnostics from all CMake-specific collections
161+
const diagnosticGroups = [
162+
{ name: 'CMake Configure', collection: collections.cmake },
163+
{ name: 'CMake Build', collection: collections.build },
164+
{ name: 'CMake Presets', collection: collections.presets }
165+
];
166+
167+
let totalErrors = 0;
168+
let totalWarnings = 0;
169+
let totalInfo = 0;
170+
const errorLines: string[] = [];
171+
172+
for (const group of diagnosticGroups) {
173+
const diagnostics: [vscode.Uri, readonly vscode.Diagnostic[]][] = [];
174+
group.collection.forEach((uri, diags) => {
175+
diagnostics.push([uri, diags]);
176+
});
177+
178+
if (diagnostics.length === 0) {
179+
continue;
180+
}
181+
182+
const groupErrors: string[] = [];
183+
for (const [uri, diags] of diagnostics) {
184+
for (const diag of diags) {
185+
// Count by severity
186+
switch (diag.severity) {
187+
case vscode.DiagnosticSeverity.Error:
188+
totalErrors++;
189+
break;
190+
case vscode.DiagnosticSeverity.Warning:
191+
totalWarnings++;
192+
break;
193+
case vscode.DiagnosticSeverity.Information:
194+
case vscode.DiagnosticSeverity.Hint:
195+
totalInfo++;
196+
break;
197+
}
198+
199+
// Format the diagnostic
200+
const severityLabel = this.getSeverityLabel(diag.severity);
201+
const relativePath = workspaceRoot ? uri.fsPath.replace(workspaceRoot, '.') : uri.fsPath;
202+
const location = `${relativePath}:${diag.range.start.line + 1}:${diag.range.start.character + 1}`;
203+
const source = diag.source ? `[${diag.source}] ` : '';
204+
const code = diag.code ? `(${diag.code}) ` : '';
205+
206+
groupErrors.push(`${severityLabel}: ${location}: ${source}${code}${diag.message}`);
207+
}
208+
}
209+
210+
if (groupErrors.length > 0) {
211+
errorLines.push(`\n## ${group.name} Errors (${groupErrors.length})`);
212+
errorLines.push(...groupErrors);
213+
}
214+
}
215+
216+
// Build summary
217+
const summary = `Found ${totalErrors} error(s), ${totalWarnings} warning(s), ${totalInfo} info message(s) in CMake diagnostics.`;
218+
219+
if (errorLines.length === 0) {
220+
return new vscode.LanguageModelToolResult([
221+
new vscode.LanguageModelTextPart('No CMake errors found. The project is clean.')
222+
]);
223+
}
224+
225+
const fullReport = [summary, ...errorLines].join('\n');
226+
return new vscode.LanguageModelToolResult([
227+
new vscode.LanguageModelTextPart(fullReport)
228+
]);
229+
}
230+
231+
private getSeverityLabel(severity: vscode.DiagnosticSeverity): string {
232+
switch (severity) {
233+
case vscode.DiagnosticSeverity.Error:
234+
return 'ERROR';
235+
case vscode.DiagnosticSeverity.Warning:
236+
return 'WARNING';
237+
case vscode.DiagnosticSeverity.Information:
238+
return 'INFO';
239+
case vscode.DiagnosticSeverity.Hint:
240+
return 'HINT';
241+
default:
242+
return 'UNKNOWN';
243+
}
244+
}
245+
}

0 commit comments

Comments
 (0)