-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathproxy-manager.ts
More file actions
1461 lines (1302 loc) · 55.1 KB
/
Copy pathproxy-manager.ts
File metadata and controls
1461 lines (1302 loc) · 55.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
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,
setCurrentThreadId as setCoreCurrentThreadId
} from '../dap-core/index.js';
import type {
ProxyStatusMessage,
ProxyDapEventMessage,
ProxyDapResponseMessage,
ProxyMessage
} from '../dap-core/types.js';
import { ErrorMessages, ProxyInitProgress } from '../utils/error-messages.js';
import { ProxyConfig } from './proxy-config.js';
import type { BreakpointSyncResult, FunctionBreakpointSyncResult } from './dap-proxy-interfaces.js';
import { IPC_HEARTBEAT, IPC_HEARTBEAT_TICK } from './dap-proxy-interfaces.js';
import {
IDebugAdapter,
AdapterLaunchBarrier,
sanitizePayloadForLogging,
sanitizeStderr,
LineBuffer
} 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': (exitCode?: number) => void;
'output': (body: DebugProtocol.OutputEvent['body']) => void;
/** Deferred breakpoint verification / relocation pushed by the adapter (issue #236) */
'breakpoint': (body: DebugProtocol.BreakpointEvent['body']) => void;
// Proxy lifecycle events
'initialized': () => void;
'init-received': () => void;
'error': (error: Error) => void;
/**
* Proxy or adapter teardown. `expected` is set on status-driven exits
* (issue #258): true = the worker saw orderly debuggee termination first;
* false = the adapter died or dropped the socket mid-run; undefined = the
* proxy process itself exited (legacy path).
*/
'exit': (code: number | null, signal?: string, expected?: boolean) => void;
// Status events
'dry-run-complete': (command: string, script: string) => void;
'adapter-configured': () => void;
/** Adapter initialize response body captured by the worker (issue #243) */
'adapter-capabilities': (capabilities: DebugProtocol.Capabilities) => void;
/** Pre-launch setFunctionBreakpoints results from the worker (issue #302) */
'function-breakpoints-synced': (results: FunctionBreakpointSyncResult[]) => void;
/** Pre-launch setBreakpoints results from the worker (issue #439) */
'breakpoints-synced': (results: BreakpointSyncResult[]) => 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,
options?: { timeoutMs?: number }
): Promise<T>;
isRunning(): boolean;
/**
* OS pid of the proxy worker this manager spawned (null before the first
* successful spawn). Survives stop()/cleanup(), so callers can verify after
* teardown that the worker actually died (issue #502).
*/
getProxyPid(): number | null;
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;
}
/** Minimal emitter surface shared by IProxyProcess and its stderr stream. */
interface RemovableEmitter {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
on(event: string, listener: (...args: any[]) => void): unknown;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
removeListener(event: string, listener: (...args: any[]) => void): unknown;
}
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;
// Worker OS pid, retained across cleanup() (which nulls proxyProcess) so
// callers can verify after teardown that the worker actually died — the
// leaked-worker case had no post-hoc handle at any layer (issue #502).
private lastProxyPid: number | 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;
/** Parent-side backstop timer; must be cleared wherever the entry settles (issue #420). */
timer?: NodeJS.Timeout;
}>();
private isInitialized = false;
// Never reset by cleanup(): stop() runs cleanup() before the process 'exit'
// event arrives, so isInitialized alone cannot distinguish a genuine
// pre-init death from the exit that follows every normal stop (issue #530)
private everInitialized = false;
private isStopped = false;
/** Bounded wait for in-flight DAP requests to settle before stop() cancels them. */
private stopDrainTimeoutMs = 1000;
/** Worker-side DAP request timeout assumed when no per-request override is given. */
private defaultDapRequestTimeoutMs = 30000;
/**
* Extra time the parent waits beyond the worker/socket timeout so the
* worker's own timeout (which produces the actionable error) fires first.
*/
private dapParentMarginMs = 5000;
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;
/**
* How far worker-side initialization got, from the worker's progress
* statuses (adapter_spawned / dap_handshake_stage). Read only when the init
* deadline fires, to say what actually stalled instead of blaming adapter
* installation (issue #493).
*/
private initProgress: ProxyInitProgress = { transportConnected: false };
/**
* Listeners installed on the proxy process (and its stderr stream) by
* setupEventHandlers, tracked so a failed start() can detach them — a stale
* process driving handleProxyExit after start() already rejected would fire
* rejections with nobody listening (issue #420).
*/
private trackedProxyListeners: Array<{
emitter: RemovableEmitter;
event: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
listener: (...args: any[]) => void;
}> = [];
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.lastProxyPid = null;
// The latch tracks the process this start() launches (issue #530)
this.everInitialized = 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') {
// Clear the handle so this manager is not permanently stuck on the
// 'Proxy already running' guard above (issue #420).
this.proxyProcess = null;
throw new Error('Proxy process is invalid or PID is missing');
}
this.lastProxyPid = this.proxyProcess.pid ?? null;
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,
language: config.language,
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,
initialFunctionBreakpoints: config.initialFunctionBreakpoints,
dryRunSpawn: config.dryRunSpawn,
logLevel: config.logLevel,
breakOnExceptions: config.breakOnExceptions,
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
});
// From here on, any failure must detach the listeners just installed on
// the proxy process: start()'s caller discards this manager on failure,
// and a stale process handle still wired to handleProxyExit would reject
// pending requests into a void (issue #420).
try {
await this.startInitializationSequence(initCommand);
} catch (error) {
this.detachProxyEventHandlers();
throw error;
}
}
/** Send init (with retry) and await readiness; extracted so start() can detach on any failure. */
private async startInitializationSequence(initCommand: object): Promise<void> {
// 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(() => {
cleanup();
const error = new Error(ErrorMessages.proxyInitTimeout(30, this.initProgress)) as Error & {
initProgress?: ProxyInitProgress;
};
// Structured copy of the facts behind the message, for the tool
// result's error payload (issue #493).
error.initProgress = { ...this.initProgress };
reject(error);
}, 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;
this.everInitialized = 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) {
// Cap what gets embedded in the user-facing error — the full
// buffer is already in the logs (issue #146).
const lines = this.stderrBuffer.slice(-10);
let text = lines.join('\n');
if (text.length > 2000) {
text = '…' + text.slice(-2000);
}
const label = this.stderrBuffer.length > lines.length
? ` (last ${lines.length} of ${this.stderrBuffer.length} lines)`
: '';
errorMessage += `\nStderr output${label}:\n${text}`;
}
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}`);
// Give in-flight DAP requests a bounded window to settle before we stop
// processing messages and cancel them. On natural termination the DAP
// 'terminated' event often races ahead of the final continue/step
// response, which is typically already in the IPC pipe — cancelling
// immediately would turn a successful operation into an error
// (issue #122 follow-up; observed with js-debug in container e2e).
await this.drainPendingDapRequests(this.stopDrainTimeoutMs);
// The proxy may have exited — or a concurrent stop() may have completed —
// while we drained; cleanup() nulls proxyProcess, so re-check before
// touching the process handle.
const process = this.proxyProcess;
if (!process) {
this.isStopped = true;
this.cleanup();
return;
}
// Mark as shutting down to stop processing new messages
this.isStopped = true;
const sessionIdSnapshot = this.sessionId;
// Cleanup (cancels whatever is still pending after the drain)
this.cleanup();
// Gate on actual exit evidence, not ChildProcess.killed — Node latches
// .killed when any signal is *delivered*, not when the process dies, so a
// prior kill() made both the terminate send and the SIGKILL escalation
// silent no-ops against a still-live worker (issue #502).
const hasExited = () => process.exitCode != null || process.signalCode != null;
// Send terminate command if process is still running
try {
if (!hasExited()) {
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 onExit = () => {
clearTimeout(timeout);
resolve();
};
const timeout = setTimeout(() => {
this.logger.warn(
`[ProxyManager] Timeout waiting for proxy exit. Force killing pid ${this.lastProxyPid ?? 'unknown'}.`
);
if (!hasExited()) {
process.kill('SIGKILL');
}
// Detach the once-listener: it never fired, and leaving it would
// accumulate a dead handler on the process object (issue #420).
process.removeListener('exit', onExit);
resolve();
}, 5000);
process.once('exit', onExit);
// If already exited, resolve immediately
if (hasExited()) {
clearTimeout(timeout);
process.removeListener('exit', onExit);
resolve();
}
});
}
/**
* Wait (bounded) for in-flight DAP requests to settle. While draining,
* isStopped is still false, so responses already in the IPC pipe are
* processed normally and resolve their pending promises — the common case
* completes within one poll interval. Requests still pending at the
* deadline are cancelled by the caller via cleanup().
*/
private async drainPendingDapRequests(timeoutMs: number, pollIntervalMs = 20): Promise<void> {
if (this.pendingDapRequests.size === 0) {
return;
}
this.logger.debug(
`[ProxyManager] Draining ${this.pendingDapRequests.size} in-flight DAP request(s) before stop (max ${timeoutMs}ms)`
);
const deadline = Date.now() + timeoutMs;
while (this.pendingDapRequests.size > 0 && Date.now() < deadline) {
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
}
if (this.pendingDapRequests.size > 0) {
this.logger.warn(
`[ProxyManager] ${this.pendingDapRequests.size} DAP request(s) still pending after ${timeoutMs}ms drain; cancelling`
);
}
}
async sendDapRequest<T extends DebugProtocol.Response>(
command: string,
args?: unknown,
options?: { timeoutMs?: number }
): 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,
// Conditional so the key is truly absent (not undefined) in IPC payloads
...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {})
};
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) => {
// Timeout handler. The worker/socket timeout (timeoutMs, default 30s)
// fires first and produces the actionable error; this parent timer is a
// backstop that only fires if the worker never responds at all. The
// handle is stored on the pending entry and cleared wherever the entry
// settles — a fired-but-uncleared backstop would otherwise reject with
// nobody listening long after the caller has moved on (issue #420).
const effectiveTimeoutMs =
(options?.timeoutMs ?? this.defaultDapRequestTimeoutMs) + this.dapParentMarginMs;
const timer = 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, Math.round(effectiveTimeoutMs / 1000))));
}
}, effectiveTimeoutMs);
timer.unref?.();
this.pendingDapRequests.set(requestId, {
resolve: resolve as (value: DebugProtocol.Response) => void,
reject,
command,
timer
});
// 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) {
clearTimeout(timer);
this.pendingDapRequests.delete(requestId);
if (barrier) {
this.clearActiveLaunchBarrier(barrier);
}
reject(error);
}
});
}
isRunning(): boolean {
// Actual-exit evidence, not .killed: a delivered signal latches .killed
// while the process may still be alive (issue #502). Loose null checks:
// test doubles may leave signalCode undefined.
return (
this.proxyProcess !== null &&
this.proxyProcess.exitCode == null &&
this.proxyProcess.signalCode == null
);
}
getProxyPid(): number | null {
return this.lastProxyPid;
}
getCurrentThreadId(): number | null {
return this.currentThreadId;
}
setCurrentThreadId(threadId: number): void {
this.currentThreadId = threadId;
// Mirror into the functional-core snapshot so an adopted anchor (the
// frameless-thread fallback, get_stack_trace {threadId}) is not stale
// there (issue #496).
if (this.dapState) {
this.dapState = setCoreCurrentThreadId(this.dapState, threadId);
}
}
private async prepareSpawnContext(config: ProxyConfig): Promise<{
executablePath: string;
proxyScriptPath: string;
env: Record<string, string>;
}> {
let executablePath = config.executablePath;
// Direct-connect attach spawns no local adapter or debuggee process, so the
// local toolchain is not required — skip environment probing (issue #331).
const isDirectConnectAttach =
config.attachMode === true && this.adapter?.usesDirectConnectForAttach?.() === true;
if (this.adapter && !isDirectConnectAttach) {
// Validate the interpreter the user configured (if any) rather than an auto-detected one,
// so a venv that has debugpy is not rejected because the system Python lacks it (issue #106).
const validation = await this.adapter.validateEnvironment(executablePath);
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 (isDirectConnectAttach && !executablePath) {
// Nominal, unverified name — connect mode never spawns it
executablePath = this.adapter?.getDefaultExecutableName?.() ?? config.language;
} 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;
// Latch the ack for the whole retry sequence (issue #512): the worker
// acks exactly once, and on a slow boot (>500ms — inspected or heavily
// loaded host) that ack lands between attempt windows. A per-attempt
// listener silently drops it, and for a worker that then exits (dry-run)
// every remaining retry fails against a process that already did its job.
let acked = false;
const onAck = () => {
acked = true;
};
this.on('init-received', onAck);
// Wait up to ms, ending early (true) the moment the ack arrives — or
// immediately when it was already latched by the long-lived listener
const waitForAck = (ms: number): Promise<boolean> =>
new Promise<boolean>((resolve) => {
if (acked) {
resolve(true);
return;
}
let settled = false;
const settle = (value: boolean) => {
if (settled) return;
settled = true;
clearTimeout(timer);
this.removeListener('init-received', onAckNow);
resolve(value);
};
const onAckNow = () => settle(true);
this.on('init-received', onAckNow);
const timer = setTimeout(() => settle(false), ms);
});
// Attempts actually made, for the failure message: a fast-fail on a dead
// worker must not report the full retry budget as spent (issue #517)
let attemptsMade = 0;
let failedFast = false;
try {
for (let attempt = 0; attempt <= maxRetries; attempt++) {
if (acked) {
this.logger.info(`[ProxyManager] Init command acknowledged before attempt ${attempt + 1}`);
return;
}
const timeoutMs = delays[Math.min(attempt, delays.length - 1)];
attemptsMade = attempt + 1;
let sendFailed = false;
try {
this.sendCommand(initCommand);
} catch (error) {
lastError = error as Error;
sendFailed = true;
this.logger.warn(
`[ProxyManager] Error sending init on attempt ${attempt + 1}: ${lastError.message}`
);
// Once the worker has exited without acking, no ack can arrive —
// fail fast with the detailed exit message instead of burning the
// remaining retries against a process that is gone (issue #512)
if (this.lastExitDetails) {
failedFast = true;
break;
}
}
// A failed send delivered nothing to wait for; an earlier attempt's
// late ack is still caught by the latch during the backoff below
if (!sendFailed) {
if (await waitForAck(timeoutMs)) {
this.logger.info(`[ProxyManager] Init command acknowledged on attempt ${attempt + 1}`);
return;
}
this.logger.warn(
`[ProxyManager] Init not acknowledged, attempt ${attempt + 1}/${maxRetries + 1}`
);
}
if (attempt < maxRetries) {
const waitMs = delays[Math.min(attempt, delays.length - 1)];
if (await waitForAck(waitMs)) {
this.logger.info(
`[ProxyManager] Init command acknowledged during backoff after attempt ${attempt + 1}`
);
return;
}
}
}
} finally {
this.removeListener('init-received', onAck);
}
// Report the attempts actually made: "after 6 attempts" on a launch that
// fast-failed on attempt 2 misreads how long the launch spent trying
// (issue #517)
const attemptSummary = failedFast
? `after ${attemptsMade} attempt${attemptsMade === 1 ? '' : 's'} (proxy exited; further retries skipped)`
: `after ${attemptsMade} attempts`;
let detailMessage = `Failed to initialize proxy ${attemptSummary}. ${
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;
// Track every listener installed here so a failed start() can detach the
// lot (issue #420); see trackedProxyListeners.
this.trackedProxyListeners = [];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const track = (emitter: RemovableEmitter, event: string, listener: (...args: any[]) => void) => {
emitter.on(event, listener);
this.trackedProxyListeners.push({ emitter, event, listener });
};
const proc = this.proxyProcess as unknown as RemovableEmitter;
// Handle IPC messages
track(proc, 'message', (rawMessage: unknown) => {
this.handleProxyMessage(rawMessage);
});
track(proc, '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'}`
);
});
track(proc, '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'}`
);
});
track(proc, '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'}`
);
});
track(proc, '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. Chunks arrive at arbitrary byte boundaries, so they are
// line-buffered before sanitization — a secret assignment split across
// two chunks would otherwise leak its tail past the key/value redaction
// patterns (issue #151). Scoped to this process's handlers so a pending
// partial line survives until this stream's own 'end'/'close', and never
// bleeds into a later process's stderr.
const stderr = this.proxyProcess.stderr as unknown as RemovableEmitter | null;
if (stderr) {
const stderrLineBuffer = new LineBuffer();
track(stderr, 'data', (data: Buffer | string) => {
this.recordStderrLines(stderrLineBuffer.append(data.toString()));
});
// Flush the trailing partial line only once the stream itself is done.
// Flushing on process 'exit' would be wrong: the pipe can still deliver
// the rest of a split line afterwards, re-creating the straddle leak.
const flushStderr = () => this.recordStderrLines(stderrLineBuffer.flush());
track(stderr, 'end', flushStderr);
track(stderr, 'close', flushStderr);
}
// Handle exit
track(proc, '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],
};
// everInitialized, not isInitialized: stop() runs cleanup() (which
// resets isInitialized) before this event fires, so the reset flag
// would report every orderly shutdown as a pre-init death (issue #530)
if (!this.everInitialized) {
this.logger.error(
`[ProxyManager] Proxy exited before initialization. code=${code} signal=${signal} stderrLines=${this.stderrBuffer.length}`,
this.stderrBuffer
);
}
this.handleProxyExit(code, signal);
});
// Handle errors
track(proc, 'error', (err: Error) => {
this.logger.error(`[ProxyManager] Proxy error:`, err);
this.emit('error', err);
this.cleanup();
});
}
/**
* Remove the listeners setupEventHandlers installed on the proxy process.
* Called when start() fails: the manager is about to be discarded, and a
* stale process handle must not keep driving handleProxyExit/cleanup —
* those reject pending requests with nobody left to listen (issue #420).
* The caller (SessionManager) still runs stop(), which operates on the
* process handle directly and needs none of these listeners.