()
| 436 | } |
| 437 | |
| 438 | async function ensureAgentSocket(): Promise<net.Socket> { |
| 439 | if (agentSocket && !agentSocket.destroyed) return agentSocket; |
| 440 | |
| 441 | try { |
| 442 | agentSocket = await connectToAgent(); |
| 443 | } catch { |
| 444 | await maybeStartAgentDaemon(connection, session); |
| 445 | for (let attempt = 0; attempt < 20; attempt++) { |
| 446 | await sleep(100); |
| 447 | try { |
| 448 | agentSocket = await connectToAgent(); |
| 449 | break; |
| 450 | } catch {} |
| 451 | } |
| 452 | } |
| 453 | |
| 454 | if (!agentSocket || agentSocket.destroyed) { |
| 455 | const target = |
| 456 | connection.type === "unix" ? connection.path : `${connection.host}:${connection.port}`; |
| 457 | throw new Error(`Could not connect to agent-browser daemon at ${target}.`); |
| 458 | } |
| 459 | |
| 460 | agentSocket.setNoDelay(true); |
| 461 | agentSocket.on( |
| 462 | "data", |
| 463 | createJsonLineParser((msg) => { |
| 464 | if (!msg || msg.id === undefined) return; |
| 465 | const messageId = typeof msg.id === "string" ? msg.id : String(msg.id); |
| 466 | const pending = agentPending.get(messageId); |
| 467 | if (!pending) return; |
| 468 | agentPending.delete(messageId); |
| 469 | const res = msg as AgentResponse; |
| 470 | if (!res.success) pending.reject(new Error(res.error || "Agent browser error")); |
| 471 | else pending.resolve(res.data); |
| 472 | }) |
| 473 | ); |
| 474 | |
| 475 | agentSocket.on("close", () => { |
| 476 | for (const pending of agentPending.values()) { |
| 477 | pending.reject(new Error("Agent browser connection closed")); |
| 478 | } |
| 479 | agentPending.clear(); |
| 480 | agentSocket = null; |
| 481 | }); |
| 482 | |
| 483 | agentSocket.on("error", () => { |
| 484 | agentSocket = null; |
| 485 | }); |
| 486 | |
| 487 | return agentSocket; |
| 488 | } |
| 489 | |
| 490 | async function agentRequest(action: string, payload: Record<string, any>): Promise<any> { |
| 491 | const socket = await ensureAgentSocket(); |
no test coverage detected