session.ts•6.14 kB
import { z } from 'zod';
import { Logger } from '../server/logger';
import { MetricsCollector } from '../server/metrics';
import { SessionManager } from '../server/session-manager';
/**
* dap.session tool implementation
*
* Manages debugging sessions and provides session information
*/
export class DapSessionTool {
private logger: Logger;
private metrics: MetricsCollector;
private sessionManager: SessionManager;
constructor() {
this.logger = new Logger('dap.session');
this.metrics = MetricsCollector.getInstance();
this.sessionManager = new SessionManager();
}
/**
* Execute the dap.session tool
*/
async execute(args: any): Promise<any> {
this.metrics.startTimer('dap.session.tool');
this.metrics.increment('dap.session.count');
try {
// Validate input
const validatedArgs = this.validateArgs(args);
this.logger.debug('Managing session', {
action: validatedArgs.action,
sessionId: validatedArgs.sessionId,
});
// Handle different session actions
let result;
switch (validatedArgs.action) {
case 'initialize':
result = await this.initializeSession(validatedArgs);
break;
case 'activate':
result = await this.activateSession(validatedArgs);
break;
case 'stop':
result = await this.stopSession(validatedArgs);
break;
case 'terminate':
result = await this.terminateSession(validatedArgs);
break;
case 'info':
result = await this.getSessionInfo(validatedArgs);
break;
case 'list':
result = await this.listSessions();
break;
default:
throw new Error(`Unknown session action: ${validatedArgs.action}`);
}
this.logger.info('Session action completed', {
action: validatedArgs.action,
sessionId: validatedArgs.sessionId,
});
this.metrics.stopTimer('dap.session.tool');
return this.createSuccessResponse(result);
} catch (error) {
this.logger.error('dap.session failed:', error);
this.metrics.increment('dap.session.error.count');
this.metrics.stopTimer('dap.session.tool');
return this.createErrorResponse((error as Error).message);
}
}
/**
* Validate input arguments
*/
private validateArgs(args: any): any {
const schema = z.object({
action: z.enum(['initialize', 'activate', 'stop', 'terminate', 'info', 'list']),
sessionId: z.string().optional(),
config: z
.object({
type: z.enum(['launch', 'attach']),
program: z.string().optional(),
cwd: z.string().optional(),
args: z.array(z.string()).optional(),
noDebug: z.boolean().default(false),
sourceMaps: z.boolean().default(true),
skipFiles: z.array(z.string()).optional(),
console: z.enum(['internalConsole', 'integratedTerminal', 'externalTerminal']).optional(),
processId: z.number().optional(),
})
.optional(),
});
return schema.parse(args);
}
/**
* Initialize a new session
*/
private async initializeSession(args: any): Promise<any> {
const config = args.config || {
type: 'launch',
program: './app.js',
};
const sessionId = await this.sessionManager.initializeSession(config);
return { sessionId };
}
/**
* Activate an existing session
*/
private async activateSession(args: any): Promise<any> {
if (!args.sessionId) {
throw new Error('sessionId is required for activation');
}
await this.sessionManager.activateSession(args.sessionId, 1);
return { success: true };
}
/**
* Stop a session
*/
private async stopSession(args: any): Promise<any> {
if (!args.sessionId) {
throw new Error('sessionId is required for stopping');
}
await this.sessionManager.stopSession(args.sessionId);
return { success: true };
}
/**
* Terminate a session
*/
private async terminateSession(args: any): Promise<any> {
if (!args.sessionId) {
throw new Error('sessionId is required for termination');
}
await this.sessionManager.terminateSession(args.sessionId);
return { success: true };
}
/**
* Get session information
*/
private async getSessionInfo(args: any): Promise<any> {
if (!args.sessionId) {
throw new Error('sessionId is required for info');
}
const session = this.sessionManager.getSession(args.sessionId);
if (!session) {
throw new Error(`Session ${args.sessionId} not found`);
}
return {
sessionId: session.sessionId,
status: session.status,
startTime: session.startTime,
lastActivity: session.lastActivity,
config: session.config,
capabilities: session.capabilities,
};
}
/**
* List all sessions
*/
private async listSessions(): Promise<any> {
const sessions = this.sessionManager.getAllSessions();
const stats = this.sessionManager.getSessionStats();
return {
sessions: sessions.map(s => ({
sessionId: s.sessionId,
status: s.status,
startTime: s.startTime,
lastActivity: s.lastActivity,
config: s.config,
})),
stats,
};
}
/**
* Create success response
*/
private createSuccessResponse(body: any) {
return {
type: 'response',
seq: 1,
command: 'session',
request_seq: 1,
success: true,
body,
};
}
/**
* Create error response
*/
private createErrorResponse(message: string) {
return {
type: 'response',
seq: 1,
command: 'session',
request_seq: 1,
success: false,
message,
body: {
error: 'Failed to manage session',
format: `{message}`,
showUser: true,
},
};
}
}
// Singleton instance
export const dapSessionTool = new DapSessionTool();
// Tool execution function
export async function executeDapSession(args: any): Promise<any> {
return await dapSessionTool.execute(args);
}