-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathpython-debug-adapter.ts
More file actions
679 lines (583 loc) · 20.1 KB
/
Copy pathpython-debug-adapter.ts
File metadata and controls
679 lines (583 loc) · 20.1 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
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
/**
* Python Debug Adapter implementation
*
* Provides Python-specific debugging functionality using debugpy.
* Encapsulates all Python-specific logic including executable discovery,
* environment validation, and debugpy integration.
*
* @since 2.0.0
*/
import { EventEmitter } from 'events';
import { spawn } from 'child_process';
import { DebugProtocol } from '@vscode/debugprotocol';
import * as path from 'path';
import {
IDebugAdapter,
AdapterState,
ValidationResult,
ValidationError,
ValidationWarning,
DependencyInfo,
AdapterCommand,
AdapterConfig,
GenericLaunchConfig,
LanguageSpecificLaunchConfig,
DebugFeature,
FeatureRequirement,
AdapterCapabilities,
AdapterError,
AdapterErrorCode,
AdapterEvents
} from '@debugmcp/shared';
import { DebugLanguage } from '@debugmcp/shared';
import { AdapterDependencies } from '@debugmcp/shared';
import { findPythonExecutable, getPythonVersion } from './utils/python-utils.js';
/**
* Cache entry for Python executable paths
*/
interface PythonPathCacheEntry {
path: string;
timestamp: number;
version?: string;
hasDebugpy?: boolean;
}
/**
* Python-specific launch configuration
*/
interface PythonLaunchConfig extends LanguageSpecificLaunchConfig {
module?: string; // For -m module execution
pythonArgs?: string[]; // Additional Python arguments
console?: 'integratedTerminal' | 'internalConsole' | 'externalTerminal';
django?: boolean; // Django debugging support
flask?: boolean; // Flask debugging support
jinja?: boolean; // Jinja template debugging
redirectOutput?: boolean; // Redirect output to debug console
showReturnValue?: boolean; // Show function return values
subProcess?: boolean; // Debug child processes
[key: string]: unknown; // Required by LanguageSpecificLaunchConfig
}
/**
* Python Debug Adapter implementation
*/
export class PythonDebugAdapter extends EventEmitter implements IDebugAdapter {
readonly language = DebugLanguage.PYTHON;
readonly name = 'Python Debug Adapter';
private state: AdapterState = AdapterState.UNINITIALIZED;
private dependencies: AdapterDependencies;
// Caching
private pythonPathCache = new Map<string, PythonPathCacheEntry>();
private readonly cacheTimeout = 60000; // 1 minute
// State
private currentThreadId: number | null = null;
private connected = false;
constructor(dependencies: AdapterDependencies) {
super();
this.dependencies = dependencies;
}
// ===== Lifecycle Management =====
async initialize(): Promise<void> {
if (process.env.CI === 'true') {
console.error('[PythonDebugAdapter] Starting initialize()');
}
this.transitionTo(AdapterState.INITIALIZING);
try {
// Validate environment
if (process.env.CI === 'true') {
console.error('[PythonDebugAdapter] Calling validateEnvironment()');
}
const validation = await this.validateEnvironment();
if (!validation.valid) {
if (process.env.CI === 'true') {
console.error('[PythonDebugAdapter] Validation failed:', validation.errors);
}
this.transitionTo(AdapterState.ERROR);
throw new AdapterError(
validation.errors[0]?.message || 'Python environment validation failed',
AdapterErrorCode.ENVIRONMENT_INVALID
);
}
this.transitionTo(AdapterState.READY);
this.emit('initialized');
} catch (error) {
this.transitionTo(AdapterState.ERROR);
throw error;
}
}
async dispose(): Promise<void> {
this.pythonPathCache.clear();
this.currentThreadId = null;
this.connected = false;
this.state = AdapterState.UNINITIALIZED;
this.emit('disposed');
}
// ===== State Management =====
getState(): AdapterState {
return this.state;
}
isReady(): boolean {
return this.state === AdapterState.READY ||
this.state === AdapterState.CONNECTED ||
this.state === AdapterState.DEBUGGING;
}
getCurrentThreadId(): number | null {
return this.currentThreadId;
}
private transitionTo(newState: AdapterState): void {
const oldState = this.state;
this.state = newState;
this.emit('stateChanged', oldState, newState);
}
// ===== Environment Validation =====
async validateEnvironment(): Promise<ValidationResult> {
const errors: ValidationError[] = [];
const warnings: ValidationWarning[] = [];
try {
// Check Python executable
if (process.env.CI === 'true') {
console.error('[PythonDebugAdapter] Resolving Python executable path...');
}
const pythonPath = await this.resolveExecutablePath();
if (process.env.CI === 'true') {
console.error('[PythonDebugAdapter] Resolved Python path:', pythonPath);
}
// Check Python version
const version = await this.checkPythonVersion(pythonPath);
if (version) {
const [major, minor] = version.split('.').map(Number);
if (major < 3 || (major === 3 && minor < 7)) {
errors.push({
code: 'PYTHON_VERSION_TOO_OLD',
message: `Python 3.7 or higher required. Current version: ${version}`,
recoverable: false
});
}
} else {
warnings.push({
code: 'PYTHON_VERSION_CHECK_FAILED',
message: 'Could not determine Python version'
});
}
// Check debugpy installation
const hasDebugpy = await this.checkDebugpyInstalled(pythonPath);
if (!hasDebugpy) {
errors.push({
code: 'DEBUGPY_NOT_INSTALLED',
message: 'debugpy not installed. Run: pip install debugpy',
recoverable: true
});
}
// Check if in virtual environment
const isVenv = await this.detectVirtualEnv(pythonPath);
if (isVenv) {
this.dependencies.logger?.info('[PythonDebugAdapter] Virtual environment detected');
}
} catch (error) {
if (process.env.CI === 'true') {
console.error('[PythonDebugAdapter] validateEnvironment catch block error:', error);
}
errors.push({
code: 'PYTHON_NOT_FOUND',
message: error instanceof Error ? error.message : 'Python executable not found',
recoverable: false
});
}
return {
valid: errors.length === 0,
errors,
warnings
};
}
getRequiredDependencies(): DependencyInfo[] {
return [
{
name: 'Python',
version: '3.7+',
required: true,
installCommand: 'Download from https://python.org'
},
{
name: 'debugpy',
version: 'latest',
required: true,
installCommand: 'pip install debugpy'
}
];
}
// ===== Executable Management =====
async resolveExecutablePath(preferredPath?: string): Promise<string> {
// Check cache first
const cacheKey = preferredPath || 'default';
const cached = this.pythonPathCache.get(cacheKey);
if (cached && Date.now() - cached.timestamp < this.cacheTimeout) {
this.dependencies.logger?.debug(`[PythonDebugAdapter] Using cached Python path: ${cached.path}`);
return cached.path;
}
// Find Python executable
const pythonPath = await findPythonExecutable(
preferredPath,
this.dependencies.logger
);
// Cache the result
this.pythonPathCache.set(cacheKey, {
path: pythonPath,
timestamp: Date.now()
});
return pythonPath;
}
getDefaultExecutableName(): string {
switch (process.platform) {
case 'win32':
return 'py';
default:
return 'python3';
}
}
getExecutableSearchPaths(): string[] {
const paths: string[] = [];
// Add common Python installation paths
if (process.platform === 'win32') {
paths.push(
'C:\\Python313',
'C:\\Python312',
'C:\\Python311',
'C:\\Python310',
'C:\\Python39',
'C:\\Python38',
'C:\\Python37',
'C:\\Program Files\\Python313',
'C:\\Program Files\\Python312',
'C:\\Program Files\\Python311',
'C:\\Program Files\\Python310',
'C:\\Program Files\\Python39',
'C:\\Program Files\\Python38',
'C:\\Program Files\\Python37',
`${process.env.LOCALAPPDATA}\\Programs\\Python\\Python313`,
`${process.env.LOCALAPPDATA}\\Programs\\Python\\Python312`,
`${process.env.LOCALAPPDATA}\\Programs\\Python\\Python311`,
`${process.env.LOCALAPPDATA}\\Programs\\Python\\Python310`,
`${process.env.LOCALAPPDATA}\\Programs\\Python\\Python39`,
`${process.env.LOCALAPPDATA}\\Programs\\Python\\Python38`,
`${process.env.LOCALAPPDATA}\\Programs\\Python\\Python37`
);
} else if (process.platform === 'darwin') {
paths.push(
'/usr/local/bin',
'/opt/homebrew/bin',
'/usr/bin'
);
} else {
paths.push(
'/usr/bin',
'/usr/local/bin',
'/opt/python/bin'
);
}
// Add PATH directories
if (process.env.PATH) {
paths.push(...process.env.PATH.split(path.delimiter));
}
return paths;
}
// ===== Adapter Configuration =====
buildAdapterCommand(config: AdapterConfig): AdapterCommand {
return {
command: config.executablePath,
args: [
'-m', 'debugpy.adapter',
'--host', config.adapterHost,
'--port', config.adapterPort.toString()
],
env: {
...process.env,
PYTHONUNBUFFERED: '1', // Ensure unbuffered output
DEBUGPY_LOG_DIR: config.logDir
}
};
}
getAdapterModuleName(): string {
return 'debugpy.adapter';
}
getAdapterInstallCommand(): string {
return 'pip install debugpy';
}
// ===== Debug Configuration =====
async transformLaunchConfig(config: GenericLaunchConfig): Promise<LanguageSpecificLaunchConfig> {
const pythonConfig: PythonLaunchConfig = {
...config,
type: 'python',
request: 'launch',
name: 'Python: Current File',
console: 'internalConsole',
redirectOutput: true,
showReturnValue: true,
justMyCode: config.justMyCode ?? true,
stopOnEntry: config.stopOnEntry ?? false
};
return pythonConfig;
}
getDefaultLaunchConfig(): Partial<GenericLaunchConfig> {
return {
stopOnEntry: false,
justMyCode: true,
env: {},
cwd: process.cwd()
};
}
// ===== DAP Protocol Operations =====
async sendDapRequest<T extends DebugProtocol.Response>(
command: string,
args?: unknown
): Promise<T> {
// This will be handled by ProxyManager
// Adapter just needs to validate the request is appropriate for Python
// Validate Python-specific commands
if (command === 'setExceptionBreakpoints' && args) {
const exceptionArgs = args as DebugProtocol.SetExceptionBreakpointsArguments;
// Ensure Python exception filters are valid
const validFilters = ['raised', 'uncaught', 'userUnhandled'];
const invalidFilters = exceptionArgs.filters?.filter(f => !validFilters.includes(f));
if (invalidFilters?.length) {
throw new AdapterError(
`Invalid Python exception filters: ${invalidFilters.join(', ')}`,
AdapterErrorCode.INVALID_RESPONSE
);
}
}
// ProxyManager will handle actual communication
return {} as T;
}
handleDapEvent(event: DebugProtocol.Event): void {
// Update thread ID on stopped events
if (event.event === 'stopped' && event.body?.threadId) {
this.currentThreadId = event.body.threadId;
}
type AdapterEventName = Extract<keyof AdapterEvents, string | symbol>;
this.emit(event.event as AdapterEventName, event.body);
}
handleDapResponse(_response: DebugProtocol.Response): void {
// Python adapter doesn't need special response handling
}
// ===== Connection Management =====
async connect(host: string, port: number): Promise<void> {
// Connection is handled by ProxyManager
// Mark adapter as connected
this.dependencies.logger?.debug(`[PythonDebugAdapter] Connect request to ${host}:${port}`);
this.connected = true;
this.transitionTo(AdapterState.CONNECTED);
this.emit('connected');
}
async disconnect(): Promise<void> {
this.connected = false;
this.currentThreadId = null;
this.transitionTo(AdapterState.DISCONNECTED);
this.emit('disconnected');
}
isConnected(): boolean {
return this.connected;
}
// ===== Error Handling =====
getInstallationInstructions(): string {
return `Python Debugging Setup:
1. Install Python 3.7 or higher:
- Windows: Download from https://python.org
- macOS: brew install python3
- Linux: sudo apt install python3 python3-pip
2. Install debugpy:
pip install debugpy
3. Verify installation:
python -m debugpy --version
For virtual environments:
python -m venv myenv
source myenv/bin/activate # On Windows: myenv\\Scripts\\activate
pip install debugpy`;
}
getMissingExecutableError(): string {
return `Python not found. Please ensure Python 3.7+ is installed and available in PATH.
Windows users: Try 'py' command or install from https://python.org
macOS users: Try 'brew install python3'
Linux users: Try 'sudo apt install python3'
You can also specify the Python path explicitly in your debug configuration.`;
}
translateErrorMessage(error: Error): string {
const message = error.message.toLowerCase();
if (message.includes('debugpy') && message.includes('modulenotfounderror')) {
return 'debugpy is not installed. Please run: pip install debugpy';
}
if (message.includes('python') && message.includes('not found')) {
return this.getMissingExecutableError();
}
if (message.includes('permission denied')) {
return `Permission denied accessing Python executable. Check file permissions.`;
}
if (message.includes('windows store')) {
return `Windows Store Python alias detected. Please install Python from https://python.org`;
}
return error.message;
}
// ===== Feature Support =====
supportsFeature(feature: DebugFeature): boolean {
const supportedFeatures = [
DebugFeature.CONDITIONAL_BREAKPOINTS,
DebugFeature.FUNCTION_BREAKPOINTS,
DebugFeature.EXCEPTION_BREAKPOINTS,
DebugFeature.VARIABLE_PAGING,
DebugFeature.EVALUATE_FOR_HOVERS,
DebugFeature.SET_VARIABLE,
DebugFeature.LOG_POINTS,
DebugFeature.TERMINATE_REQUEST,
DebugFeature.EXCEPTION_OPTIONS,
DebugFeature.EXCEPTION_INFO_REQUEST
];
return supportedFeatures.includes(feature);
}
getFeatureRequirements(feature: DebugFeature): FeatureRequirement[] {
const requirements: FeatureRequirement[] = [];
switch (feature) {
case DebugFeature.CONDITIONAL_BREAKPOINTS:
requirements.push({
type: 'dependency',
description: 'debugpy 1.0+',
required: true
});
break;
case DebugFeature.LOG_POINTS:
requirements.push({
type: 'version',
description: 'debugpy 1.5+',
required: true
});
break;
case DebugFeature.EXCEPTION_INFO_REQUEST:
requirements.push({
type: 'version',
description: 'Python 3.7+',
required: true
});
break;
}
return requirements;
}
getCapabilities(): AdapterCapabilities {
return {
supportsConfigurationDoneRequest: true,
supportsFunctionBreakpoints: true,
supportsConditionalBreakpoints: true,
supportsHitConditionalBreakpoints: true,
supportsEvaluateForHovers: true,
exceptionBreakpointFilters: [
{
filter: 'raised',
label: 'Raised Exceptions',
description: 'Break on all raised exceptions',
default: false,
supportsCondition: true
},
{
filter: 'uncaught',
label: 'Uncaught Exceptions',
description: 'Break on uncaught exceptions',
default: true,
supportsCondition: true
},
{
filter: 'userUnhandled',
label: 'User Unhandled Exceptions',
description: 'Break on exceptions not handled by user code',
default: false,
supportsCondition: true
}
],
supportsStepBack: false,
supportsSetVariable: true,
supportsRestartFrame: false,
supportsGotoTargetsRequest: false,
supportsStepInTargetsRequest: true,
supportsCompletionsRequest: true,
completionTriggerCharacters: ['.', '['],
supportsModulesRequest: true,
supportsRestartRequest: false,
supportsExceptionOptions: true,
supportsValueFormattingOptions: true,
supportsExceptionInfoRequest: true,
supportTerminateDebuggee: true,
supportSuspendDebuggee: false,
supportsDelayedStackTraceLoading: true,
supportsLoadedSourcesRequest: true,
supportsLogPoints: true,
supportsTerminateThreadsRequest: false,
supportsSetExpression: false,
supportsTerminateRequest: true,
supportsDataBreakpoints: false,
supportsReadMemoryRequest: false,
supportsWriteMemoryRequest: false,
supportsDisassembleRequest: false,
supportsCancelRequest: false,
supportsBreakpointLocationsRequest: true,
supportsClipboardContext: false,
supportsSteppingGranularity: false,
supportsInstructionBreakpoints: false,
supportsExceptionFilterOptions: true,
supportsSingleThreadExecutionRequests: false
};
}
// ===== Python-specific helper methods =====
/**
* Check Python version
*/
private async checkPythonVersion(pythonPath: string): Promise<string | null> {
// Check cache — try resolved path first, then 'default' key
const cached = this.pythonPathCache.get(pythonPath) || this.pythonPathCache.get('default');
if (cached?.version) {
return cached.version;
}
const version = await getPythonVersion(pythonPath);
// Update cache — store explicitly under the pythonPath key to avoid key mismatch
if (version) {
this.pythonPathCache.set(pythonPath, { ...(cached ?? {}), version, path: pythonPath, timestamp: Date.now() });
}
return version;
}
/**
* Check if debugpy is installed
*/
private async checkDebugpyInstalled(pythonPath: string): Promise<boolean> {
// Check cache — try resolved path first, then 'default' key
const cached = this.pythonPathCache.get(pythonPath) || this.pythonPathCache.get('default');
if (cached?.hasDebugpy !== undefined) {
return cached.hasDebugpy;
}
return new Promise((resolve) => {
const child = spawn(pythonPath, ['-c', 'import debugpy; print(debugpy.__version__)'], {
stdio: ['ignore', 'pipe', 'pipe']
});
let output = '';
child.stdout?.on('data', (data) => { output += data.toString(); });
child.on('error', () => resolve(false));
child.on('exit', (code) => {
const hasDebugpy = code === 0 && output.trim().length > 0;
// Update cache — store explicitly under the pythonPath key to avoid key mismatch
this.pythonPathCache.set(pythonPath, { ...(cached ?? {}), hasDebugpy, path: pythonPath, timestamp: Date.now() });
if (hasDebugpy) {
this.dependencies.logger?.info(`[PythonDebugAdapter] debugpy version: ${output.trim()}`);
}
resolve(hasDebugpy);
});
});
}
/**
* Detect if Python is in a virtual environment
*/
private async detectVirtualEnv(pythonPath: string): Promise<boolean> {
return new Promise((resolve) => {
const child = spawn(pythonPath, ['-c', 'import sys; print(hasattr(sys, "real_prefix") or (hasattr(sys, "base_prefix") and sys.base_prefix != sys.prefix))'], {
stdio: ['ignore', 'pipe', 'ignore']
});
let output = '';
child.stdout?.on('data', (data) => { output += data.toString(); });
child.on('error', () => resolve(false));
child.on('exit', () => {
resolve(output.trim().toLowerCase() === 'true');
});
});
}
}