(
path: string,
opts?: { isExplicit?: boolean },
)
| 423 | * processes (hooks, spawned agents) can discover and connect back. |
| 424 | */ |
| 425 | export async function startUdsMessaging( |
| 426 | path: string, |
| 427 | opts?: { isExplicit?: boolean }, |
| 428 | ): Promise<void> { |
| 429 | if (server) { |
| 430 | logForDebugging('[udsMessaging] server already running, skipping start') |
| 431 | return |
| 432 | } |
| 433 | |
| 434 | assertValidUnixSocketPath(path) |
| 435 | |
| 436 | // Ensure parent directory exists (skip on Windows — pipe paths aren't files) |
| 437 | if (process.platform !== 'win32') { |
| 438 | await ensureSocketParent(path) |
| 439 | } |
| 440 | |
| 441 | // Clean up stale socket file (skip on Windows — pipe paths aren't files) |
| 442 | if (process.platform !== 'win32') { |
| 443 | try { |
| 444 | await unlink(path) |
| 445 | } catch { |
| 446 | // ENOENT is fine |
| 447 | } |
| 448 | } |
| 449 | |
| 450 | const token = ensureAuthToken() |
| 451 | let startedServer: Server | null = null |
| 452 | let exportedSocketEnv = false |
| 453 | try { |
| 454 | await new Promise<void>((resolve, reject) => { |
| 455 | const srv = createServer(socket => { |
| 456 | if (clients.size >= MAX_UDS_CLIENTS) { |
| 457 | logForDebugging( |
| 458 | `[udsMessaging] rejected client: ${clients.size}/${MAX_UDS_CLIENTS} clients already connected`, |
| 459 | ) |
| 460 | socket.destroy() |
| 461 | return |
| 462 | } |
| 463 | clients.add(socket) |
| 464 | logForDebugging( |
| 465 | `[udsMessaging] client connected (total: ${clients.size})`, |
| 466 | ) |
| 467 | let authenticated = false |
| 468 | let closing = false |
| 469 | const closeWithError = (data: string): void => { |
| 470 | if (closing || socket.destroyed) return |
| 471 | closing = true |
| 472 | socket.pause() |
| 473 | writeSocketErrorAndDestroy(socket, data) |
| 474 | } |
| 475 | const authTimer = setTimeout(() => { |
| 476 | if (authenticated || socket.destroyed) return |
| 477 | logForDebugging('[udsMessaging] closing unauthenticated idle client') |
| 478 | closeWithError('authentication timeout') |
| 479 | }, UDS_AUTH_TIMEOUT_MS) |
| 480 | unrefTimer(authTimer) |
| 481 | socket.setTimeout(UDS_IDLE_TIMEOUT_MS, () => { |
| 482 | logForDebugging('[udsMessaging] closing idle client') |
no test coverage detected