-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathmock-debug-adapter.ts
More file actions
487 lines (419 loc) · 14.3 KB
/
Copy pathmock-debug-adapter.ts
File metadata and controls
487 lines (419 loc) · 14.3 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
/**
* Mock Debug Adapter implementation for testing
*
* Provides a fully functional debug adapter that simulates debugging
* without requiring external dependencies.
*
* @since 2.0.0
*/
import { EventEmitter } from 'events';
import { DebugProtocol } from '@vscode/debugprotocol';
import * as path from 'path';
import * as fs from 'fs';
import { fileURLToPath } from 'url';
import {
IDebugAdapter,
AdapterState,
ValidationResult,
DependencyInfo,
AdapterCommand,
AdapterConfig,
GenericLaunchConfig,
LanguageSpecificLaunchConfig,
DebugFeature,
FeatureRequirement,
AdapterCapabilities,
AdapterError,
AdapterErrorCode,
AdapterEvents
} from '@debugmcp/shared';
import { DebugLanguage } from '@debugmcp/shared';
import { AdapterDependencies } from '@debugmcp/shared';
/**
* Mock adapter configuration
*/
export interface MockAdapterConfig {
// Timing configuration
connectionDelay?: number; // Delay for connect operation
// Behavior configuration
supportedFeatures?: DebugFeature[]; // Which DAP features to support
}
/**
* Mock error scenarios
*/
export enum MockErrorScenario {
NONE = 'none',
EXECUTABLE_NOT_FOUND = 'executable_not_found',
CONNECTION_TIMEOUT = 'connection_timeout'
}
/**
* Valid state transitions
* Made more permissive to match real adapter behavior (e.g., Python adapter)
* Real adapters don't have strict state validation, so the mock shouldn't either
*/
const VALID_TRANSITIONS: { [key in AdapterState]?: AdapterState[] } = {
[AdapterState.UNINITIALIZED]: [
AdapterState.INITIALIZING,
AdapterState.READY, // Allow direct ready
AdapterState.CONNECTED, // Allow direct connection
AdapterState.DEBUGGING, // Allow direct debugging (matches real adapter behavior)
AdapterState.ERROR
],
[AdapterState.INITIALIZING]: [
AdapterState.READY,
AdapterState.CONNECTED, // Allow direct connection during init
AdapterState.ERROR,
AdapterState.UNINITIALIZED // Allow reset
],
[AdapterState.READY]: [
AdapterState.CONNECTED,
AdapterState.DEBUGGING, // Allow direct debugging from ready
AdapterState.DISCONNECTED, // Allow disconnection
AdapterState.ERROR,
AdapterState.UNINITIALIZED // Allow reset
],
[AdapterState.CONNECTED]: [
AdapterState.DEBUGGING,
AdapterState.CONNECTED, // Allow staying connected (idempotent)
AdapterState.DISCONNECTED,
AdapterState.READY, // Allow going back to ready
AdapterState.ERROR
],
[AdapterState.DEBUGGING]: [
AdapterState.DEBUGGING, // Allow staying in debugging (idempotent)
AdapterState.CONNECTED, // Allow going back to connected
AdapterState.DISCONNECTED,
AdapterState.READY, // Allow going back to ready
AdapterState.ERROR
],
[AdapterState.DISCONNECTED]: [
AdapterState.READY,
AdapterState.CONNECTED, // Allow reconnection
AdapterState.UNINITIALIZED, // Allow full reset
AdapterState.ERROR
],
[AdapterState.ERROR]: [
AdapterState.UNINITIALIZED,
AdapterState.READY, // Allow recovery to ready
AdapterState.DISCONNECTED // Allow recovery to disconnected
]
};
/**
* Mock debug adapter implementation
*/
export class MockDebugAdapter extends EventEmitter implements IDebugAdapter {
readonly language = DebugLanguage.MOCK;
readonly name = 'Mock Debug Adapter';
private state: AdapterState = AdapterState.UNINITIALIZED;
private config: Required<MockAdapterConfig>;
private dependencies: AdapterDependencies;
// State
private currentThreadId: number | null = null;
private connected = false;
// Error simulation
private errorScenario: MockErrorScenario = MockErrorScenario.NONE;
constructor(dependencies: AdapterDependencies, config: MockAdapterConfig = {}) {
super();
this.dependencies = dependencies;
this.config = {
connectionDelay: config.connectionDelay ?? 50,
supportedFeatures: config.supportedFeatures ?? [
DebugFeature.CONDITIONAL_BREAKPOINTS,
DebugFeature.FUNCTION_BREAKPOINTS,
DebugFeature.VARIABLE_PAGING,
DebugFeature.SET_VARIABLE
],
};
}
// ===== Lifecycle Management =====
async initialize(): Promise<void> {
this.transitionTo(AdapterState.INITIALIZING);
try {
// Validate environment
const validation = await this.validateEnvironment();
if (!validation.valid) {
this.transitionTo(AdapterState.ERROR);
throw new AdapterError(
validation.errors[0]?.message || '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.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;
const validTransitions = VALID_TRANSITIONS[oldState];
if (!validTransitions?.includes(newState)) {
throw new AdapterError(
`Invalid state transition: ${oldState} → ${newState}`,
AdapterErrorCode.UNKNOWN_ERROR
);
}
this.state = newState;
this.emit('stateChanged', oldState, newState);
}
// ===== Environment Validation =====
async validateEnvironment(): Promise<ValidationResult> {
if (this.errorScenario === MockErrorScenario.EXECUTABLE_NOT_FOUND) {
return {
valid: false,
errors: [{
code: 'MOCK_NOT_FOUND',
message: 'Mock executable not found',
recoverable: false
}],
warnings: []
};
}
// Mock adapter always validates successfully
return {
valid: true,
errors: [],
warnings: []
};
}
getRequiredDependencies(): DependencyInfo[] {
// Mock adapter has no external dependencies
return [];
}
// ===== Executable Management =====
async resolveExecutablePath(preferredPath?: string): Promise<string> {
if (preferredPath) {
return preferredPath;
}
// Use node as the mock executable
return process.execPath;
}
getDefaultExecutableName(): string {
return 'node';
}
getExecutableSearchPaths(): string[] {
return process.env.PATH?.split(path.delimiter) || [];
}
// ===== Adapter Configuration =====
buildAdapterCommand(config: AdapterConfig): AdapterCommand {
// When compiled, this will be in packages/adapter-mock/dist/
let mockAdapterPath: string;
try {
// Use fileURLToPath for correct handling of spaces, drive letters, etc.
const __filename = fileURLToPath(import.meta.url);
const currentDir = path.dirname(__filename);
mockAdapterPath = path.join(currentDir, 'mock-adapter-process.js');
// In npx bundle, the process file is bundled as mock-adapter-process.cjs
// in the same directory as cli.mjs
if (!fs.existsSync(mockAdapterPath)) {
const bundledPath = path.join(currentDir, 'mock-adapter-process.cjs');
if (fs.existsSync(bundledPath)) {
mockAdapterPath = bundledPath;
this.dependencies.logger?.debug(
`[MockDebugAdapter] Using bundled mock adapter process: ${mockAdapterPath}`
);
}
}
} catch {
// Fallback: assume we're running from the project root
// The compiled file is at packages/adapter-mock/dist/mock-adapter-process.js
const projectRoot = path.resolve(process.cwd());
mockAdapterPath = path.join(projectRoot, 'packages', 'adapter-mock', 'dist', 'mock-adapter-process.js');
this.dependencies.logger?.debug(
`[MockDebugAdapter] Using fallback path resolution: ${mockAdapterPath}`
);
}
return {
command: process.execPath,
args: [
mockAdapterPath,
'--port', config.adapterPort.toString(),
'--host', config.adapterHost,
'--session', config.sessionId
],
env: {
...process.env,
MOCK_ADAPTER_LOG: config.logDir
}
};
}
getAdapterModuleName(): string {
return 'mock-adapter';
}
getAdapterInstallCommand(): string {
return 'echo "Mock adapter is built-in"';
}
// ===== Debug Configuration =====
async transformLaunchConfig(config: GenericLaunchConfig): Promise<LanguageSpecificLaunchConfig> {
return {
...config,
type: 'mock',
request: 'launch',
name: 'Mock Debug'
};
}
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
// Mock adapter just validates the request is appropriate
this.dependencies.logger?.debug(`[MockDebugAdapter] DAP request: ${command}`, args);
// 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;
this.transitionTo(AdapterState.DEBUGGING);
} else if (event.event === 'continued') {
this.transitionTo(AdapterState.DEBUGGING);
} else if (event.event === 'terminated' || event.event === 'exited') {
this.currentThreadId = null;
if (this.connected) {
this.transitionTo(AdapterState.CONNECTED);
} else {
this.transitionTo(AdapterState.DISCONNECTED);
}
}
type AdapterEventName = Extract<keyof AdapterEvents, string | symbol>;
this.emit(event.event as AdapterEventName, event.body);
}
handleDapResponse(_response: DebugProtocol.Response): void {
// Mock adapter doesn't need special response handling
void _response; // Explicitly ignore
}
// ===== Connection Management =====
async connect(host: string, port: number): Promise<void> {
// Simulate connection delay if configured
if (this.config.connectionDelay > 0) {
await new Promise(resolve => setTimeout(resolve, this.config.connectionDelay));
}
if (this.errorScenario === MockErrorScenario.CONNECTION_TIMEOUT) {
throw new AdapterError(
'Connection timeout',
AdapterErrorCode.CONNECTION_TIMEOUT,
true
);
}
// Connection is handled by ProxyManager
// Store connection info for debugging purposes
this.dependencies.logger?.debug(`[MockDebugAdapter] 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 'The Mock Debug Adapter is built-in and requires no installation.';
}
getMissingExecutableError(): string {
return 'Mock executable not found. This should not happen with the mock adapter.';
}
translateErrorMessage(error: Error): string {
if (error.message.includes('ENOENT')) {
return 'Mock file not found: ' + error.message;
}
return error.message;
}
// ===== Feature Support =====
supportsFeature(feature: DebugFeature): boolean {
return this.config.supportedFeatures?.includes(feature) || false;
}
getFeatureRequirements(feature: DebugFeature): FeatureRequirement[] {
const requirements: FeatureRequirement[] = [];
if (feature === DebugFeature.CONDITIONAL_BREAKPOINTS) {
requirements.push({
type: 'version',
description: 'Mock adapter version 1.0+',
required: true
});
}
return requirements;
}
getCapabilities(): AdapterCapabilities {
return {
supportsConfigurationDoneRequest: true,
supportsFunctionBreakpoints: this.supportsFeature(DebugFeature.FUNCTION_BREAKPOINTS),
supportsConditionalBreakpoints: this.supportsFeature(DebugFeature.CONDITIONAL_BREAKPOINTS),
supportsHitConditionalBreakpoints: false,
supportsEvaluateForHovers: this.supportsFeature(DebugFeature.EVALUATE_FOR_HOVERS),
exceptionBreakpointFilters: [],
supportsStepBack: false,
supportsSetVariable: this.supportsFeature(DebugFeature.SET_VARIABLE),
supportsRestartFrame: false,
supportsGotoTargetsRequest: false,
supportsStepInTargetsRequest: false,
supportsCompletionsRequest: false,
supportsModulesRequest: false,
supportsRestartRequest: false,
supportsExceptionOptions: false,
supportsValueFormattingOptions: false,
supportsExceptionInfoRequest: false,
supportTerminateDebuggee: true,
supportSuspendDebuggee: false,
supportsDelayedStackTraceLoading: false,
supportsLoadedSourcesRequest: false,
supportsLogPoints: this.supportsFeature(DebugFeature.LOG_POINTS),
supportsTerminateThreadsRequest: false,
supportsSetExpression: false,
supportsTerminateRequest: true,
supportsDataBreakpoints: false,
supportsReadMemoryRequest: false,
supportsWriteMemoryRequest: false,
supportsDisassembleRequest: false,
supportsCancelRequest: false,
supportsBreakpointLocationsRequest: false,
supportsClipboardContext: false,
supportsSteppingGranularity: false,
supportsInstructionBreakpoints: false,
supportsExceptionFilterOptions: false,
supportsSingleThreadExecutionRequests: false
};
}
// ===== Mock-specific methods =====
/**
* Set error scenario for testing
*/
setErrorScenario(scenario: MockErrorScenario): void {
this.errorScenario = scenario;
}
}