* 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)
| 768 | * end early — the MCP spec allows it to stay open across reconnects. |
| 769 | */ |
| 770 | function pipeUntilClose(socket: net.Socket): Promise<void> { |
| 771 | return new Promise((resolve) => { |
| 772 | let resolved = false; |
| 773 | const done = () => { if (!resolved) { resolved = true; resolve(); } }; |
| 774 | |
| 775 | process.stdin.on('data', (chunk) => { |
| 776 | try { socket.write(chunk); } catch { /* socket may have errored — close path catches it */ } |
| 777 | }); |
| 778 | process.stdin.on('end', () => { |
| 779 | try { socket.end(); } catch { /* ignore */ } |
| 780 | done(); |
| 781 | }); |
| 782 | // 'close' and 'error' both tear down: a socket-backed stdin can fail with |
| 783 | // an 'error' (ECONNRESET/hangup) rather than a clean close; destroying it |
| 784 | // stops a hung fd from busy-spinning the event loop (#799). |
| 785 | const teardown = () => { |
| 786 | try { process.stdin.destroy(); } catch { /* ignore */ } |
| 787 | try { socket.destroy(); } catch { /* ignore */ } |
| 788 | done(); |
| 789 | }; |
| 790 | process.stdin.on('close', teardown); |
| 791 | process.stdin.on('error', teardown); |
| 792 | |
| 793 | socket.on('data', (chunk) => { |
| 794 | try { process.stdout.write(chunk); } catch { /* ignore */ } |
| 795 | }); |
| 796 | socket.on('end', () => done()); |
| 797 | socket.on('close', () => done()); |
| 798 | socket.on('error', (err) => { |
| 799 | process.stderr.write(`[CodeGraph MCP] daemon socket error: ${err.message}\n`); |
| 800 | done(); |
| 801 | }); |
| 802 | }); |
| 803 | } |
| 804 | |
| 805 | /** |
| 806 | * PPID watchdog mirroring the one in `MCPServer.start` — kills the proxy if |