| 509 | } |
| 510 | |
| 511 | private handleConnection(socket: net.Socket): void { |
| 512 | if (this.stopping) { socket.destroy(); return; } |
| 513 | this.acceptedSockets.add(socket); |
| 514 | socket.once('close', () => this.acceptedSockets.delete(socket)); |
| 515 | // Hello first so the proxy can verify versions before piping any |
| 516 | // application bytes. The proxy reads exactly one line, then forwards. |
| 517 | const hello: DaemonHello = { |
| 518 | codegraph: CodeGraphPackageVersion, |
| 519 | pid: process.pid, |
| 520 | socketPath: this.socketPath, |
| 521 | protocol: 1, |
| 522 | }; |
| 523 | socket.write(JSON.stringify(hello) + '\n'); |
| 524 | |
| 525 | // Read the optional client-hello (proxy → daemon) to learn the client's |
| 526 | // peer pids, then hand the socket to the session. Fail-safe: any problem — |
| 527 | // timeout, a non-hello first line, an early close — yields null pids and we |
| 528 | // fall back to the socket-close lifecycle exactly as before (#692). |
| 529 | void readClientHello(socket).then(({ challenge, ...peers }) => { |
| 530 | if (this.stopping || socket.destroyed) { socket.destroy(); return; } |
| 531 | // A client that asked gets its proof before the session's first byte. |
| 532 | if (challenge !== undefined) this.answerChallenge(socket, challenge); |
| 533 | const transport = new SocketTransport(socket); |
| 534 | const session = new MCPSession(transport, this.engine, { |
| 535 | explicitProjectPath: this.projectRoot, |
| 536 | }); |
| 537 | transport.onClose(() => this.dropClient(session)); |
| 538 | this.clients.add(session); |
| 539 | this.clientPeers.set(session, peers); |
| 540 | this.disarmIdleTimer(); |
| 541 | session.start(); |
| 542 | // Observe inbound bytes purely to feed the inactivity backstop — a second |
| 543 | // 'data' listener that reads nothing, added AFTER the transport's so the |
| 544 | // unshifted client-hello tail reaches the transport intact. |
| 545 | socket.on('data', () => { this.lastActivityAt = Date.now(); }); |
| 546 | }); |
| 547 | } |
| 548 | |
| 549 | /** |
| 550 | * Answer a client-hello's challenge with this user's proof (see |