* Pipe stdin → socket and socket → stdout. Resolves once either end closes * so the process can exit. Note: we deliberately do NOT use * `process.stdin.pipe(socket)` because pipe propagates 'end' onto the * downstream, which would close the socket prematurely if stdin happens to * end early — th
(socket: net.Socket)
| 712 | * end early — the MCP spec allows it to stay open across reconnects. |
| 713 | */ |
| 714 | function pipeUntilClose(socket: net.Socket): Promise<void> { |
| 715 | return new Promise((resolve) => { |
| 716 | let resolved = false; |
| 717 | const done = () => { if (!resolved) { resolved = true; resolve(); } }; |
| 718 | |
| 719 | process.stdin.on('data', (chunk) => { |
| 720 | try { socket.write(chunk); } catch { /* socket may have errored — close path catches it */ } |
| 721 | }); |
| 722 | process.stdin.on('end', () => { |
| 723 | try { socket.end(); } catch { /* ignore */ } |
| 724 | done(); |
| 725 | }); |
| 726 | // 'close' and 'error' both tear down: a socket-backed stdin can fail with |
| 727 | // an 'error' (ECONNRESET/hangup) rather than a clean close; destroying it |
| 728 | // stops a hung fd from busy-spinning the event loop (#799). |
| 729 | const teardown = () => { |
| 730 | try { process.stdin.destroy(); } catch { /* ignore */ } |
| 731 | try { socket.destroy(); } catch { /* ignore */ } |
| 732 | done(); |
| 733 | }; |
| 734 | process.stdin.on('close', teardown); |
| 735 | process.stdin.on('error', teardown); |
| 736 | |
| 737 | socket.on('data', (chunk) => { |
| 738 | try { process.stdout.write(chunk); } catch { /* ignore */ } |
| 739 | }); |
| 740 | socket.on('end', () => done()); |
| 741 | socket.on('close', () => done()); |
| 742 | socket.on('error', (err) => { |
| 743 | process.stderr.write(`[CodeGraph MCP] daemon socket error: ${err.message}\n`); |
| 744 | done(); |
| 745 | }); |
| 746 | }); |
| 747 | } |
| 748 | |
| 749 | /** |
| 750 | * PPID watchdog mirroring the one in `MCPServer.start` — kills the proxy if |