-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathproxy-manager.ts
More file actions
1061 lines (919 loc) · 35.7 KB
/
Copy pathproxy-manager.ts
File metadata and controls
1061 lines (919 loc) · 35.7 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
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
/**
* ProxyManager - Handles spawning and communication with debug proxy processes
*/
import { EventEmitter } from 'events';
import { DebugProtocol } from '@vscode/debugprotocol';
import { v4 as uuidv4 } from 'uuid';
import path from 'path';
import { fileURLToPath } from 'url';
import {
IFileSystem,
ILogger
} from '@debugmcp/shared';
import { IProxyProcessLauncher, IProxyProcess } from '@debugmcp/shared';
import {
createInitialState,
handleProxyMessage,
isValidProxyMessage,
DAPSessionState,
addPendingRequest,
removePendingRequest,
clearPendingRequests
} from '../dap-core/index.js';
import type {
ProxyStatusMessage,
ProxyDapEventMessage,
ProxyDapResponseMessage,
ProxyMessage
} from '../dap-core/types.js';
import { ErrorMessages } from '../utils/error-messages.js';
import { sanitizePayloadForLogging, sanitizeStderr } from '../utils/env-sanitizer.js';
import { ProxyConfig } from './proxy-config.js';
import { IDebugAdapter, AdapterLaunchBarrier } from '@debugmcp/shared';
/**
* Events emitted by ProxyManager
*/
export interface ProxyManagerEvents {
// DAP events
'stopped': (threadId: number | undefined, reason: string, data?: DebugProtocol.StoppedEvent['body']) => void;
'continued': () => void;
'terminated': () => void;
'exited': () => void;
// Proxy lifecycle events
'initialized': () => void;
'init-received': () => void;
'error': (error: Error) => void;
'exit': (code: number | null, signal?: string) => void;
// Status events
'dry-run-complete': (command: string, script: string) => void;
'adapter-configured': () => void;
'dap-event': (event: string, body: unknown) => void;
}
/**
* Interface for proxy managers
*/
export interface IProxyManager extends EventEmitter {
start(config: ProxyConfig): Promise<void>;
stop(): Promise<void>;
sendDapRequest<T extends DebugProtocol.Response>(
command: string,
args?: unknown
): Promise<T>;
isRunning(): boolean;
getCurrentThreadId(): number | null;
setCurrentThreadId(threadId: number): void;
// Typed event emitter methods
on<K extends keyof ProxyManagerEvents>(
event: K,
listener: ProxyManagerEvents[K]
): this;
emit<K extends keyof ProxyManagerEvents>(
event: K,
...args: Parameters<ProxyManagerEvents[K]>
): boolean;
hasDryRunCompleted(): boolean;
getDryRunSnapshot(): { command?: string; script?: string } | undefined;
}
interface ProxyRuntimeEnvironment {
moduleUrl: string;
cwd: () => string;
}
const DEFAULT_RUNTIME_ENVIRONMENT: ProxyRuntimeEnvironment = {
moduleUrl: import.meta.url,
cwd: () => process.cwd()
};
/**
* Concrete implementation of ProxyManager
*/
export class ProxyManager extends EventEmitter implements IProxyManager {
private proxyProcess: IProxyProcess | null = null;
private sessionId: string | null = null;
private currentThreadId: number | null = null;
private pendingDapRequests = new Map<string, {
resolve: (response: DebugProtocol.Response) => void;
reject: (error: Error) => void;
command: string;
}>();
private isInitialized = false;
private isStopped = false;
private isDryRun = false;
private dryRunCompleteReceived = false;
private dryRunCommandSnapshot?: string;
private dryRunScriptPath?: string;
private adapterConfigured = false;
private dapState: DAPSessionState | null = null;
private stderrBuffer: string[] = [];
private lastExitDetails:
| {
code: number | null;
signal: string | null;
timestamp: number;
capturedStderr: string[];
}
| undefined;
private readonly runtimeEnv: ProxyRuntimeEnvironment;
private activeLaunchBarrier: AdapterLaunchBarrier | null = null;
private activeLaunchBarrierRequestId: string | null = null;
private proxyMessageCounter = 0;
private exitEmitted = false;
constructor(
private adapter: IDebugAdapter | null, // Optional adapter for language-agnostic support
private proxyProcessLauncher: IProxyProcessLauncher,
private fileSystem: IFileSystem,
private logger: ILogger,
runtimeEnv: ProxyRuntimeEnvironment = DEFAULT_RUNTIME_ENVIRONMENT
) {
super();
this.runtimeEnv = runtimeEnv;
// Safety handler: prevents Node.js from throwing when 'error' is emitted
// after all named listeners have been removed (e.g., late IPC messages from
// a child process that hasn't fully exited yet).
this.on('error', () => {});
}
async start(config: ProxyConfig): Promise<void> {
if (this.proxyProcess) {
throw new Error('Proxy already running');
}
this.sessionId = config.sessionId;
this.isStopped = false;
this.isDryRun = config.dryRunSpawn === true;
this.dryRunCompleteReceived = false;
this.dryRunCommandSnapshot = undefined;
this.dryRunScriptPath = config.scriptPath;
this.lastExitDetails = undefined;
if (config.adapterCommand?.command) {
const parts = [config.adapterCommand.command, ...(config.adapterCommand.args ?? [])]
.filter((part) => typeof part === 'string' && part.length > 0);
if (parts.length > 0) {
this.dryRunCommandSnapshot = parts.join(' ');
}
} else if (!this.dryRunCommandSnapshot && config.executablePath) {
this.dryRunCommandSnapshot = config.executablePath;
}
// Initialize functional core state
this.dapState = createInitialState(config.sessionId);
const { executablePath, proxyScriptPath, env } = await this.prepareSpawnContext(config);
this.logger.info(`[ProxyManager] Spawning proxy for session ${config.sessionId}. Path: ${proxyScriptPath}`);
try {
this.proxyProcess = this.proxyProcessLauncher.launchProxy(
proxyScriptPath,
config.sessionId,
env
);
} catch (error) {
this.logger.error(`[ProxyManager] Failed to spawn proxy:`, error);
throw error;
}
if (!this.proxyProcess || typeof this.proxyProcess.pid === 'undefined') {
throw new Error('Proxy process is invalid or PID is missing');
}
this.logger.info(`[ProxyManager] Proxy spawned with PID: ${this.proxyProcess.pid}`);
// Set up event handlers
this.setupEventHandlers();
// Wait a brief moment for the process to start before sending init
await new Promise(resolve => setTimeout(resolve, 50));
// Send initialization command with retry logic
const initCommand = {
cmd: 'init',
sessionId: config.sessionId,
executablePath: executablePath, // Using resolved executable path
adapterHost: config.adapterHost,
adapterPort: config.adapterPort,
logDir: config.logDir,
scriptPath: config.scriptPath,
scriptArgs: config.scriptArgs,
stopOnEntry: config.stopOnEntry,
justMyCode: config.justMyCode,
initialBreakpoints: config.initialBreakpoints,
dryRunSpawn: config.dryRunSpawn,
launchConfig: config.launchConfig,
// Pass adapter command info for language-agnostic adapter spawning
adapterCommand: config.adapterCommand
};
// Debug log the command being sent
this.logger.info(`[ProxyManager] Sending init command with adapterCommand:`, {
hasAdapterCommand: !!config.adapterCommand,
adapterCommand: config.adapterCommand ? {
command: config.adapterCommand.command,
args: config.adapterCommand.args,
hasEnv: !!config.adapterCommand.env
} : null
});
// Send init command with retry logic
await this.sendInitWithRetry(initCommand);
// Wait for initialization or dry run completion
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error(ErrorMessages.proxyInitTimeout(30)));
}, 30000);
const cleanup = () => {
clearTimeout(timeout);
this.removeListener('initialized', handleInitialized);
this.removeListener('dry-run-complete', handleDryRun);
this.removeListener('error', handleError);
this.removeListener('exit', handleExit);
};
const handleInitialized = () => {
this.isInitialized = true;
cleanup();
resolve();
};
const handleDryRun = () => {
cleanup();
resolve();
};
const handleError = (error: Error) => {
cleanup();
reject(error);
};
const handleExit = (code: number | null, signal?: string) => {
cleanup();
if (this.isDryRun && code === 0) {
// Normal exit for dry run
resolve();
} else {
let errorMessage = `Proxy exited during initialization. Code: ${code}, Signal: ${signal}`;
if (this.stderrBuffer.length > 0) {
errorMessage += `\nStderr output:\n${this.stderrBuffer.join('\n')}`;
}
reject(new Error(errorMessage));
}
};
this.once('initialized', handleInitialized);
this.once('dry-run-complete', handleDryRun);
this.once('error', handleError);
this.once('exit', handleExit);
});
}
async stop(): Promise<void> {
if (!this.proxyProcess) {
// No proxy process, but still dispose adapter to release instance slot
this.cleanup();
return;
}
this.logger.info(`[ProxyManager] Stopping proxy for session ${this.sessionId}`);
// Mark as shutting down to stop processing new messages
this.isStopped = true;
const process = this.proxyProcess;
const sessionIdSnapshot = this.sessionId;
// Immediately cleanup to prevent "unknown request" warnings
this.cleanup();
// Send terminate command if process is still running
try {
if (!process.killed) {
process.send({ cmd: 'terminate', sessionId: sessionIdSnapshot });
}
} catch (error) {
this.logger.error(`[ProxyManager] Error sending terminate command:`, error);
}
// Wait for graceful exit or force kill after timeout
return new Promise((resolve) => {
const timeout = setTimeout(() => {
this.logger.warn(`[ProxyManager] Timeout waiting for proxy exit. Force killing.`);
if (!process.killed) {
process.kill('SIGKILL');
}
resolve();
}, 5000);
process.once('exit', () => {
clearTimeout(timeout);
resolve();
});
// If already killed/exited, resolve immediately
if (process.killed || process.exitCode !== null) {
clearTimeout(timeout);
resolve();
}
});
}
async sendDapRequest<T extends DebugProtocol.Response>(
command: string,
args?: unknown
): Promise<T> {
if (!this.proxyProcess || !this.isInitialized) {
throw new Error('Proxy not initialized');
}
const barrier = this.adapter?.createLaunchBarrier?.(command, args);
const requestId = uuidv4();
const commandToSend = {
cmd: 'dap',
sessionId: this.sessionId,
requestId,
dapCommand: command,
dapArgs: args
};
if (barrier && !barrier.awaitResponse) {
this.logger.info(
`[ProxyManager] Sending DAP command with adapter barrier (fire-and-forget): ${command}, requestId: ${requestId}`
);
this.setActiveLaunchBarrier(barrier, requestId);
barrier.onRequestSent(requestId);
try {
this.sendCommand(commandToSend);
} catch (error) {
this.clearActiveLaunchBarrier(barrier);
throw error;
}
try {
await barrier.waitUntilReady();
return {} as T;
} finally {
this.clearActiveLaunchBarrier(barrier);
}
}
this.logger.info(`[ProxyManager] Sending DAP command: ${command}, requestId: ${requestId}`);
if (barrier) {
this.setActiveLaunchBarrier(barrier, requestId);
barrier.onRequestSent(requestId);
}
return new Promise<T>((resolve, reject) => {
this.pendingDapRequests.set(requestId, {
resolve: resolve as (value: DebugProtocol.Response) => void,
reject,
command
});
// Mirror into functional core for observability (seq is placeholder; ProxyManager remains authoritative)
if (this.dapState) {
this.dapState = addPendingRequest(this.dapState, {
requestId,
command,
seq: 0,
timestamp: Date.now()
});
}
try {
this.sendCommand(commandToSend);
} catch (error) {
this.pendingDapRequests.delete(requestId);
if (barrier) {
this.clearActiveLaunchBarrier(barrier);
}
reject(error);
}
// Timeout handler
setTimeout(() => {
if (this.pendingDapRequests.has(requestId)) {
this.pendingDapRequests.delete(requestId);
if (this.dapState) {
this.dapState = removePendingRequest(this.dapState, requestId);
}
if (this.activeLaunchBarrier && this.activeLaunchBarrierRequestId === requestId) {
this.clearActiveLaunchBarrier();
}
reject(new Error(ErrorMessages.dapRequestTimeout(command, 35)));
}
}, 35000);
});
}
isRunning(): boolean {
return this.proxyProcess !== null && !this.proxyProcess.killed;
}
getCurrentThreadId(): number | null {
return this.currentThreadId;
}
setCurrentThreadId(threadId: number): void {
this.currentThreadId = threadId;
}
private async prepareSpawnContext(config: ProxyConfig): Promise<{
executablePath: string;
proxyScriptPath: string;
env: Record<string, string>;
}> {
let executablePath = config.executablePath;
if (this.adapter) {
const validation = await this.adapter.validateEnvironment();
if (!validation.valid) {
throw new Error(
`Invalid environment for ${this.adapter.language}: ${validation.errors[0].message}`
);
}
if (!executablePath) {
executablePath = await this.adapter.resolveExecutablePath();
this.logger.info(`[ProxyManager] Adapter resolved executable path: ${executablePath}`);
}
} else if (!executablePath) {
throw new Error('No executable path provided and no adapter available to resolve it');
}
const proxyScriptPath = await this.findProxyScript();
if (!executablePath) {
throw new Error('Executable path could not be determined after validation');
}
const env = this.cloneProcessEnv();
return {
executablePath,
proxyScriptPath,
env
};
}
private cloneProcessEnv(): Record<string, string> {
const env: Record<string, string> = {};
for (const [key, value] of Object.entries(process.env)) {
if (value !== undefined) {
env[key] = value;
}
}
return env;
}
private async findProxyScript(): Promise<string> {
const modulePath = fileURLToPath(this.runtimeEnv.moduleUrl);
const moduleDir = path.dirname(modulePath);
const dirParts = moduleDir.split(path.sep);
const cwd = this.runtimeEnv.cwd();
const lastPart = dirParts[dirParts.length - 1];
const secondLast = dirParts[dirParts.length - 2];
let distPath: string;
if (lastPart === 'dist') {
distPath = path.join(moduleDir, 'proxy', 'proxy-bootstrap.js');
} else if (lastPart === 'proxy' && secondLast === 'dist') {
distPath = path.join(moduleDir, 'proxy-bootstrap.js');
} else {
// Fallback to development layout
distPath = path.resolve(moduleDir, '../../dist/proxy/proxy-bootstrap.js');
}
this.logger.info(`[ProxyManager] Checking for proxy script at: ${distPath}`);
if (!(await this.fileSystem.pathExists(distPath))) {
throw new Error(
`Bootstrap worker script not found at: ${distPath}\n` +
`Module directory: ${moduleDir}\n` +
`Current working directory: ${cwd}\n` +
`This usually means:\n` +
` 1. You need to run 'npm run build' first\n` +
` 2. The build failed to copy proxy files\n` +
` 3. The TypeScript compilation structure is unexpected`
);
}
return distPath;
}
private async sendInitWithRetry(initCommand: object): Promise<void> {
const maxRetries = 5;
const delays = [500, 1000, 2000, 4000, 8000]; // More generous backoff for Windows CI
let lastError: Error | undefined;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
const timeoutMs = delays[Math.min(attempt, delays.length - 1)];
try {
const received = await new Promise<boolean>((resolve, reject) => {
let resolved = false;
const handler = () => {
if (resolved) return;
resolved = true;
if (timer) clearTimeout(timer);
resolve(true);
};
const cleanup = () => {
this.removeListener('init-received', handler);
if (timer) clearTimeout(timer);
};
this.on('init-received', handler);
const timer = setTimeout(() => {
if (resolved) return;
resolved = true;
this.removeListener('init-received', handler);
resolve(false);
}, timeoutMs);
try {
this.sendCommand(initCommand);
} catch (error) {
cleanup();
reject(error);
}
});
if (received) {
this.logger.info(`[ProxyManager] Init command acknowledged on attempt ${attempt + 1}`);
return;
}
this.logger.warn(
`[ProxyManager] Init not acknowledged, attempt ${attempt + 1}/${maxRetries + 1}`
);
} catch (error) {
lastError = error as Error;
this.logger.warn(
`[ProxyManager] Error sending init on attempt ${attempt + 1}: ${lastError.message}`
);
}
if (attempt < maxRetries) {
const waitMs = delays[Math.min(attempt, delays.length - 1)];
await new Promise((resolve) => setTimeout(resolve, waitMs));
}
}
let detailMessage = `Failed to initialize proxy after ${maxRetries + 1} attempts. ${
lastError ? `Last error: ${lastError.message}` : 'Init command not acknowledged'
}`;
if (this.lastExitDetails) {
const { code, signal, capturedStderr } = this.lastExitDetails;
const stderrSnippet = capturedStderr.length
? capturedStderr.slice(-10).join('\n')
: '<<no stderr captured>>';
detailMessage += ` Proxy exit details -> code=${code} signal=${signal} stderr:\n${stderrSnippet}`;
}
throw new Error(detailMessage);
}
private sendCommand(command: object): void {
if (!this.proxyProcess || this.proxyProcess.killed) {
if (this.lastExitDetails) {
this.logger.error(
`[ProxyManager] Attempted to send command after proxy unavailable. Last exit -> code=${this.lastExitDetails.code} signal=${this.lastExitDetails.signal}`,
this.lastExitDetails.capturedStderr
);
} else {
this.logger.error('[ProxyManager] Attempted to send command but proxy process is not available (no exit details recorded).');
}
throw new Error('Proxy process not available');
}
const rawChild =
(this.proxyProcess as unknown as { childProcess?: { connected?: boolean; pid?: number; killed?: boolean } })
.childProcess;
const requestId = (command as { requestId?: string }).requestId;
const cmd = (command as { cmd?: string }).cmd;
const dapCommand = (command as { dapCommand?: string }).dapCommand;
const connectedBefore =
rawChild && typeof rawChild.connected === 'boolean' ? rawChild.connected : undefined;
const childPid = rawChild?.pid;
this.logger.debug(
`[ProxyManager] IPC pre-send pid=${childPid ?? 'unknown'} connected=${connectedBefore} cmd=${cmd}${
dapCommand ? `/${dapCommand}` : ''
} requestId=${requestId ?? 'n/a'}`
);
this.logger.info(`[ProxyManager] Sending command to proxy: ${JSON.stringify(sanitizePayloadForLogging(command)).substring(0, 500)}`);
try {
this.proxyProcess.sendCommand(command);
this.logger.info(`[ProxyManager] Command dispatched via proxy process`);
const connectedAfter =
rawChild && typeof rawChild.connected === 'boolean' ? rawChild.connected : undefined;
this.logger.debug(
`[ProxyManager] IPC post-send pid=${childPid ?? 'unknown'} connected=${connectedAfter} cmd=${cmd}${
dapCommand ? `/${dapCommand}` : ''
} requestId=${requestId ?? 'n/a'}`
);
} catch (error) {
const connectedAfter =
rawChild && typeof rawChild.connected === 'boolean' ? rawChild.connected : undefined;
this.logger.error(
`[ProxyManager] Failed to send command (pid=${childPid ?? 'unknown'} connected=${connectedAfter} cmd=${cmd}${
dapCommand ? `/${dapCommand}` : ''
} requestId=${requestId ?? 'n/a'})`,
error
);
throw error;
}
}
private setupEventHandlers(): void {
if (!this.proxyProcess) return;
// Handle IPC messages
this.proxyProcess.on('message', (rawMessage: unknown) => {
this.handleProxyMessage(rawMessage);
});
this.proxyProcess.on('ipc-send-start', (data: { pid?: number; connectedBefore?: boolean; summary?: string; timestamp?: number }) => {
this.logger.debug(
`[ProxyManager] IPC send start pid=${data?.pid ?? 'unknown'} connected=${data?.connectedBefore} summary=${data?.summary ?? 'n/a'}`
);
});
this.proxyProcess.on('ipc-send-complete', (data: { pid?: number; connectedAfter?: boolean; summary?: string; timestamp?: number; queueSizeBefore?: number; queueSizeAfter?: number }) => {
this.logger.debug(
`[ProxyManager] IPC send complete pid=${data?.pid ?? 'unknown'} connected=${data?.connectedAfter} summary=${data?.summary ?? 'n/a'} queueBefore=${data?.queueSizeBefore ?? 'n/a'} queueAfter=${data?.queueSizeAfter ?? 'n/a'}`
);
});
this.proxyProcess.on('ipc-send-failed', (data: { pid?: number; killed?: boolean; childProcessKilled?: boolean | string; summary?: string; timestamp?: number }) => {
this.logger.warn(
`[ProxyManager] IPC send returned false pid=${data?.pid ?? 'unknown'} killed=${data?.killed} childKilled=${data?.childProcessKilled} summary=${data?.summary ?? 'n/a'}`
);
});
this.proxyProcess.on('ipc-send-error', (data: { pid?: number; error?: string; summary?: string; timestamp?: number }) => {
this.logger.error(
`[ProxyManager] IPC send error pid=${data?.pid ?? 'unknown'} error=${data?.error ?? 'unknown'} summary=${data?.summary ?? 'n/a'}`
);
});
// Handle stderr
this.proxyProcess.stderr?.on('data', (data: Buffer | string) => {
const output = data.toString().trim();
// Sanitize before logging and storing — stderr may contain env vars
const sanitizedLines = sanitizeStderr([output]);
this.logger.error(`[ProxyManager STDERR] ${sanitizedLines[0]}`);
// Capture sanitized stderr for error reporting during initialization
if (!this.isInitialized) {
this.stderrBuffer.push(sanitizedLines[0]);
}
});
// Handle exit
this.proxyProcess.on('exit', (code: number | null, signal: string | null) => {
this.logger.info(`[ProxyManager] Proxy exited. Code: ${code}, Signal: ${signal}`);
this.lastExitDetails = {
code,
signal,
timestamp: Date.now(),
capturedStderr: [...this.stderrBuffer],
};
if (!this.isInitialized) {
this.logger.error(
`[ProxyManager] Proxy exited before initialization. code=${code} signal=${signal} stderrLines=${this.stderrBuffer.length}`,
this.stderrBuffer
);
}
this.handleProxyExit(code, signal);
});
// Handle errors
this.proxyProcess.on('error', (err: Error) => {
this.logger.error(`[ProxyManager] Proxy error:`, err);
this.emit('error', err);
this.cleanup();
});
}
private handleProxyMessage(rawMessage: unknown): void {
// Skip all message processing after stop() to prevent emitting events with no listeners
if (this.isStopped) {
this.logger.debug(`[ProxyManager] Ignoring late message after stop (session ${this.sessionId})`);
return;
}
if ((rawMessage as { type?: string })?.type === 'ipc-heartbeat') {
const heartbeat = rawMessage as { counter?: number; timestamp?: number };
this.logger.debug(
`[ProxyManager] Received worker heartbeat counter=${heartbeat.counter ?? 'n/a'} timestamp=${heartbeat.timestamp ?? 'n/a'}`
);
return;
}
if ((rawMessage as { type?: string })?.type === 'ipc-heartbeat-tick') {
const heartbeatTick = rawMessage as { timestamp?: number };
this.logger.debug(
`[ProxyManager] Received worker heartbeat tick timestamp=${heartbeatTick.timestamp ?? 'n/a'}`
);
return;
}
this.proxyMessageCounter += 1;
this.logger.debug(
`[ProxyManager] Received message #${this.proxyMessageCounter}:`,
rawMessage
);
// Validate message format
if (!isValidProxyMessage(rawMessage)) {
this.logger.warn(`[ProxyManager] Invalid message format:`, rawMessage);
return;
}
const message = rawMessage as ProxyMessage;
// Fast-path: always forward DAP events to consumers to avoid missing stops/output
if (message.type === 'dapEvent') {
this.handleDapEvent(message as ProxyDapEventMessage);
}
// Handle status messages
if (message.type === 'status') {
this.handleStatusMessage(message as ProxyStatusMessage);
}
// Use functional core if state is initialized
if (this.dapState) {
const result = handleProxyMessage(this.dapState, message);
// Execute commands from functional core
for (const command of result.commands) {
switch (command.type) {
case 'log':
this.logger[command.level](command.message, command.data);
break;
case 'emitEvent':
{
// Skip emitEvent commands for DAP events — they are already handled
// by the fast-path handleDapEvent() call above to avoid double emission.
if (message.type === 'dapEvent') break;
const args = (command.args as unknown[]) ?? [];
this.emit(command.event as keyof ProxyManagerEvents, ...(args as never[]));
}
break;
case 'killProcess':
this.proxyProcess?.kill();
break;
case 'sendToProxy':
this.sendCommand(command.command);
break;
// Note: sendToClient is not used in ProxyManager context
}
}
// Update state if changed
if (result.newState) {
this.dapState = result.newState;
// Sync local state with functional core state
this.isInitialized = result.newState.initialized;
this.adapterConfigured = result.newState.adapterConfigured;
// Only update currentThreadId if the core provided a concrete number.
// Avoid overwriting the value we set in the fast-path dapEvent handler with null/undefined.
const coreTid = (result.newState as { currentThreadId?: number | null }).currentThreadId;
if (typeof coreTid === 'number') {
this.currentThreadId = coreTid;
}
}
// Resolve/reject pending DAP request Promises. The functional core above only
// tracks state; response resolution remains imperative because it involves
// Promise callbacks that cannot be expressed as pure commands.
if (message.type === 'dapResponse') {
this.handleDapResponse(message as ProxyDapResponseMessage);
}
} else {
// Fallback if state not initialized (shouldn't happen)
this.logger.error(`[ProxyManager] DAP state not initialized`);
}
}
private handleDapResponse(message: ProxyDapResponseMessage): void {
const pending = this.pendingDapRequests.get(message.requestId);
if (!pending) {
// During shutdown, it's normal to receive responses for requests that were cancelled
if (this.proxyProcess) {
this.logger.debug(`[ProxyManager] Received response for unknown/cancelled request: ${message.requestId}`);
}
return;
}
this.pendingDapRequests.delete(message.requestId);
// Mirror completion into functional core
if (this.dapState) {
this.dapState = removePendingRequest(this.dapState, message.requestId);
}
if (this.activeLaunchBarrier && this.activeLaunchBarrierRequestId === message.requestId) {
this.clearActiveLaunchBarrier();
}
if (message.success) {
// If this was a 'threads' response, opportunistically capture a usable thread id
try {
if (pending.command === 'threads') {
const resp = (message.response || message.body) as DebugProtocol.ThreadsResponse | undefined;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const threads = (resp && (resp as any).body && Array.isArray((resp as any).body.threads)) ? (resp as any).body.threads : [];
const first = threads.length ? threads[0]?.id : undefined;
if (typeof first === 'number') {
this.currentThreadId = first;
}
}
} catch {
// ignore capture errors
}
pending.resolve((message.response || message.body) as DebugProtocol.Response);
} else {
pending.reject(new Error(message.error || `DAP request '${pending.command}' failed`));
}
}
private handleDapEvent(message: ProxyDapEventMessage): void {
this.activeLaunchBarrier?.onDapEvent(
message.event,
message.body as DebugProtocol.Event['body'] | undefined
);
this.logger.info(`[ProxyManager] DAP event: ${message.event}`, message.body);
switch (message.event) {
case 'stopped':
const stoppedBody = message.body as { threadId?: number; reason?: string } | undefined;
const threadIdMaybe = (typeof stoppedBody?.threadId === 'number') ? stoppedBody!.threadId! : undefined;
const reason = stoppedBody?.reason || 'unknown';
if (typeof threadIdMaybe === 'number') {
this.currentThreadId = threadIdMaybe;
}
// Do not fabricate a threadId; emit undefined if adapter omitted it
this.emit('stopped', threadIdMaybe, reason, stoppedBody as DebugProtocol.StoppedEvent['body']);
break;
case 'continued':
this.emit('continued');
break;
case 'terminated':
this.emit('terminated');
break;
case 'exited':
this.emit('exited');
break;
// Forward other events as generic DAP events
default:
this.emit('dap-event', message.event, message.body);
}
}
private handleStatusMessage(message: ProxyStatusMessage): void {
this.activeLaunchBarrier?.onProxyStatus(message.status, message);
switch (message.status) {
case 'proxy_minimal_ran_ipc_test':
this.logger.info(`[ProxyManager] IPC test message received`);
this.proxyProcess?.kill();
break;
case 'init_received':
this.logger.info(`[ProxyManager] Init command acknowledged by proxy`);
this.emit('init-received');
break;
case 'dry_run_complete':
this.logger.info(`[ProxyManager] Dry run complete`);
this.dryRunCompleteReceived = true;
if (typeof message.command === 'string' && message.command.trim().length > 0) {
this.dryRunCommandSnapshot = message.command;
}
if (typeof message.script === 'string' && message.script.trim().length > 0) {
this.dryRunScriptPath = message.script;
}
this.emit('dry-run-complete', message.command, message.script);
break;
case 'adapter_configured_and_launched':
this.logger.info(`[ProxyManager] Adapter configured and launched`);
this.adapterConfigured = true;
this.emit('adapter-configured');
if (!this.isInitialized) {
this.isInitialized = true;
this.emit('initialized');
}
break;
case 'adapter_connected':
// Adapter transport is up; allow client to proceed with DAP handshake.
this.logger.info(`[ProxyManager] Adapter transport connected. Marking initialized to unblock client handshake.`);
if (!this.isInitialized) {
this.isInitialized = true;
this.emit('initialized');
}
break;
case 'adapter_exited':
case 'dap_connection_closed':
case 'terminated':
this.logger.info(`[ProxyManager] Status: ${message.status}`);
if (!this.exitEmitted) {
this.exitEmitted = true;
this.emit('exit', message.code ?? 1, message.signal || undefined);
}
break;
}
}
private handleProxyExit(code: number | null, signal: string | null): void {
this.activeLaunchBarrier?.onProxyExit(code, signal);
this.clearActiveLaunchBarrier();
if (this.isDryRun && code === 0 && !this.dryRunCompleteReceived) {
const fallbackCommand = this.dryRunCommandSnapshot ?? '(command unavailable)';
const fallbackScript = this.dryRunScriptPath ?? '';
this.logger.warn(
`[ProxyManager] Dry run proxy exited without reporting completion; synthesizing dry-run-complete event.`
);
this.dryRunCompleteReceived = true;
this.dryRunCommandSnapshot = fallbackCommand;
this.dryRunScriptPath = fallbackScript;
this.emit('dry-run-complete', fallbackCommand, fallbackScript);
}
// Clean up pending requests
this.pendingDapRequests.forEach(pending => {
pending.reject(new Error('Proxy exited'));
});
this.pendingDapRequests.clear();
// Emit exit event
if (!this.exitEmitted) {
this.exitEmitted = true;
this.emit('exit', code, signal || undefined);
}
// Clean up
this.cleanup();
}
private cleanup(): void {
// Clear pending DAP requests to avoid "unknown request" warnings during shutdown
if (this.pendingDapRequests.size > 0) {
this.logger.debug(`[ProxyManager] Clearing ${this.pendingDapRequests.size} pending DAP requests during cleanup`);
for (const pending of this.pendingDapRequests.values()) {
pending.reject(new Error(`Request cancelled during proxy shutdown: ${pending.command}`));
}
this.pendingDapRequests.clear();
}
// Clear functional core mirror
if (this.dapState) {