openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
394 lines (393 loc) • 15.6 kB
JavaScript
import { g as readStringValue, l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { o as writeRuntimeJson } from "./runtime-B-SLYP-m.mjs";
import { t as isAbortError } from "./abort-signal-D4Q6SEw7.mjs";
import { b as resolveGatewayPort } from "./paths-DAcAg5aV.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { r as scheduleAbsoluteDeadline } from "./absolute-deadline-kK4DcdPs.mjs";
import { a as readBestEffortConfig } from "./io.runtime-DsJ2dLCQ.mjs";
import { s as isLoopbackHost } from "./net-BgRayX-P.mjs";
import "./config-CMA-J084.mjs";
import { n as pickBestEffortPrimaryTailnetIPv4 } from "./network-discovery-display-DFKPX-nl.mjs";
import { r as resolveExplicitGatewayAuth } from "./credentials-UDpmcQCV.mjs";
import { n as isRich, r as theme, t as colorize } from "./theme-BOI0xyRZ.mjs";
import { a as resolveGatewayDeviceAuthRoute, o as resolveGatewaySshRemotePort } from "./connection-details-BWzGtdxz.mjs";
import { t as parseGatewayPortOption } from "./gateway-port-option-D-9uSBm2.mjs";
import "./call-DVCK1deJ.mjs";
import { n as ensureExplicitGatewayAuth } from "./client-bootstrap-BzJO9FYk.mjs";
import { n as probeGateway } from "./probe-yxDLQFmi.mjs";
import { r as withProgress } from "./progress-DZHhZ1Fk.mjs";
import { n as parseTimeoutMsWithFallback } from "./parse-timeout-qqSdJSy9.mjs";
import { a as resolveWideAreaDiscoveryDomain } from "./widearea-dns-Clgx1Bw3.mjs";
import { t as discoverGatewayBeacons } from "./bonjour-discovery-B1DGhRj_.mjs";
import { n as buildGatewayDiscoveryTarget, r as serializeGatewayDiscoveryBeacon } from "./gateway-discovery-targets-BLlhMUdW.mjs";
import { a as renderProbeSummaryLine, c as resolveTargets, d as pickGatewaySelfPresence, i as isScopeLimitedProbeFailure, l as sanitizeSshTarget, n as isPostConnectProbeFailure, o as resolveAuthForTarget, r as isProbeReachable, s as resolveProbeBudgetMs, t as extractConfigSummary, u as summarizeGatewayProbeCapability } from "./helpers-B7QUNUvT.mjs";
//#region src/commands/gateway-status.ts
function buildSshTarget(e) {
const t = normalizeOptionalString(e.host) ?? "";
if (!t) return null;
const n = normalizeOptionalString(e.user) ?? "";
const r = n ? `${n}@${t}` : t;
const i = e.port ?? 22;
if (e.port !== void 0 && i) return `${r}:${i}`;
return r;
}
async function gatewayStatusCommand(e, t) {
await ensureExplicitGatewayAuth({
urlOverride: e.url?.trim(),
urlOverrideSource: "cli",
explicitAuth: resolveExplicitGatewayAuth(e),
errorHint: "Fix: pass --token or --password with --url."
});
const n = Date.now();
const r = await readBestEffortConfig();
const i = isRich() && e.json !== true;
const a = parseTimeoutMsWithFallback(e.timeout, 3e3, { invalidType: "error" });
const o = parseGatewayPortOption(e.port);
const s = resolveWideAreaDiscoveryDomain({ configDomain: r.discovery?.wideArea?.domain });
const c = resolveTargets(r, e.url, o);
const l = pickBestEffortPrimaryTailnetIPv4();
const u = o ?? resolveGatewayPort(r);
const d = r.gateway?.tls?.enabled === true ? "wss" : "ws";
const f = {
localLoopbackUrl: `${d}://127.0.0.1:${u}`,
localTailnetUrl: l ? `${d}://${l}:${u}` : null,
tailnetIPv4: l ?? null
};
const p = o ?? resolveGatewaySshRemotePort(r);
const m = Math.min(1200, a);
const h = typeof e.url === "string" && e.url.trim().length > 0;
const g = o === void 0 || h;
let _ = sanitizeSshTarget(e.ssh) ?? (g ? sanitizeSshTarget(r.gateway?.remote?.sshTarget) : null);
let v = sanitizeSshTarget(e.sshIdentity) ?? (g ? sanitizeSshTarget(r.gateway?.remote?.sshIdentity) : null);
if (!_ && g) {
const e = normalizeOptionalString(r.gateway?.remote?.url);
const t = e ? URL.parse(e)?.hostname : void 0;
_ = t ? buildSshTarget({
user: process.env.USER,
host: t
}) : null;
}
const y = _;
const b = c.find((e) => e.kind === "configRemote");
const x = resolveGatewayDeviceAuthRoute({
config: r,
url: b?.url ?? "",
remote: true,
configuredRemote: true
}).sshTunnel;
const S = b?.url.startsWith("wss://") && sanitizeSshTarget(x?.target) === y && x?.remotePort === p ? b.url : void 0;
const C = r.gateway?.tls?.enabled === true ? await import("./gateway-6xEaCcr5.mjs").then(({ inspectGatewayTlsCertificate: e }) => e(r.gateway?.tls)) : void 0;
const w = new AbortController();
const T = performance.now() + a;
const remainingMs = () => Math.max(0, Math.ceil(T - performance.now()));
let E = false;
const D = scheduleAbsoluteDeadline(T, () => {
E = true;
w.abort();
}, () => performance.now());
let O;
const onSignal = (e) => {
if (!O) {
O = e;
w.abort();
}
};
const onSigInt = () => onSignal("SIGINT");
const onSigTerm = () => onSignal("SIGTERM");
process.on("SIGINT", onSigInt);
process.on("SIGTERM", onSigTerm);
const k = await (async () => {
try {
return await withProgress({
label: "Inspecting gateways…",
indeterminate: true,
enabled: e.json !== true
}, async () => {
const t = discoverGatewayBeacons({
timeoutMs: m,
deadlineMs: T,
signal: w.signal,
wideAreaDomain: s
}).catch(() => []);
const probeTarget = async (t, n) => {
const i = await resolveAuthForTarget(r, t, {
token: readStringValue(e.token),
password: readStringValue(e.password)
});
const a = await probeGateway({
url: t.url,
config: r,
configuredRemote: t.kind === "configRemote",
...t.kind === "sshTunnel" ? {
originScopedDeviceAuth: true,
sshTunnel: {
target: y ?? _ ?? "",
remotePort: p,
...v ? { identity: v } : {}
},
preparedSshTunnel: n ?? void 0
} : t.kind !== "localLoopback" ? { originScopedDeviceAuth: true } : {},
auth: {
token: i.token,
password: i.password
},
tlsFingerprint: t.kind === "localLoopback" && t.url.startsWith("wss://") ? C?.ok ? C.value.fingerprintSha256 : void 0 : void 0,
timeoutMs: Math.max(1, resolveProbeBudgetMs(remainingMs(), t)),
signal: w.signal
});
if (E && a.error === "aborted") a.error = "timeout";
return {
target: t,
probe: a,
configSummary: a.configSnapshot ? extractConfigSummary(a.configSnapshot) : null,
self: pickGatewaySelfPresence(a.presence),
authDiagnostics: i.diagnostics ?? []
};
};
const n = c.map((e) => ({
target: e,
result: probeTarget(e)
}));
let i = null;
let a = false;
const probeTunnel = async () => {
if (!_ && e.sshAuto) {
const { parseSshTarget: e } = await import("./ssh-tunnel-3VCewHVk.mjs");
const n = normalizeOptionalString(process.env.USER) ?? "";
for (const r of await t) {
const t = buildGatewayDiscoveryTarget(r, { sshUser: n }).sshTarget;
if (t && e(t)) {
_ = t;
break;
}
}
}
if (!_) return null;
let o;
try {
if (y) {
const [{ resolveSshConfig: e }, { parseSshTarget: t }] = await Promise.all([import("./ssh-config-B9J66WNM.mjs"), import("./ssh-tunnel-3VCewHVk.mjs")]);
const n = t(y);
if (n) {
const t = await e(n, {
explicitPort: /:\d+$/.test(y.trim()),
identity: v ?? void 0,
timeoutMs: Math.min(800, remainingMs()),
signal: w.signal
});
if (t) {
const e = buildSshTarget({
user: t.user ?? n.user,
host: t.host ?? n.host,
port: t.port ?? n.port
});
if (e) {
_ = e;
if (!v) v = t.identityFiles.find((e) => normalizeOptionalString(e)) ?? null;
}
}
}
}
await Promise.all(n.filter(({ target: e }) => {
const t = URL.parse(e.url);
return t && isLoopbackHost(t.hostname) && Number(t.port || (t.protocol === "wss:" ? 443 : 80)) === p;
}).map(({ result: e }) => e));
if (w.signal.aborted) {
i = E ? "timeout" : "Aborted";
return null;
}
const { startSshPortForward: e } = await import("./ssh-tunnel-3VCewHVk.mjs");
o = await e({
target: _,
identity: v ?? void 0,
hostKeyPolicy: r.gateway?.remote?.sshHostKeyPolicy,
localPortPreferred: p,
remotePort: p,
timeoutMs: Math.min(1500, remainingMs()),
signal: w.signal
});
} catch (e) {
i = isAbortError(e) ? E ? "timeout" : "Aborted" : formatErrorMessage(e);
return null;
}
a = true;
try {
return await probeTarget({
id: "sshTunnel",
kind: "sshTunnel",
url: S ?? `ws://127.0.0.1:${o.localPort}`,
active: true,
tunnel: {
kind: "ssh",
target: _,
localPort: o.localPort,
remotePort: p,
pid: o.pid
}
}, o);
} finally {
try {
await o.stop();
} catch {}
}
};
const [o, l, u] = await Promise.all([
t,
Promise.all(n.map(({ result: e }) => e)),
probeTunnel()
]);
return {
discovery: o,
probed: u ? [u, ...l.filter((e) => e.target.url !== u.target.url)] : l,
sshTarget: _,
sshTunnelStarted: a,
sshTunnelError: i
};
});
} finally {
D();
process.off("SIGINT", onSigInt);
process.off("SIGTERM", onSigTerm);
}
})();
if (O) {
t.exit(O === "SIGINT" ? 130 : 143);
return;
}
const A = k.probed.filter((e) => isProbeReachable(e.probe));
const j = A.find((e) => e.target.kind === "explicit") ?? A.find((e) => e.target.kind === "sshTunnel") ?? A.find((e) => e.target.kind === "configRemote") ?? A.find((e) => e.target.kind === "localLoopback") ?? null;
const M = [];
if (k.sshTarget && !k.sshTunnelStarted) M.push({
code: "ssh_tunnel_failed",
message: k.sshTunnelError ? `SSH tunnel failed: ${k.sshTunnelError}` : "SSH tunnel failed to start; falling back to direct checks."
});
if (C && !C.ok && C.error) M.push({
code: "local_tls_runtime_unavailable",
message: `Local gateway TLS is enabled but OpenClaw could not load the local certificate fingerprint: ${C.error}`,
targetIds: ["localLoopback"]
});
if (A.length === 0 && k.discovery.length === 0) M.push({
code: "no_gateway_reachable",
message: "No gateway answered any check and Bonjour discovery returned no local gateways. Run `openclaw gateway status --deep --require-rpc` to inspect service state, config paths, listener owners, and logs; include `ss -ltnp` or `lsof -nP -iTCP:<port> -sTCP:LISTEN` for the configured port when filing a report.",
targetIds: k.probed.map((e) => e.target.id)
});
const N = A.map((e) => {
if (!e.self) return null;
const t = normalizeLowercaseStringOrEmpty(e.self.host);
const n = normalizeLowercaseStringOrEmpty(e.self.ip);
const r = normalizeLowercaseStringOrEmpty(e.self.instanceId);
const i = normalizeLowercaseStringOrEmpty(e.self.deviceId);
const a = r ? `instance:${r}` : i ? `device:${i}` : "";
if (!t && !n || !a) return null;
return `${t}\0${n}\0${a}`;
});
if (A.length > 1 && (N.some((e) => e === null) || new Set(N).size > 1)) M.push({
code: "multiple_gateways",
message: "Unconventional setup: multiple reachable gateway identities detected. Usually one gateway per network is recommended unless you intentionally run isolated profiles, like a rescue bot (see docs: /gateway#multiple-gateways-same-host).",
targetIds: A.map((e) => e.target.id)
});
for (const e of k.probed) {
if (e.authDiagnostics.length === 0 || isProbeReachable(e.probe)) continue;
for (const t of e.authDiagnostics) M.push({
code: "auth_secretref_unresolved",
message: t,
targetIds: [e.target.id]
});
}
for (const e of k.probed.filter((e) => isScopeLimitedProbeFailure(e.probe))) M.push({
code: "probe_scope_limited",
message: "Read-check diagnostics are limited by gateway scopes (missing operator.read). Connection succeeded, but read-only status calls are incomplete. Hint: pair device identity or use credentials with operator.read.",
targetIds: [e.target.id]
});
for (const e of k.probed.filter((e) => isPostConnectProbeFailure(e.probe) && !isScopeLimitedProbeFailure(e.probe))) {
const t = e.probe.error ? `: ${e.probe.error}` : ".";
M.push({
code: "probe_detail_failed",
message: `Gateway accepted the WebSocket connection, but follow-up read diagnostics failed${t}`,
targetIds: [e.target.id]
});
}
const P = summarizeGatewayProbeCapability(A.map((e) => e.probe));
if (e.json) {
const e = k.probed.some((e) => isPostConnectProbeFailure(e.probe));
writeRuntimeJson(t, {
ok: A.length > 0,
degraded: e,
capability: P,
ts: Date.now(),
durationMs: Date.now() - n,
timeoutMs: a,
primaryTargetId: j?.target.id ?? null,
warnings: M,
network: f,
discovery: {
timeoutMs: m,
count: k.discovery.length,
beacons: k.discovery.map(serializeGatewayDiscoveryBeacon)
},
targets: k.probed.map((e) => ({
id: e.target.id,
kind: e.target.kind,
url: e.target.url,
active: e.target.active,
tunnel: e.target.tunnel ?? null,
connect: {
ok: isProbeReachable(e.probe),
rpcOk: e.probe.ok,
scopeLimited: isScopeLimitedProbeFailure(e.probe),
latencyMs: e.probe.connectLatencyMs,
error: e.probe.error,
close: e.probe.close
},
auth: e.probe.auth,
server: e.probe.server,
self: e.self,
config: e.configSummary,
health: e.probe.health,
summary: e.probe.status,
presence: e.probe.presence
}))
});
if (A.length === 0) t.exit(1);
return;
}
const F = A.length > 0;
t.log(colorize(i, theme.heading, "Gateway Status"));
t.log(F ? `${colorize(i, theme.success, "Reachable")}: yes` : `${colorize(i, theme.error, "Reachable")}: no`);
t.log(`${colorize(i, theme.info, "Capability")}: ${P.replaceAll("_", "-")}`);
t.log(colorize(i, theme.muted, `Check budget: ${a}ms`));
if (M.length > 0) {
t.log("");
t.log(colorize(i, theme.warn, "Warning:"));
for (const e of M) t.log(`- ${e.message}`);
}
t.log("");
t.log(colorize(i, theme.heading, "Discovery (this machine)"));
const I = s ? `local. + ${s}` : "local.";
t.log(`Found ${k.discovery.length} ${k.discovery.length > 0 ? "gateway(s)" : "gateways"} via Bonjour (${I})`);
if (k.discovery.length === 0) t.log(colorize(i, theme.muted, "Tip: if the gateway is remote, mDNS won’t cross networks; use Wide-Area Bonjour (split DNS) or SSH tunnels."));
t.log("");
t.log(colorize(i, theme.heading, "Targets"));
for (const e of k.probed) {
const n = e.target;
const r = n.kind === "localLoopback" ? "Local loopback" : n.kind === "sshTunnel" ? "Remote over SSH" : n.kind === "configRemote" ? n.active ? "Remote (configured)" : "Remote (configured, inactive)" : "URL (explicit)";
t.log(`${colorize(i, theme.heading, r)} ${colorize(i, theme.muted, n.url)}`);
t.log(` ${renderProbeSummaryLine(e.probe, i)}`);
if (e.target.tunnel?.kind === "ssh") t.log(` ${colorize(i, theme.muted, "ssh")}: ${colorize(i, theme.command, e.target.tunnel.target)}`);
if (e.probe.ok && e.self) {
const n = e.self.host ?? "unknown";
const r = e.self.ip ? ` (${e.self.ip})` : "";
const a = e.self.platform ? ` · ${e.self.platform}` : "";
const o = e.self.version ? ` · app ${e.self.version}` : "";
t.log(` ${colorize(i, theme.info, "Gateway")}: ${n}${r}${a}${o}`);
}
if (e.configSummary) {
const n = e.configSummary.discovery.wideAreaEnabled === true ? "enabled" : e.configSummary.discovery.wideAreaEnabled === false ? "disabled" : "unknown";
t.log(` ${colorize(i, theme.info, "Wide-area discovery")}: ${n}`);
}
t.log("");
}
if (!F) t.exit(1);
}
//#endregion
export { gatewayStatusCommand };