UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

298 lines (297 loc) • 10.5 kB
import { u as isErrno, y as toErrorObject } from "./paths-0xDagtub.mjs"; import { A as parseStrictPositiveInteger, L as normalizeLowercaseStringOrEmpty, s as normalizeProfileName } from "./path-guards-quCEQx1i.mjs"; import { Z as expectDefined } from "./redact-BRF0hr6G.mjs"; import "./errors-hqLS1E8Y.mjs"; import { t as classifyOpenClawArgv } from "./gateway-process-argv-DB5Y-Mad.mjs"; import { t as parseWindowsNativeCommandLine } from "./windows-command-line-pAvLBgBI.mjs"; import net from "node:net"; //#region src/cli/command-format.ts const CLI_PREFIX_RE = /^(?:pnpm|npm|bunx|npx)\s+openclaw\b|^openclaw\b/; const CONTAINER_FLAG_RE = /(?:^|\s)--container(?:\s|=|$)/; const PROFILE_FLAG_RE = /(?:^|\s)--profile(?:\s|=|$)/; const DEV_FLAG_RE = /(?:^|\s)--dev(?:\s|$)/; const UPDATE_RE = /^(?:\s+--(?:dev|no-color|(?:profile|log-level)[=\s]+\S+))*\s+update(?:\s|$)/; const CONTAINER_HINT_RE = /^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$/; function formatCliCommand(e, t = process.env) { const n = t.OPENCLAW_CONTAINER_HINT?.trim(); const r = n && CONTAINER_HINT_RE.test(n) ? n : void 0; const i = normalizeProfileName(t.OPENCLAW_PROFILE); if (!r && !i) return e; if (!CLI_PREFIX_RE.test(e)) return e; let a; if (r && !CONTAINER_FLAG_RE.test(e) && !UPDATE_RE.test(e.replace(CLI_PREFIX_RE, ""))) a = `--container ${r}`; if (!r && i && !PROFILE_FLAG_RE.test(e) && !DEV_FLAG_RE.test(e)) a = `--profile ${i}`; return a ? e.replace(CLI_PREFIX_RE, (e) => `${e} ${a}`) : e; } //#endregion //#region src/daemon/arg-split.ts /** Splits service command strings while preserving quoted arguments across platform parsers. */ function splitArgsPreservingQuotes(e, t) { const n = []; let r = null; let i = null; const a = t?.escapeMode ?? "none"; const o = new Set(t?.quoteChars ?? ["\""]); const s = t?.quoteStart ?? "anywhere"; for (let t = 0; t < e.length; t++) { const c = e.charAt(t); if (c === "\\" && (a === "backslash" || a === "backslash-quote-only" && e[t + 1] === "\"")) { if (t + 1 < e.length) { r = (r ?? "") + e[t + 1]; t++; } continue; } if (o.has(c)) { if (i === c) { i = null; continue; } if (!i && (s === "anywhere" || !r)) { i = c; r ??= ""; continue; } } if (!i && /\s/.test(c)) { if (r !== null) { n.push(r); r = null; } continue; } r = (r ?? "") + c; } if (r !== null) n.push(r); return n; } //#endregion //#region src/infra/ports-netstat.ts function normalizeTcpHost(e) { const t = e.toLowerCase(); return t.startsWith("::ffff:") ? t.slice(7) : t; } function parseTcpPort(e) { if (!e || !/^\d+$/.test(e)) return null; const t = Number(e); return Number.isSafeInteger(t) && t >= 0 && t <= 65535 ? t : null; } function parseTcpEndpoint(e) { const t = /^(?:\[([^\]]+)\]|([\s\S]+)):(\d+)$/.exec(e.trim()); if (!t) return null; const n = parseTcpPort(t[3]); return n === null ? null : { host: normalizeTcpHost(expectDefined(t[1] ?? t[2], "bracket match capture group 1")), port: n }; } /** Parses the address field emitted for a TCP listener by lsof or netstat. */ function parseTcpListenerEndpoint(e) { const t = e?.trim().replace(/^tcp6?\s+/i, "").replace(/\s*\(listen\)\s*$/i, ""); return t ? parseTcpEndpoint(t) : null; } function isWildcardEndpoint(e) { const t = e?.trim(); if (!t || t === "*:*") return true; const n = parseTcpEndpoint(t); if (!n) return false; return n.port === 0 && [ "0.0.0.0", "::", "*" ].includes(n.host); } function parseWindowsNetstatListeners(e, t) { const n = []; for (const r of e.split(/\r?\n/)) { const e = r.trim().split(/\s+/); if (e.length < 5 || e[0]?.toUpperCase() !== "TCP") continue; const i = e[1]; const a = e[2]; if (!i || parseTcpEndpoint(i)?.port !== t) continue; if (!isWildcardEndpoint(a)) continue; const o = parseStrictPositiveInteger(e.at(-1)); if (o === void 0) continue; n.push({ pid: o, address: i }); } return n; } //#endregion //#region src/infra/ports-format.ts function classifyPortListener(e) { const t = normalizeLowercaseStringOrEmpty(e.command ?? ""); if (t === "socat" || t === "socat1" || t === "socat.exe") return "non_gateway"; const n = e.commandLine ? process.platform === "win32" ? parseWindowsNativeCommandLine(e.commandLine) ?? [] : splitArgsPreservingQuotes(e.commandLine, { escapeMode: "backslash-quote-only" }) : [e.command ?? ""]; if (classifyOpenClawArgv(n, { command: "gateway", pid: e.pid }).kind === "openclaw") return "gateway"; const r = normalizeLowercaseStringOrEmpty(n[0] ?? ""); if (/(?:^|[/\\])ssh(?:\.exe)?$/.test(t) || /(?:^|[/\\])ssh(?:\.exe)?$/.test(r)) return "ssh"; if (t === "sshd" || /(?:^|[/\\])sshd(?:\.exe)?$/.test(t) || /(?:^|[/\\])[^/\\\s]*ssh[^/\\\s]*(?:\.exe)?$/.test(t) || /(?:^|[/\\])[^/\\\s]*ssh[^/\\\s]*(?:\.exe)?$/.test(r)) return "non_gateway"; return "unknown"; } function classifyLoopbackAddressFamily(e) { if (e === "127.0.0.1" || e === "localhost") return "ipv4"; if (e === "::1" || e === "::ffff:127.0.0.1") return "ipv6"; return null; } function isWildcardAddress(e) { return e === "0.0.0.0" || e === "::" || e === "*"; } function isExpectedGatewayBindAddress(e) { return classifyLoopbackAddressFamily(e) !== null || isWildcardAddress(e); } function parsePortListeners(e, t) { const n = []; for (const r of e) { const e = r.pid; if (typeof e !== "number" || !Number.isFinite(e) || typeof r.address !== "string") return null; const i = parseTcpListenerEndpoint(r.address); if (!i || i.port !== t) return null; n.push({ pid: e, host: i.host }); } return n; } function parseGatewayListeners(e, t) { if (e.some((e) => classifyPortListener(e) !== "gateway")) return null; return parsePortListeners(e, t); } function parsedListenersAreDualStackLoopback(e) { const t = new Set(e.map(({ pid: e }) => e)); const n = new Set(e.map(({ host: e }) => classifyLoopbackAddressFamily(e))); return t.size === 1 && !n.has(null) && n.has("ipv4") && n.has("ipv6"); } function parsedListenersOwnSpecificIpv4WithLoopback(e) { return e.every(({ pid: t }) => t === e[0]?.pid) && e.some(({ host: e }) => e === "127.0.0.1") && e.some(({ host: e }) => e !== "127.0.0.1" && net.isIP(e) === 4 && !isWildcardAddress(e)); } function isExpectedGatewayListeners(e, t) { const n = parseGatewayListeners(e, t); if (!n) return false; if (n.length === 1) return Boolean(n[0] && isExpectedGatewayBindAddress(n[0].host)); return parsedListenersAreDualStackLoopback(n) || n.length === 2 && parsedListenersOwnSpecificIpv4WithLoopback(n); } function buildPortHints(e, t) { if (e.length === 0) return []; const n = new Set(e.map((e) => classifyPortListener(e))); const r = []; const i = isExpectedGatewayListeners(e, t); if (n.has("gateway") && !i) r.push(`Gateway already running locally. Stop it (${formatCliCommand("openclaw gateway stop")}) or use a different port.`); if (n.has("ssh")) r.push("SSH tunnel already bound to this port. Close the tunnel or use a different local port in -L."); if (n.has("unknown") || n.has("non_gateway")) r.push("Another process is listening on this port."); if (e.length > 1 && !i) r.push("Multiple listeners detected; ensure only one gateway/tunnel per port unless intentionally running isolated profiles."); return r; } //#endregion //#region src/infra/ports-probe.ts const PORT_PROBE_HOSTS = [ "127.0.0.1", "0.0.0.0", "::1", "::" ]; async function tryListenOnPort(e) { if (e.signal?.aborted) throw e.signal.reason; const t = { port: e.port }; if (e.host) t.host = e.host; if (typeof e.exclusive === "boolean") t.exclusive = e.exclusive; if (e.signal) t.signal = e.signal; return await new Promise((n, r) => { const clearAbort = () => e.signal?.removeEventListener("abort", onAbort); const onAbort = () => { clearAbort(); r(toErrorObject(e.signal?.reason, "Port check aborted")); }; e.signal?.addEventListener("abort", onAbort, { once: true }); const i = net.createServer().once("error", (e) => { clearAbort(); r(e); }).once("listening", () => { const t = i.address(); i.close(() => { clearAbort(); if (!t || typeof t === "string") r(/* @__PURE__ */ new Error("expected TCP listener address")); else n(e.port === 0 ? t.port : void 0); }); }).listen(t); }); } /** Observe a listener without retaining its socket or cancellation hook. */ async function probeTcpListener(e, t, n, r) { n?.throwIfAborted(); const i = r === void 0 ? 250 : r - Date.now(); if (i <= 0) return "unknown"; return await new Promise((r) => { const a = net.connect({ host: t, port: e }); let o = "unknown"; const destroy = () => a.destroy(); n?.addEventListener("abort", destroy, { once: true }); a.once("connect", () => { o = "busy"; destroy(); }); a.once("error", (e) => { o = isErrno(e) && e.code === "ECONNREFUSED" ? "free" : "unknown"; destroy(); }); a.setTimeout(i, destroy); a.once("close", () => { n?.removeEventListener("abort", destroy); r(o); }); }); } async function isIpv6LoopbackUnavailable(e) { try { await tryListenOnPort({ port: 0, host: "::1", ...e ? { signal: e } : {} }); return false; } catch (e) { return isErrno(e) && e.code === "EADDRNOTAVAIL"; } } async function probePortOnHost(e, t, n, r) { try { await tryListenOnPort({ port: e, host: t, exclusive: true, ...n ? { signal: n } : {} }); const i = await probeTcpListener(e, t, n, r); if (i === "unknown" && t === "::" && await isIpv6LoopbackUnavailable(n)) return "free"; return i; } catch (i) { n?.throwIfAborted(); if (isErrno(i) && i.code === "EADDRINUSE") return "busy"; if (process.platform === "win32" && isErrno(i) && i.code === "EACCES") return await probeTcpListener(e, t, n, r) === "busy" ? "busy" : "unknown"; if (isErrno(i) && (i.code === "EADDRNOTAVAIL" || i.code === "EAFNOSUPPORT")) return "skip"; return "unknown"; } } /** Checks selected local addresses without resolving listener diagnostics. */ async function probePortUsage(e, t = PORT_PROBE_HOSTS, n, r) { n?.throwIfAborted(); let i = false; for (const a of t) { const t = await probePortOnHost(e, a, n, r); n?.throwIfAborted(); if (t === "busy") return "busy"; if (t === "unknown") i = true; } return i ? "unknown" : "free"; } //#endregion export { parseTcpEndpoint as a, buildPortHints as i, probeTcpListener as n, parseTcpListenerEndpoint as o, tryListenOnPort as r, parseWindowsNetstatListeners as s, probePortUsage as t };