forked from microsoft/vscode-java-debug
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlanguageModelTool.ts
More file actions
1577 lines (1394 loc) · 62.4 KB
/
languageModelTool.ts
File metadata and controls
1577 lines (1394 loc) · 62.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
10000
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
import * as fs from 'fs';
import * as path from 'path';
import * as vscode from 'vscode';
import { sendError, sendInfo } from "vscode-extension-telemetry-wrapper";
// ============================================================================
// Constants
// ============================================================================
const CONSTANTS = {
/** Timeout for waitForSession mode (ms) */
SESSION_WAIT_TIMEOUT: 45000,
/** Maximum wait time for smart polling (ms) */
SMART_POLLING_MAX_WAIT: 15000,
/** Interval between polling checks (ms) */
SMART_POLLING_INTERVAL: 300,
/** Timeout for build tasks (ms) */
BUILD_TIMEOUT: 60000,
/** Maximum number of Java files to check for compilation errors */
MAX_JAVA_FILES_TO_CHECK: 100,
/** Default stack trace depth */
DEFAULT_STACK_DEPTH: 50,
/** Maximum depth for recursive file search */
MAX_FILE_SEARCH_DEPTH: 10
};
interface DebugJavaApplicationInput {
target: string;
workspacePath: string;
args?: string[];
skipBuild?: boolean;
classpath?: string;
waitForSession?: boolean;
}
interface DebugJavaApplicationResult {
success: boolean;
message: string;
terminalName?: string;
status?: 'started' | 'timeout' | 'sent'; // More specific status
sessionId?: string; // Session ID if detected
}
// Type definitions for Language Model API (these will be in future VS Code versions)
// For now, we use 'any' to allow compilation with older VS Code types
interface LanguageModelTool<T = any> {
invoke(options: { input: T }, token: vscode.CancellationToken): Promise<any>;
}
/**
* Registers the Language Model Tool for debugging Java applications.
* This allows AI assistants to help users debug Java code by invoking the debugjava command.
*/
export function registerLanguageModelTool(context: vscode.ExtensionContext): vscode.Disposable | undefined {
// Check if the Language Model API is available
const lmApi = (vscode as any).lm;
if (!lmApi || typeof lmApi.registerTool !== 'function') {
// Language Model API not available in this VS Code version
return undefined;
}
const tool: LanguageModelTool<DebugJavaApplicationInput> = {
async invoke(options: { input: DebugJavaApplicationInput }, token: vscode.CancellationToken): Promise<any> {
sendInfo('', {
operationName: 'languageModelTool.debugJavaApplication.invoke',
target: options.input.target,
skipBuild: options.input.skipBuild?.toString() || 'false',
});
try {
const result = await debugJavaApplication(options.input, token);
// Format the message for AI - use simple text, not JSON
const message = result.success
? `✓ ${result.message}`
: `✗ ${result.message}`;
// Return result in the expected format - simple text part
return new (vscode as any).LanguageModelToolResult([
new (vscode as any).LanguageModelTextPart(message)
]);
} catch (error) {
sendError(error as Error);
const errorMessage = error instanceof Error ? error.message : String(error);
return new (vscode as any).LanguageModelToolResult([
new (vscode as any).LanguageModelTextPart(`✗ Debug failed: ${errorMessage}`)
]);
}
}
};
const disposable = lmApi.registerTool('debug_java_application', tool);
context.subscriptions.push(disposable);
return disposable;
}
/**
* Main function to debug a Java application.
* This function handles:
* 1. Cleanup any existing debug session (to avoid port conflicts)
* 2. Project type detection
* 3. Building the project if needed
* 4. Executing the debugjava command
*/
async function debugJavaApplication(
input: DebugJavaApplicationInput,
token: vscode.CancellationToken
): Promise<DebugJavaApplicationResult> {
if (token.isCancellationRequested) {
return {
success: false,
message: 'Operation cancelled by user'
};
}
// Step 0: Cleanup any existing Java debug session to avoid port conflicts
const existingSession = vscode.debug.activeDebugSession;
if (existingSession && existingSession.type === 'java') {
sendInfo('', {
operationName: 'languageModelTool.cleanupExistingSession',
sessionId: existingSession.id,
sessionName: existingSession.name
});
try {
await vscode.debug.stopDebugging(existingSession);
// Give VS Code a moment to clean up the session
await new Promise(resolve => setTimeout(resolve, 500));
} catch (error) {
// Log but continue - the old session might already be dead
sendInfo('', {
operationName: 'languageModelTool.cleanupExistingSessionFailed',
error: String(error)
});
}
}
// Also close any existing "Java Debug" terminals to avoid confusion
for (const existingTerminal of vscode.window.terminals) {
if (existingTerminal.name === 'Java Debug') {
existingTerminal.dispose();
}
}
// Validate workspace path
const workspaceUri = vscode.Uri.file(input.workspacePath);
if (!fs.existsSync(input.workspacePath)) {
return {
success: false,
message: `Workspace path does not exist: ${input.workspacePath}`
};
}
// Step 1: Detect project type
const projectType = detectProjectType(input.workspacePath);
// Step 2: Build the project if needed
if (!input.skipBuild) {
const buildResult = await buildProject(workspaceUri, projectType, token);
if (!buildResult.success) {
return buildResult;
}
}
// Step 3: Construct and execute the debugjava command
const debugCommand = constructDebugCommand(input, projectType);
// Validate that we can construct a valid command
if (!debugCommand || debugCommand === 'debugjava') {
return {
success: false,
message: 'Failed to construct debug command. Please check the target parameter.'
};
}
// Step 4: Execute in terminal and optionally wait for debug session
const terminal = vscode.window.createTerminal({
name: 'Java Debug',
cwd: input.workspacePath,
hideFromUser: false,
isTransient: false // Keep terminal alive even after process exits
});
terminal.show();
// Build info message for AI
let targetInfo = input.target;
let warningNote = '';
if (input.target.endsWith('.jar')) {
targetInfo = input.target;
} else if (input.target.includes('.')) {
targetInfo = input.target;
} else {
// Simple class name - check if we successfully detected the full name
const detectedClassName = findFullyQualifiedClassName(input.workspacePath, input.target, projectType);
if (detectedClassName) {
targetInfo = `${detectedClassName} (detected from ${input.target})`;
} else {
targetInfo = input.target;
warningNote = ' ⚠️ Note: Could not auto-detect package name. If you see "ClassNotFoundException", please provide the fully qualified class name (e.g., "com.example.App" instead of "App").';
}
}
// If waitForSession is true, wait for the debug session to start
if (input.waitForSession) {
return new Promise<DebugJavaApplicationResult>((resolve) => {
let sessionStarted = false;
// Listen for debug session start
const sessionDisposable = vscode.debug.onDidStartDebugSession((session) => {
if (session.type === 'java' && !sessionStarted) {
sessionStarted = true;
sessionDisposable.dispose();
if (timeoutHandle) {
clearTimeout(timeoutHandle);
}
sendInfo('', {
operationName: 'languageModelTool.debugSessionStarted.eventBased',
sessionId: session.id,
sessionName: session.name
});
resolve({
success: true,
status: 'started',
sessionId: session.id,
message: `✓ Debug session started for ${targetInfo}. Session ID: ${session.id}. The debugger is now attached and ready. Any breakpoints you set will be active.${warningNote}`,
terminalName: terminal.name
});
}
});
// Send the command after setting up the listener
terminal.sendText(debugCommand);
// Set a timeout for large applications
const timeoutHandle = setTimeout(() => {
if (!sessionStarted) {
sessionDisposable.dispose();
sendInfo('', {
operationName: 'languageModelTool.debugSessionTimeout.eventBased',
target: targetInfo
});
resolve({
success: false,
status: 'timeout',
message: `❌ Debug session failed to start within ${CONSTANTS.SESSION_WAIT_TIMEOUT / 1000} seconds for ${targetInfo}.\n\n` +
`This usually indicates a problem:\n` +
`• Compilation errors preventing startup\n` +
`• ClassNotFoundException or NoClassDefFoundError\n` +
`• Application crashed during initialization\n` +
`• Incorrect main class or classpath configuration\n\n` +
`Action required:\n` +
`1. Check terminal '${terminal.name}' for error messages\n` +
`2. Verify the target class name is correct\n` +
`3. Ensure the project is compiled successfully\n` +
`4. Use get_debug_session_info() to confirm session status${warningNote}`,
terminalName: terminal.name
});
}
}, CONSTANTS.SESSION_WAIT_TIMEOUT);
});
} else {
// Default behavior: send command and use smart polling to detect session start
terminal.sendText(debugCommand);
// Smart polling to detect session start
const maxWaitTime = CONSTANTS.SMART_POLLING_MAX_WAIT;
const pollInterval = CONSTANTS.SMART_POLLING_INTERVAL;
const startTime = Date.now();
while (Date.now() - startTime < maxWaitTime) {
// Check if debug session has started
const session = vscode.debug.activeDebugSession;
if (session && session.type === 'java') {
const elapsedTime = ((Date.now() - startTime) / 1000).toFixed(1);
sendInfo('', {
operationName: 'languageModelTool.debugSessionDetected',
sessionId: session.id,
elapsedTime
});
return {
success: true,
status: 'started',
sessionId: session.id,
message: `✓ Debug session started for ${targetInfo} (detected in ${elapsedTime}s). Session ID: ${session.id}. The debugger is attached and ready.${warningNote}`,
terminalName: terminal.name
};
}
// Wait before next check
await new Promise(resolve => setTimeout(resolve, pollInterval));
}
// Timeout: session not detected within 15 seconds
sendInfo('', {
operationName: 'languageModelTool.debugSessionTimeout.smartPolling',
target: targetInfo,
maxWaitTime
});
return {
success: true,
status: 'timeout',
message: `⚠️ Debug command sent for ${targetInfo}, but session not detected within ${CONSTANTS.SMART_POLLING_MAX_WAIT / 1000} seconds.\n\n` +
`Possible reasons:\n` +
`• Application is still starting (large projects may take longer)\n` +
`• Compilation errors (check terminal '${terminal.name}' for errors)\n` +
`• Application may have started and already terminated\n\n` +
`Next steps:\n` +
`• Use get_debug_session_info() to check if session is now active\n` +
`• Check terminal '${terminal.name}' for error messages\n` +
`• If starting slowly, wait a bit longer and check again${warningNote}`,
terminalName: terminal.name
};
}
}
/**
* Detects the type of Java project based on build files present.
*/
function detectProjectType(workspacePath: string): 'maven' | 'gradle' | 'vscode' | 'unknown' {
if (fs.existsSync(path.join(workspacePath, 'pom.xml'))) {
return 'maven';
}
if (fs.existsSync(path.join(workspacePath, 'build.gradle')) ||
fs.existsSync(path.join(workspacePath, 'build.gradle.kts'))) {
return 'gradle';
}
// Check if VS Code Java extension is likely managing compilation
const workspaceFolder = vscode.workspace.getWorkspaceFolder(vscode.Uri.file(workspacePath));
if (workspaceFolder) {
const javaExt = vscode.extensions.getExtension('redhat.java');
if (javaExt?.isActive) {
return 'vscode';
}
}
return 'unknown';
}
/**
* Builds the Java project based on its type.
*/
async function buildProject(
workspaceUri: vscode.Uri,
projectType: 'maven' | 'gradle' | 'vscode' | 'unknown',
_token: vscode.CancellationToken
): Promise<DebugJavaApplicationResult> {
switch (projectType) {
case 'maven':
return buildMavenProject(workspaceUri);
case 'gradle':
return buildGradleProject(workspaceUri);
case 'vscode':
return ensureVSCodeCompilation(workspaceUri);
case 'unknown':
// Try to proceed anyway - user might have manually compiled
return {
success: true,
message: 'Unknown project type. Skipping build step. Ensure your Java files are compiled.'
};
}
}
/**
* Executes a shell task and waits for completion.
* This is a common function used by both Maven and Gradle builds.
*/
async function executeShellTask(
workspaceUri: vscode.Uri,
taskId: string,
taskName: string,
command: string,
successMessage: string,
timeoutMessage: string,
failureMessagePrefix: string
): Promise<DebugJavaApplicationResult> {
return new Prom
4D2B
ise((resolve) => {
const workspaceFolder = vscode.workspace.getWorkspaceFolder(workspaceUri);
if (!workspaceFolder) {
resolve({
success: false,
message: `Cannot find workspace folder for ${workspaceUri.fsPath}`
});
return;
}
const task = new vscode.Task(
{ type: 'shell', task: taskId },
workspaceFolder,
taskName,
'Java Debug',
new vscode.ShellExecution(command, { cwd: workspaceUri.fsPath })
);
let resolved = false;
let taskDisposable: vscode.Disposable | undefined;
let errorDisposable: vscode.Disposable | undefined;
const cleanup = () => {
clearTimeout(timeoutHandle);
taskDisposable?.dispose();
errorDisposable?.dispose();
};
// Set a timeout to avoid hanging indefinitely
const timeoutHandle = setTimeout(() => {
if (!resolved) {
resolved = true;
cleanup();
resolve({
success: true,
message: timeoutMessage
});
}
}, CONSTANTS.BUILD_TIMEOUT);
vscode.tasks.executeTask(task).then(
(execution) => {
taskDisposable = vscode.tasks.onDidEndTask((e) => {
if (e.execution === execution && !resolved) {
resolved = true;
cleanup();
resolve({
success: true,
message: successMessage
});
}
});
errorDisposable = vscode.tasks.onDidEndTaskProcess((e) => {
if (e.execution === execution && e.exitCode !== 0 && !resolved) {
resolved = true;
cleanup();
resolve({
success: false,
message: `${failureMessagePrefix} with exit code ${e.exitCode}. Please check the terminal output.`
});
}
});
},
(error: Error) => {
if (!resolved) {
resolved = true;
cleanup();
resolve({
success: false,
message: `Failed to execute task: ${error.message}`
});
}
}
);
});
}
/**
* Builds a Maven project using mvn compile.
*/
async function buildMavenProject(
workspaceUri: vscode.Uri
): Promise<DebugJavaApplicationResult> {
return executeShellTask(
workspaceUri,
'maven-compile',
'Maven Compile',
'mvn compile',
'Maven project compiled successfully',
'Maven compile command sent. Build may still be in progress.',
'Maven build failed'
);
}
/**
* Builds a Gradle project using gradle classes.
*/
async function buildGradleProject(
workspaceUri: vscode.Uri
): Promise<DebugJavaApplicationResult> {
const gradleWrapper = process.platform === 'win32' ? 'gradlew.bat' : './gradlew';
const gradleCommand = fs.existsSync(path.join(workspaceUri.fsPath, gradleWrapper))
? gradleWrapper
: 'gradle';
return executeShellTask(
workspaceUri,
'gradle-classes',
'Gradle Classes',
`${gradleCommand} classes`,
'Gradle project compiled successfully',
'Gradle compile command sent. Build may still be in progress.',
'Gradle build failed'
);
}
/**
* Ensures VS Code Java Language Server has compiled the files.
*/
async function ensureVSCodeCompilation(workspaceUri: vscode.Uri): Promise<DebugJavaApplicationResult> {
try {
// Check for compilation errors using VS Code diagnostics
const javaFiles = await vscode.workspace.findFiles(
new vscode.RelativePattern(workspaceUri, '**/*.java'),
'**/node_modules/**',
CONSTANTS.MAX_JAVA_FILES_TO_CHECK
);
let hasErrors = false;
for (const file of javaFiles) {
const diagnostics = vscode.languages.getDiagnostics(file);
const errors = diagnostics.filter(d => d.severity === vscode.DiagnosticSeverity.Error);
if (errors.length > 0) {
hasErrors = true;
break;
}
}
if (hasErrors) {
return {
success: false,
message: 'Compilation errors detected in the project. Please fix the errors before debugging.'
};
}
// Check if Java extension is active and in standard mode
const javaExt = vscode.extensions.getExtension('redhat.java');
if (!javaExt?.isActive) {
return {
success: true,
message: 'Java Language Server is not active. Proceeding with debug, but ensure your code is compiled.'
};
}
return {
success: true,
message: 'VS Code Java compilation verified'
};
} catch (error) {
// If we can't verify, proceed anyway
return {
success: true,
message: 'Unable to verify compilation status. Proceeding with debug.'
};
}
}
/**
* Constructs the debugjava command based on input parameters.
*/
function constructDebugCommand(
input: DebugJavaApplicationInput,
projectType: 'maven' | 'gradle' | 'vscode' | 'unknown'
): string {
let command = 'debugjava';
// Handle JAR files
if (input.target.endsWith('.jar')) {
command += ` -jar ${input.target}`;
}
// Handle raw java command arguments (starts with - like -cp, -jar, etc)
else if (input.target.startsWith('-')) {
command += ` ${input.target}`;
}
// Handle class name (with or without package)
else {
let className = input.target;
// If target doesn't contain a dot and we can find the Java file,
// try to detect the fully qualified class name
if (!input.target.includes('.')) {
const detectedClassName = findFullyQualifiedClassName(input.workspacePath, input.target, projectType);
if (detectedClassName) {
sendInfo('', {
operationName: 'languageModelTool.classNameDetection',
simpleClassName: input.target,
detectedClassName,
projectType
});
className = detectedClassName;
} else {
// No package detected - class is in default package
sendInfo('', {
operationName: 'languageModelTool.classNameDetection.noPackage',
simpleClassName: input.target,
projectType
});
}
}
// Use provided classpath if available, otherwise infer it
const classpath = input.classpath || inferClasspath(input.workspacePath, projectType);
command += ` -cp "${classpath}" ${className}`;
}
// Add arguments if provided
if (input.args && input.args.length > 0) {
command += ' ' + input.args.join(' ');
}
return command;
}
/**
* Tries to find the fully qualified class name by searching for the Java file.
* This helps when user provides just "App" instead of "com.example.App".
*/
function findFullyQualifiedClassName(
workspacePath: string,
simpleClassName: string,
projectType: 'maven' | 'gradle' | 'vscode' | 'unknown'
): string | null {
// Determine source directories based on project type
const sourceDirs: string[] = [];
switch (projectType) {
case 'maven':
sourceDirs.push(path.join(workspacePath, 'src', 'main', 'java'));
break;
case 'gradle':
sourceDirs.push(path.join(workspacePath, 'src', 'main', 'java'));
break;
case 'vscode':
sourceDirs.push(path.join(workspacePath, 'src'));
break;
case 'unknown':
// Try all common locations
sourceDirs.push(
path.join(workspacePath, 'src', 'main', 'java'),
path.join(workspacePath, 'src'),
workspacePath
);
break;
}
// Search for the Java file
for (const srcDir of sourceDirs) {
if (!fs.existsSync(srcDir)) {
continue;
}
try {
const javaFile = findJavaFile(srcDir, simpleClassName, 0);
if (javaFile) {
4D2B
// Extract package name from the file
const packageName = extractPackageName(javaFile);
if (packageName) {
return `${packageName}.${simpleClassName}`;
} else {
// No package, use simple name
return simpleClassName;
}
}
} catch (error) {
// Continue searching in other directories
}
}
return null;
}
/**
* Recursively searches for a Java file with the given class name.
* @param depth Current recursion depth (for limiting search depth)
*/
function findJavaFile(dir: string, className: string, depth: number = 0): string | null {
// Limit recursion depth to prevent performance issues
if (depth > CONSTANTS.MAX_FILE_SEARCH_DEPTH) {
return null;
}
try {
const files = fs.readdirSync(dir);
for (const file of files) {
const filePath = path.join(dir, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
// Skip common non-source directories
if (file === 'node_modules' || file === '.git' || file === 'target' || file === 'build') {
continue;
}
const found = findJavaFile(filePath, className, depth + 1);
if (found) {
return found;
}
} else if (file === `${className}.java`) {
return filePath;
}
}
} catch (error) {
// Ignore permission errors or other file system issues
}
return null;
}
/**
* Extracts the package name from a Java source file.
*/
function extractPackageName(javaFilePath: string): string | null {
try {
const content = fs.readFileSync(javaFilePath, 'utf-8');
const packageMatch = content.match(/^\s*package\s+([\w.]+)\s*;/m);
return packageMatch ? packageMatch[1] : null;
} catch (error) {
return null;
}
}
/**
* Checks if a directory contains any .class files.
* @param depth Current recursion depth (for limiting search depth)
*/
function hasClassFiles(dir: string, depth: number = 0): boolean {
// Limit recursion depth to prevent performance issues
if (depth > CONSTANTS.MAX_FILE_SEARCH_DEPTH) {
return false;
}
try {
const files = fs.readdirSync(dir);
for (const file of files) {
const filePath = path.join(dir, file);
const stat = fs.statSync(filePath);
if (stat.isFile() && file.endsWith('.class')) {
return true;
} else if (stat.isDirectory()) {
if (hasClassFiles(filePath, depth + 1)) {
return true;
}
}
}
} catch (error) {
// Ignore errors
}
return false;
}
/**
* Infers the classpath based on project type and common conventions.
*/
function inferClasspath(workspacePath: string, projectType: 'maven' | 'gradle' | 'vscode' | 'unknown'): string {
const classpaths: string[] = [];
switch (projectType) {
case 'maven':
// Maven standard output directory
const mavenTarget = path.join(workspacePath, 'target', 'classes');
if (fs.existsSync(mavenTarget)) {
classpaths.push(mavenTarget);
}
break;
case 'gradle':
// Gradle standard output directories
const gradleMain = path.join(workspacePath, 'build', 'classes', 'java', 'main');
if (fs.existsSync(gradleMain)) {
classpaths.push(gradleMain);
}
break;
case 'vscode':
// VS Code Java extension default output
const vscodeOut = path.join(workspacePath, 'bin');
if (fs.existsSync(vscodeOut)) {
classpaths.push(vscodeOut);
}
break;
}
// Fallback to common locations
if (classpaths.length === 0) {
const commonPaths = [
path.join(workspacePath, 'bin'), // VS Code default
path.join(workspacePath, 'out'), // IntelliJ default
path.join(workspacePath, 'target', 'classes'), // Maven
path.join(workspacePath, 'build', 'classes', 'java', 'main'), // Gradle
path.join(workspacePath, 'build', 'classes'),
];
// Check each common path
for (const p of commonPaths) {
if (fs.existsSync(p)) {
// Check if there are actually .class files in this directory
if (hasClassFiles(p)) {
classpaths.push(p);
break;
}
}
}
}
// If still no classpath found, use current directory
// This is common for simple projects where .class files are alongside .java files
if (classpaths.length === 0) {
classpaths.push('.');
}
return classpaths.join(path.delimiter);
}
// ============================================================================
// Debug Session Control Tools
// ============================================================================
interface SetBreakpointInput {
filePath: string;
lineNumber: number;
condition?: string;
hitCondition?: string;
logMessage?: string;
}
interface StepOperationInput {
operation: 'stepIn' | 'stepOut' | 'stepOver' | 'continue' | 'pause';
threadId?: number;
}
interface GetVariablesInput {
threadId?: number;
frameId?: number;
scopeType?: 'local' | 'static' | 'all';
filter?: string;
}
interface GetStackTraceInput {
threadId?: number;
maxDepth?: number;
}
interface EvaluateExpressionInput {
expression: string;
threadId?: number;
frameId?: number;
context?: 'watch' | 'repl' | 'hover';
}
interface RemoveBreakpointsInput {
filePath?: string;
lineNumber?: number;
}
interface StopDebugSessionInput {
reason?: string;
}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
type GetDebugSessionInfoInput = Record<string, never>;
/**
* Result of finding a suspended thread
*/
interface SuspendedThreadInfo {
threadId: number;
frameId: number;
}
/**
* Finds the first suspended thread in the debug session.
* Returns the thread ID and top frame ID, or null if no suspended thread is found.
*/
async function findFirstSuspendedThread(session: vscode.DebugSession): Promise<SuspendedThreadInfo | null> {
try {
const threadsResponse = await session.customRequest('threads');
for (const thread of threadsResponse.threads || []) {
try {
const stackResponse = await session.customRequest('stackTrace', {
threadId: thread.id,
startFrame: 0,
levels: 1
});
if (stackResponse?.stackFrames?.length > 0) {
return {
threadId: thread.id,
frameId: stackResponse.stackFrames[0].id
};
}
} catch {
// Thread is running, continue to next
continue;
}
}
} catch {
// Failed to get threads
}
return null;
}
/**
* Registers all debug session control tools
*/
export function registerDebugSessionTools(_context: vscode.ExtensionContext): vscode.Disposable[] {
const lmApi = (vscode as any).lm;
if (!lmApi || typeof lmApi.registerTool !== 'function') {
return [];
}
const disposables: vscode.Disposable[] = [];
// Tool 1: Set Breakpoint
const setBreakpointTool: LanguageModelTool<SetBreakpointInput> = {
async invoke(options: { input: SetBreakpointInput }, _token: vscode.CancellationToken): Promise<any> {
try {
const { filePath, lineNumber, condition, hitCondition, logMessage } = options.input;
// Set breakpoint through VS Code API (no active session required)
const uri = vscode.Uri.file(filePath);
const breakpoint = new vscode.SourceBreakpoint(
new vscode.Location(uri, new vscode.Position(lineNumber - 1, 0)),
true, // enabled
condition,
hitCondition,
logMessage
);
vscode.debug.addBreakpoints([breakpoint]);
const bpType = logMessage ? 'Logpoint' : 'Breakpoint';
const session = vscode.debug.activeDebugSession;
const sessionInfo = (session && session.type === 'java')
? ' (active in current session)'
: ' (will activate when debugging starts)';
return new (vscode as any).LanguageModelToolResult([
new (vscode as any).LanguageModelTextPart(
`✓ ${bpType} set at ${path.basename(filePath)}:${lineNumber}${condition ? ` (condition: ${condition})` : ''}${sessionInfo}`
)
]);
} catch (error) {
return new (vscode as any).LanguageModelToolResult([
new (vscode as any).LanguageModelTextPart(`✗ Failed to set breakpoint: ${error}`)
]);
}
}
};
disposables.push(lmApi.registerTool('set_java_breakpoint', setBreakpointTool));
// Tool 2: Step Operations
const stepOperationTool: LanguageModelTool<StepOperationInput> = {
async invoke(options: { input: StepOperationInput }, _token: vscode.CancellationToken): Promise<any> {
try {
const session = vscode.debug.activeDebugSession;
if (!session || session.type !== 'java') {
return new (vscode as any).LanguageModelToolResult([
new (vscode as any).LanguageModelTextPart('✗ No active Java debug session.')
]);
}
const { operation, threadId } = options.input;
// Map operation to VS Code debug commands
const commandMap: { [key: string]: string } = {
stepIn: 'workbench.action.debug.stepInto',
stepOut: 'workbench.action.debug.stepOut',
stepOver: 'workbench.action.debug.stepOver',
continue: 'workbench.action.debug.continue',
pause: 'workbench.action.debug.pause'
};
const command = commandMap[operation];
if (threadId !== undefined) {
// For thread-specific operations, use custom request
await session.customRequest(operation, { threadId });
} else {
// Use VS Code command for current thread
await vscode.commands.executeCommand(command);
}
return new (vscode as any).LanguageModelToolResult([
new (vscode as any).LanguageModelTextPart(`✓ Executed ${operation}`)
]);
} catch (error) {
return new (vscode as any).LanguageModelToolResult([
new (vscode as any).LanguageModelTextPart(`✗ Step operation failed: ${error}`)
]);
}
}
};
disposables.push(lmApi.registerTool('debug_step_operation', stepOperationTool));
// Tool 3: Get Variables
const getVariablesTool: LanguageModelTool<GetVariablesInput> = {
async invoke(options: { input: GetVariablesInput }, _token: vscode.CancellationToken): Promise<any> {