-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathpython-debug-adapter.ts
More file actions
859 lines (748 loc) · 26.6 KB
/
Copy pathpython-debug-adapter.ts
File metadata and controls
859 lines (748 loc) · 26.6 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
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
/**
* 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 { existsSync } from 'fs';
import { DebugProtocol } from '@vscode/debugprotocol';
import * as path from 'path';
import {
IDebugAdapter,
AdapterState,
ValidationResult,
ValidationError,
ValidationWarning,
DependencyInfo,
AdapterCommand,
AdapterConfig,
GenericLaunchConfig,
LanguageSpecificLaunchConfig,
GenericAttachConfig,
LanguageSpecificAttachConfig,
DebugFeature,
FeatureRequirement,
AdapterCapabilities,
AdapterError,
AdapterErrorCode,
AdapterEvents
} from '@debugmcp/shared';
import { DebugLanguage } from '@debugmcp/shared';
import { AdapterDependencies } from '@debugmcp/shared';
import { sanitizeStderrTail } 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-specific attach configuration (debugpy client-connect shape)
*/
interface PythonAttachConfig extends LanguageSpecificAttachConfig {
type: 'python';
request: 'attach';
name: string;
connect: { host: string; port: number };
justMyCode: boolean;
cwd?: string;
env?: Record<string, string>;
pathMappings?: Array<{ localRoot: string; remoteRoot: string }>;
}
/**
* Python Debug Adapter implementation
*/
export class PythonDebugAdapter extends EventEmitter implements IDebugAdapter {
readonly language = DebugLanguage.PYTHON;
readonly name = 'Python Debug Adapter';
// debugpy attach schema https://github.com/microsoft/debugpy/wiki/Debug-configuration-settings
// plus the generic keys transformAttachConfig special-cases. Unlisted keys
// still reach debugpy (forwarded with a warning) — this list only powers
// recognition + typo suggestions (#466).
readonly supportedAttachKeys = [
'host',
'port',
'justMyCode',
'pathMappings',
'redirectOutput',
'showReturnValue',
'subProcess',
'clientOS',
'django',
'jinja',
'stopOnEntry',
'cwd',
'env',
'logToFile',
'steppingResumesAllThreads',
'rules'
] as const;
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(executablePath?: string): Promise<ValidationResult> {
const errors: ValidationError[] = [];
const warnings: ValidationWarning[] = [];
try {
// Check Python executable. Validate the interpreter the user actually configured
// (e.g. a virtualenv python) rather than an auto-detected system one — see issue #106.
if (process.env.CI === 'true') {
console.error('[PythonDebugAdapter] Resolving Python executable path...');
}
const pythonPath = await this.resolveExecutablePath(executablePath);
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. When the user configured an explicit interpreter we fail
// fast with a clear, correct error for that interpreter. When the interpreter was merely
// auto-detected (no executablePath given), debugpy may still live in the user's virtualenv,
// so we downgrade to a warning and re-check at launch time — consistent with the factory's
// #16 fix and avoids blocking virtualenv users (issue #106).
const hasDebugpy = await this.checkDebugpyInstalled(pythonPath);
if (!hasDebugpy) {
if (executablePath) {
errors.push({
code: 'DEBUGPY_NOT_INSTALLED',
message: `debugpy not installed for ${pythonPath}. Run: ${pythonPath} -m pip install debugpy`,
recoverable: true
});
} else {
warnings.push({
code: 'DEBUGPY_NOT_INSTALLED',
message: 'debugpy not found in the auto-detected Python. If using a virtualenv, ' +
'pass its interpreter as executablePath; otherwise run: pip install debugpy'
});
}
}
// 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: this.preferNoConsoleInterpreter(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
}
};
}
/**
* On Windows, run the adapter under the sibling pythonw.exe when it exists.
*
* The adapter is spawned detached, so it has no console; debugpy's launcher
* (a console-subsystem grandchild that Node's windowsHide cannot reach) then
* gets a fresh *visible* console allocated by Windows — one window per debug
* session (#215). pythonw.exe is the GUI-subsystem build of the same
* interpreter (same directory ⇒ same version, site-packages, and venv), and
* since the launch config does not pin `python`, the launcher and debuggee
* inherit it too, so no process in the chain ever gets a console. Debuggee
* output is unaffected: with internalConsole it flows through pipes owned by
* the launcher, not a console.
*/
private preferNoConsoleInterpreter(executablePath: string): string {
if (process.platform !== 'win32') {
return executablePath;
}
// path.win32 explicitly: this is Windows path logic and must behave the
// same when unit-tested on posix hosts.
const base = path.win32.basename(executablePath);
if (!/^python(\d+(\.\d+)*)?\.exe$/i.test(base)) {
return executablePath;
}
const pythonw = path.win32.join(path.win32.dirname(executablePath), base.replace(/^python/i, 'pythonw'));
return existsSync(pythonw) ? pythonw : executablePath;
}
getAdapterModuleName(): string {
return 'debugpy.adapter';
}
getAdapterInstallCommand(): string {
return 'pip install debugpy';
}
// ===== Debug Configuration =====
async transformLaunchConfig(config: GenericLaunchConfig): Promise<LanguageSpecificLaunchConfig> {
const requestedConsole = (config as PythonLaunchConfig).console;
const pythonConfig: PythonLaunchConfig = {
...config,
type: 'python',
request: 'launch',
name: 'Python: Current File',
// Honor a user-supplied console mode (#215); default to internalConsole
// since this server is headless and cannot service runInTerminal requests.
console: requestedConsole ?? '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()
};
}
supportsAttach(): boolean {
return true;
}
supportsDetach(): boolean {
return true;
}
usesDirectConnectForAttach(): boolean {
return true;
}
transformAttachConfig(config: GenericAttachConfig): PythonAttachConfig {
const host = config.host || '127.0.0.1';
const port = config.port;
if (typeof port !== 'number') {
if (config.processId !== undefined || config.processName !== undefined) {
throw new AdapterError(
'Python attach does not support attaching by process ID or name. ' +
'Start the target with: python -m debugpy --listen 127.0.0.1:<port> script.py and attach to that port',
AdapterErrorCode.ENVIRONMENT_INVALID
);
}
throw new AdapterError(
'Python attach requires the port of a listening debugpy endpoint ' +
'(python -m debugpy --listen 127.0.0.1:<port> script.py)',
AdapterErrorCode.ENVIRONMENT_INVALID
);
}
const {
request: _request,
__attachMode: _attachMode,
host: _host,
port: _port,
// debugpy rejects configs carrying both `connect` and top-level
// host/port ("mutually exclusive"), so those must not leak through.
console: _console,
processId: _processId,
processName: _processName,
identifierType: _identifierType,
timeout: _timeout,
sourcePaths: _sourcePaths,
// ptvsd-era sugar; debugpy's native shape is pathMappings. Stripping
// (rather than forwarding or converting) keeps one canonical lever —
// the session layer reports adapterConfig keys dropped here (#450).
localRoot: _localRoot,
remoteRoot: _remoteRoot,
justMyCode,
stopOnEntry,
cwd,
env,
...rest
} = config as Record<string, unknown>;
void _request; void _attachMode; void _host; void _port; void _console;
void _processId; void _processName; void _identifierType; void _timeout;
void _sourcePaths; void _localRoot; void _remoteRoot;
// Advanced passthrough (pathMappings, subProcess, django, …) with the
// normalized debugpy client-connect shape on top (issue #450).
const attachConfig: PythonAttachConfig = {
...rest,
type: 'python',
request: 'attach',
name: 'Python: Attach',
// The adapter policy's spawn config reads connect.* too.
connect: { host, port },
justMyCode: (justMyCode as boolean | undefined) ?? true
};
if (stopOnEntry !== undefined) {
attachConfig.stopOnEntry = stopOnEntry as boolean;
}
if (cwd) {
attachConfig.cwd = cwd as string;
}
if (env) {
attachConfig.env = env as Record<string, string>;
}
return attachConfig;
}
getDefaultAttachConfig(): Partial<GenericAttachConfig> {
return {
request: 'attach',
host: '127.0.0.1',
justMyCode: true
};
}
// ===== 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'],
windowsHide: true
});
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: ${sanitizeStderrTail(output)}`);
}
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'],
windowsHide: true
});
let output = '';
child.stdout?.on('data', (data) => { output += data.toString(); });
child.on('error', () => resolve(false));
child.on('exit', () => {
resolve(output.trim().toLowerCase() === 'true');
});
});
}
}