| 664 | clearTimeout(timer); |
| 665 | }; |
| 666 | const onData = (chunk: string | Buffer) => { |
| 667 | buffer += typeof chunk === 'string' ? chunk : chunk.toString('utf8'); |
| 668 | const idx = buffer.indexOf('\n'); |
| 669 | if (idx === -1) { |
| 670 | if (buffer.length > MAX_HELLO_LINE_BYTES) { |
| 671 | cleanup(); |
| 672 | reject(new Error('daemon hello line exceeded size limit')); |
| 673 | } |
| 674 | return; |
| 675 | } |
| 676 | const line = buffer.slice(0, idx); |
| 677 | // Re-emit anything past the newline so the pipe-stage sees it. |
| 678 | const tail = buffer.slice(idx + 1); |
| 679 | cleanup(); |
| 680 | if (tail.length > 0) { |
| 681 | // Push back via unshift — Node's net.Socket supports it on readable streams. |
| 682 | socket.unshift(tail); |
| 683 | } |
| 684 | try { |
| 685 | const parsed = JSON.parse(line) as DaemonHello; |
| 686 | if (typeof parsed.codegraph !== 'string' || typeof parsed.pid !== 'number') { |
| 687 | reject(new Error('daemon hello missing required fields')); |
| 688 | return; |
| 689 | } |
| 690 | resolve(parsed); |
| 691 | } catch (err) { |
| 692 | reject(new Error(`daemon hello not JSON: ${err instanceof Error ? err.message : String(err)}`)); |
| 693 | } |
| 694 | }; |
| 695 | const onError = (err: Error) => { cleanup(); reject(err); }; |
| 696 | const onClose = () => { cleanup(); reject(new Error('daemon closed connection before hello')); }; |
| 697 | const timer = setTimeout(() => { |