| 71 | // ─── Server ───────────────────────────────────────────────────────────────── |
| 72 | |
| 73 | export function startStdioServer(options: StdioServerOptions): StdioServerHandle { |
| 74 | const stdin = options.stdin ?? process.stdin; |
| 75 | const stdout = options.stdout ?? process.stdout; |
| 76 | const logToStderr = options.logToStderr ?? true; |
| 77 | const dispatch = makeDispatcher(options.core, { strict: !!options.strict }); |
| 78 | |
| 79 | let closed = false; |
| 80 | const eventsHandlers = new Set<symbol>(); |
| 81 | const logsHandlers = new Set<symbol>(); |
| 82 | |
| 83 | // ─── Server-initiated RPC bookkeeping ── |
| 84 | // Reverse-direction requests (bridge → client) live in their own |
| 85 | // ID namespace ("srv-1", "srv-2", …) so they never collide with the |
| 86 | // numeric IDs the Python client uses for forward requests. |
| 87 | let serverRequestSeq = 0; |
| 88 | const serverPending = new Map< |
| 89 | string, |
| 90 | { |
| 91 | resolve: (value: unknown) => void; |
| 92 | reject: (err: unknown) => void; |
| 93 | timer: ReturnType<typeof setTimeout> | null; |
| 94 | } |
| 95 | >(); |
| 96 | |
| 97 | const eventsUnsubscribe = options.core.subscribeEvents((e) => { |
| 98 | writeNotification(RPC_METHODS.EVENTS_NOTIFY, e); |
| 99 | }); |
| 100 | const logsUnsubscribe = options.core.subscribeLogs((r) => { |
| 101 | writeNotification(RPC_METHODS.LOGS_FORWARD, r); |
| 102 | }); |
| 103 | |
| 104 | function finishTransport(err?: Error): void { |
| 105 | if (closed) return; |
| 106 | closed = true; |
| 107 | try { |
| 108 | eventsUnsubscribe(); |
| 109 | } catch { |
| 110 | /* ignore */ |
| 111 | } |
| 112 | try { |
| 113 | logsUnsubscribe(); |
| 114 | } catch { |
| 115 | /* ignore */ |
| 116 | } |
| 117 | for (const [id, entry] of serverPending) { |
| 118 | if (entry.timer) clearTimeout(entry.timer); |
| 119 | entry.reject(err ?? new Error("stdio bridge closed")); |
| 120 | serverPending.delete(id); |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | function writeLine(obj: unknown): void { |
| 125 | try { |
| 126 | stdout.write(JSON.stringify(obj) + "\n"); |
| 127 | } catch (err) { |
| 128 | if (logToStderr) { |
| 129 | process.stderr.write( |
| 130 | `bridge.stdio.write.err: ${err instanceof Error ? err.message : String(err)}\n`, |