UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

95 lines (94 loc) • 2.5 kB
import { R as resolveTimerTimeoutMs } from "./number-coercion-D6u-4YD8.mjs"; import { p as toErrorObject } from "./error-coercion-hDrHOSGy.mjs"; import net from "node:net"; import { addAbortListener } from "node:events"; import { clearTimeout, setTimeout } from "node:timers"; //#region src/infra/jsonl-socket.ts const JSONL_SOCKET_MAX_LINE_BYTES = 16777216; /** * Sends one JSONL request line, half-closes the write side, and waits for an accepted response line. */ async function requestJsonlSocket(e) { const { socketPath: t, requestLine: n, accept: r, signal: i } = e; const a = e.timeoutMs === 0 ? 0 : resolveTimerTimeoutMs(e.timeoutMs, 1); return await new Promise((o, s) => { const c = new net.Socket(); let l = false; let u = false; let d; const f = []; let p = 0; const cleanup = () => { if (l) return false; l = true; clearTimeout(d); m?.[Symbol.dispose](); c.destroy(); return true; }; const finish = (e) => { if (cleanup()) o(e); }; const fail = (e) => { if (cleanup()) s(toErrorObject(e, "Socket request failed before sending.")); }; const finishPeerLoss = () => finish(u ? e.onResponseLost?.() ?? null : null); const appendLineChunk = (t) => { if (p + t.byteLength > (e.maxResponseLineBytes ?? JSONL_SOCKET_MAX_LINE_BYTES)) { finishPeerLoss(); return false; } if (t.byteLength > 0) { f.push(t); p += t.byteLength; } return true; }; if (a > 0) d = setTimeout(() => finish(u ? e.onTimeout?.() ?? null : null), a); const m = i ? addAbortListener(i, () => finish(null)) : void 0; if (i?.aborted) { finish(null); return; } c.on("error", finishPeerLoss); c.on("end", finishPeerLoss); c.on("close", finishPeerLoss); c.connect(t, () => { if (l) return; try { e.beforeSend?.(); } catch (e) { fail(e); return; } if (l) return; u = true; c.end(`${n}\n`); }); c.on("data", (e) => { let t = 0; while (t < e.byteLength) { const n = e.indexOf(10, t); if (n === -1) { appendLineChunk(e.subarray(t)); return; } if (!appendLineChunk(e.subarray(t, n))) return; const i = (f.length > 1 ? Buffer.concat(f, p) : f[0])?.toString("utf8").trim() ?? ""; f.length = 0; p = 0; t = n + 1; if (!i) continue; try { const e = JSON.parse(i); const t = r(e); if (t === void 0) continue; finish(t); return; } catch {} } }); }); } //#endregion export { requestJsonlSocket as t };