openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
582 lines (581 loc) • 29 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { D as parseStrictPositiveInteger } from "./number-coercion-D6u-4YD8.mjs";
import { S as MACHINE_OUTPUT_JSON_OPTION_DESCRIPTION } from "./argv-CbnKpH-r.mjs";
import "./src-H3RMXyFL.mjs";
import { n as formatByteSize } from "./format-KwhqGIVR.mjs";
import { r as defaultRuntime, t as ExitError } from "./runtime-B-SLYP-m.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { o as getAsyncWorkSignal } from "./async-work-scope-BXagjUap.mjs";
import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs";
import { n as createLazyPromise } from "./lazy-promise-DiCvjz9w.mjs";
import { n as monotonicNow } from "./monotonic-time-Cc4T2fkU.mjs";
import { n as isRich, r as theme, t as colorize } from "./theme-BOI0xyRZ.mjs";
import { r as formatCliJsonFailure, u as rethrowExpectedCliError } from "./failure-output-DVVDqwuu.mjs";
import { t as formatDocsLink } from "./links-41lO3DKP.mjs";
import { n as inheritOptionFromParent } from "./command-options-D76J8Wl7.mjs";
import { o as resolveGatewayRpcOptions, r as callGatewayFromCliWithTransport, s as resolveGatewayRpcOptionsWithLocalPort, t as addGatewayClientOptions } from "./gateway-rpc-CxUN2f1a.mjs";
import { t as addGatewayServiceCommands } from "./register-service-commands-DyRFDtr8.mjs";
import { t as isGatewayMachineOutput } from "./output-mode-BlxuA5LZ.mjs";
import { n as parseTimeoutMsWithFallback } from "./parse-timeout-qqSdJSy9.mjs";
import { n as formatHelpExamples } from "./help-format-D2ytHW5E.mjs";
import { t as parseOptionalPositiveInteger } from "./parse-positive-integer-DrSNo4LV.mjs";
import { n as setCommandJsonMode } from "./json-mode-DF5JGxtm.mjs";
import { t as addGatewayRunCommand } from "./run-command-CyHSIuiw.mjs";
import { randomBytes } from "node:crypto";
import { setTimeout } from "node:timers/promises";
//#region src/cli/gateway-cli/gateway-action.ts
function gatewayAction(e, t) {
return async function(...n) {
const r = Boolean(this.opts().json);
try {
await e.apply(this, n);
} catch (e) {
if (e instanceof ExitError) throw e;
if (!r) rethrowExpectedCliError(e);
if (r) {
const { formatGatewayAuthErrorJson: t, formatGatewayClientRequestErrorJson: n, formatGatewayTransportErrorJson: r } = await import("./call-CT5jlfNe.mjs");
defaultRuntime.writeJson(t(e) ?? n(e) ?? r(e) ?? formatCliJsonFailure(e));
defaultRuntime.exit(1);
return;
}
const n = formatErrorMessage(e);
defaultRuntime.error(t ? `${t}: ${n}` : n);
defaultRuntime.exit(1);
}
};
}
//#endregion
//#region src/cli/gateway-cli/register-recover-lock.ts
function addGatewayLockRecoveryCommand(e) {
e.command("recover-lock").description("Inspect or explicitly recover an unchanged Gateway state lock").option("--confirm <fingerprint>", "Recover only the lock record shown by a prior inspection").option("--json", "Output JSON", false).action(gatewayAction(async (e) => {
const { inspectGatewayLockRecovery: t, recoverGatewayLock: n } = await import("./gateway-lock-recovery-zdsmkc2b.mjs");
if (e.confirm) {
const t = await n({ confirmation: e.confirm });
if (e.json) defaultRuntime.writeJson(t);
else defaultRuntime.log("Gateway lock recovery completed. Start the Gateway again.");
return;
}
const r = await t();
const i = formatCliCommand(`openclaw gateway recover-lock --confirm ${r.confirmation}`);
if (e.json) {
defaultRuntime.writeJson({
present: r.present,
holders: r.holders,
confirmation: r.confirmation,
command: i
});
return;
}
if (!r.present) {
defaultRuntime.log("No Gateway lock or owner lease is present.");
return;
}
for (const e of r.holders) defaultRuntime.log(e);
defaultRuntime.log("Stop the recorded holder through its service manager or container first. If you have confirmed it stopped, recover exactly these unchanged records with:");
defaultRuntime.log(i);
}, "Gateway lock recovery failed"));
}
//#endregion
//#region src/infra/restart-handoff-contract.ts
const GATEWAY_RESTART_HANDOFF_PROTOCOL = "openclaw.gateway.restart-handoff";
//#endregion
//#region src/cli/gateway-cli/register-restart-handoff.ts
function writeRestartHandoffError(e) {
defaultRuntime.writeJson({
ok: false,
protocol: GATEWAY_RESTART_HANDOFF_PROTOCOL,
protocolVersion: 1,
status: "error",
reason: e
});
}
function collectExpectedPid(e, t) {
return Array.isArray(t) ? [...t, e] : [t, e];
}
function addGatewayRestartHandoffCommands(e) {
const t = e.command("restart-handoff", { hidden: true });
t.command("capabilities").description("Report the gateway restart-handoff machine contract").option("--json", MACHINE_OUTPUT_JSON_OPTION_DESCRIPTION).action(() => {
defaultRuntime.writeJson({
ok: true,
protocol: GATEWAY_RESTART_HANDOFF_PROTOCOL,
protocolVersion: 1,
operations: ["consume"]
});
});
t.command("consume").description("Atomically consume a gateway restart handoff").helpOption(false).allowUnknownOption().allowExcessArguments().option("--expected-pid [pid]", "PID of the exited gateway process", collectExpectedPid, []).option("--json", MACHINE_OUTPUT_JSON_OPTION_DESCRIPTION).action(async (e, t) => {
const n = Array.isArray(e.expectedPid) ? e.expectedPid : [];
const r = t.args.length === 0 && n.length === 1 ? parseStrictPositiveInteger(n[0]) : void 0;
if (r === void 0) {
writeRestartHandoffError("invalid-expected-pid");
defaultRuntime.exit(2);
return;
}
try {
const { consumeGatewayRestartHandoffSync: e } = await import("./restart-handoff-BVauZkgo.mjs");
const t = e({ expectedPid: r });
defaultRuntime.writeJson({
ok: true,
protocol: GATEWAY_RESTART_HANDOFF_PROTOCOL,
protocolVersion: 1,
...t
});
} catch (e) {
defaultRuntime.error(`Gateway restart handoff consume failed: ${String(e)}`);
writeRestartHandoffError("store-unavailable");
defaultRuntime.exit(1);
}
});
}
//#endregion
//#region src/cli/gateway-cli/stability-bundle-target.ts
function normalizeStabilityBundleTarget(e) {
if (e === void 0 || e === false) return null;
const t = normalizeOptionalString(e);
if (typeof e === "string" && t === void 0) throw new Error("--bundle must be a non-empty path or \"latest\".");
return t ?? "latest";
}
//#endregion
//#region src/cli/gateway-cli/stability-format.ts
function formatStabilityBytes(e) {
if (e === void 0) return "n/a";
return formatByteSize(e, {
style: "iec",
maxUnit: "giga",
separator: " ",
fractionDigits: (e, t) => t === "byte" || e >= 100 ? 0 : 1
});
}
function formatStabilityEvent(e) {
return [
new Date(e.ts).toISOString(),
`#${e.seq}`,
e.type,
e.provider ? `provider=${e.provider}` : "",
e.model ? `model=${e.model}` : "",
e.durationMs !== void 0 ? `wall=${Math.round(e.durationMs)}ms` : "",
e.providerProcessingMs !== void 0 ? `processing=${Math.round(e.providerProcessingMs)}ms` : "",
e.providerWaitEstimateMs !== void 0 ? `wait~=${Math.round(e.providerWaitEstimateMs)}ms` : "",
e.failureKind ? `failure=${e.failureKind}` : "",
e.level ? `level=${e.level}` : "",
e.action ? `action=${e.action}` : "",
e.outcome ? `outcome=${e.outcome}` : "",
e.surface ? `surface=${e.surface}` : "",
e.channel ? `channel=${e.channel}` : "",
e.pluginId ? `plugin=${e.pluginId}` : "",
e.reason ? `reason=${e.reason}` : "",
e.bytes !== void 0 ? `bytes=${formatStabilityBytes(e.bytes)}` : "",
e.limitBytes !== void 0 ? `limit=${formatStabilityBytes(e.limitBytes)}` : "",
e.queueDepth !== void 0 ? `queueDepth=${e.queueDepth}` : "",
e.queueLength !== void 0 ? `queueLength=${e.queueLength}` : "",
e.droppedEvents !== void 0 ? `dropped=${e.droppedEvents}` : "",
e.maxQueueLength !== void 0 ? `maxQueue=${e.maxQueueLength}` : "",
e.queued !== void 0 ? `queued=${e.queued}` : "",
e.memory ? `rss=${formatStabilityBytes(e.memory.rssBytes)}` : "",
e.memory ? `heap=${formatStabilityBytes(e.memory.heapUsedBytes)}` : ""
].filter(Boolean).join(" ");
}
//#endregion
//#region src/cli/gateway-cli/suspend-cli.ts
const MIN_SUSPEND_POLL_DELAY_MS = 50;
async function runGatewaySuspend(e, t) {
const n = e.requestId;
const r = n === void 0 ? `cli-${randomBytes(4).toString("hex")}` : n.trim();
if (n !== void 0 && (!r || r.length > 128)) throw new Error("--request-id must contain 1 to 128 characters");
let i;
const a = e.waitSeconds;
if (a !== void 0) {
const e = typeof a === "number" ? a : Number(a.trim() || NaN);
if (!Number.isFinite(e) || e < 0) throw new Error("--wait must be a non-negative number of seconds");
i = Math.floor(e * 1e3);
if (!Number.isSafeInteger(i)) throw new Error("--wait is too large");
}
const o = i === void 0 ? void 0 : monotonicNow() + i;
const s = i === void 0 ? 1 : Math.ceil(i / MIN_SUSPEND_POLL_DELAY_MS) + 1;
let c;
const l = getAsyncWorkSignal();
for (let n = 0; n < s; n += 1) {
if (l?.aborted) return;
if (n > 0 && o !== void 0 && monotonicNow() >= o) break;
c = await t.callGateway("gateway.suspend.prepare", e.rpcOpts, { requestId: r });
if (c.status === "ready") {
if (e.json) {
t.runtime.writeJson({
...c,
requestId: r
});
return;
}
const n = isRich();
t.runtime.log(colorize(n, theme.success, "Gateway suspension prepared."));
t.runtime.log(`${colorize(n, theme.muted, "Suspension ID:")} ${c.suspensionId}`);
t.runtime.log(`${colorize(n, theme.muted, "Expires:")} ${new Date(c.expiresAtMs).toISOString()} (${c.expiresAtMs} ms)`);
const i = e.rpcOpts.localPortOverride;
const a = `openclaw gateway resume ${c.suspensionId}`;
t.runtime.log(`Resume with: ${formatCliCommand(i === void 0 ? a : `${a} --port ${i}`)}`);
return;
}
if (l?.aborted) return;
if (c.status === "draining") throw new Error("Gateway suspension unexpectedly entered drain mode");
if (o === void 0) break;
const i = o - monotonicNow();
if (i <= 0) break;
const a = Math.min(i, Math.max(MIN_SUSPEND_POLL_DELAY_MS, c.retryAfterMs));
try {
await setTimeout(a, void 0, { signal: l });
} catch (e) {
if (!l?.aborted) throw e;
return;
}
}
if (!c || c.status !== "busy") throw new Error("Gateway suspension polling ended without a result");
if (e.json) {
t.runtime.writeJson({
...c,
requestId: r
});
t.runtime.exit(1);
return;
}
const u = o === void 0 ? "Retry later or use --wait <seconds>." : "Timed out waiting for the Gateway to become idle.";
const d = c.blockers.map((e) => `- ${e.message}`);
const f = [`Gateway suspension is busy (${c.reason}; ${c.activeCount} active).`, ...d.length > 0 ? ["Blockers:", ...d] : []].join("\n");
throw new Error(`${f}\n${u}`);
}
async function runGatewayResume(e, t) {
const n = await t.callGateway("gateway.suspend.resume", e.rpcOpts, { suspensionId: e.suspensionId });
if (e.json) {
t.runtime.writeJson(n);
return;
}
t.runtime.log(n.resumed ? "Gateway resumed." : "No matching suspension was held (lease already expired or resumed); gateway is running.");
}
//#endregion
//#region src/cli/gateway-cli/register.ts
const loadWideAreaDnsModule = createLazyPromise(() => import("./widearea-dns-Das_oauP.mjs"));
const loadCostUsageRenderer = createLazyPromise(() => import("./usage-cost-renderer-CgxNq1F2.mjs"));
const loadStabilityBundleModule = createLazyPromise(() => import("./diagnostic-stability-bundle-BqD2A-5e.mjs"));
const DEFAULT_GATEWAY_RPC_TIMEOUT_MS = 1e4;
const SETUP_INFERENCE_DETECT_RPC_TIMEOUT_MS = 4e4;
function gatewayCallOpts(e) {
return addGatewayClientOptions(e, { timeoutMs: DEFAULT_GATEWAY_RPC_TIMEOUT_MS }).option("--json", "Output JSON", false);
}
async function callGatewayReadOnlyCli(e, t, n) {
return await callGatewayFromCliWithTransport(e, t, n, {
defaultTimeoutMs: DEFAULT_GATEWAY_RPC_TIMEOUT_MS,
sharedStateMode: "read-only"
});
}
function parseGatewayCallParams(e = "{}") {
try {
return JSON.parse(e);
} catch {
throw new Error("--params must be valid JSON.");
}
}
function parseDaysOption(e) {
if (typeof e === "number" && Number.isFinite(e)) return Math.max(1, Math.floor(e));
if (typeof e === "string") {
const t = parseStrictPositiveInteger(e);
if (t !== void 0) return t;
throw new Error(`Invalid --days. Use a positive integer, e.g. --days 30. Received: "${e}".`);
}
return 30;
}
async function printGatewayResult(e, t, n) {
if (e) {
defaultRuntime.writeJson(t);
return;
}
for (const e of await n(isRich())) defaultRuntime.log(e);
}
function renderStabilitySummary(e, t) {
const n = [colorize(t, theme.heading, "Gateway Stability"), `${colorize(t, theme.muted, "Events:")} ${e.count}/${e.capacity}${e.dropped > 0 ? ` · dropped=${e.dropped}` : ""}`];
const r = Object.entries(e.summary.byType).toSorted((e, t) => t[1] - e[1] || e[0].localeCompare(t[0])).slice(0, 8).map(([e, t]) => `${e}=${t}`).join(", ");
if (r) n.push(`${colorize(t, theme.muted, "Types:")} ${r}`);
const i = e.summary.memory;
if (i) n.push(`${colorize(t, theme.muted, "Memory:")} rss=${formatStabilityBytes(i.latest?.rssBytes)} heap=${formatStabilityBytes(i.latest?.heapUsedBytes)} maxRss=${formatStabilityBytes(i.maxRssBytes)} pressure=${i.pressureCount}`);
const a = e.summary.payloadLarge;
if (a) {
const e = Object.entries(a.bySurface).toSorted((e, t) => t[1] - e[1] || e[0].localeCompare(t[0])).map(([e, t]) => `${e}=${t}`).join(", ");
n.push(`${colorize(t, theme.muted, "Large payloads:")} total=${a.count} rejected=${a.rejected} truncated=${a.truncated} chunked=${a.chunked}${e ? ` · ${e}` : ""}`);
}
if (e.events.length > 0) {
n.push(colorize(t, theme.muted, "Recent:"));
for (const t of e.events) n.push(` ${formatStabilityEvent(t)}`);
}
return n;
}
async function writeSupportExportFromCli(e) {
const { writeDiagnosticSupportExport: t } = await import("./diagnostic-support-export-EYuofcPl.mjs");
const n = {
url: e.rpc?.url,
token: e.rpc?.token,
password: e.rpc?.password,
timeout: e.rpc?.timeout ?? "3000",
json: true
};
const r = await t({
outputPath: e.output,
logLimit: parseOptionalPositiveInteger(e.logLines, "--log-lines", "."),
logMaxBytes: parseOptionalPositiveInteger(e.logBytes, "--log-bytes", "."),
stabilityBundle: e.stabilityBundle,
readStatusSnapshot: async () => {
const { gatherDaemonStatus: e } = await import("./status.gather-zCT6rmfM.mjs");
return await e({
rpc: n,
probe: true,
requireRpc: false,
deep: false
});
},
readHealthSnapshot: async () => await callGatewayReadOnlyCli("health", n),
readGatewayCapabilities: async () => await callGatewayReadOnlyCli("diagnostics.capabilities", n)
});
await printGatewayResult(e.json, r, (e) => [
colorize(e, theme.heading, "Diagnostics export"),
`${colorize(e, theme.muted, "Path:")} ${r.path}`,
`${colorize(e, theme.muted, "Size:")} ${formatStabilityBytes(r.bytes)}`,
`${colorize(e, theme.muted, "Files:")} ${r.manifest.contents.length}`,
`${colorize(e, theme.muted, "Privacy:")} payload-free stability, sanitized logs/status/health/config`
]);
}
function registerGatewayCli(e) {
const t = addGatewayRunCommand(e.command("gateway").description("Run, inspect, and query the WebSocket Gateway").addHelpText("after", () => `\n${theme.heading("Examples:")}\n${formatHelpExamples([
["openclaw gateway run", "Run the gateway in the foreground."],
["openclaw gateway status", "Show service status plus connectivity/capability."],
["openclaw gateway auth-token --show", "Reveal the shared token interactively."],
["openclaw gateway discover", "Find local and wide-area gateway beacons."],
["openclaw gateway stability", "Show recent stability diagnostics."],
["openclaw gateway call health", "Call a gateway RPC method directly."]
])}\n\n${theme.muted("Docs:")} ${formatDocsLink("/cli/gateway", "docs.openclaw.ai/cli/gateway")}\n`));
addGatewayRunCommand(t.command("run").description("Run the WebSocket Gateway (foreground)"));
addGatewayServiceCommands(t, { statusDescription: "Show gateway service status + check connectivity/capability" });
addGatewayRestartHandoffCommands(t);
addGatewayLockRecoveryCommand(t);
setCommandJsonMode(t, "output", ({ argv: e }) => isGatewayMachineOutput(e));
t.command("auth-token").description("Reveal the configured shared Gateway token").option("--show", "Print the token to an interactive terminal", false).action(gatewayAction(async (e) => {
if (!e.show) throw new Error("Pass --show to confirm that you want to print the Gateway token to this terminal.");
const { gatewayAuthTokenCommand: t } = await import("./gateway-auth-token-1j5ZaBRx.mjs");
await t(defaultRuntime);
}, "Gateway auth token failed"));
gatewayCallOpts(t.command("call").description("Call a Gateway method").argument("<method>", "Method name (health/status/system-presence/cron.*)").option("--expect-url <url>", "Fail if the resolved Gateway URL differs; preserves configured authentication").option("--params <json>", "JSON object string for params", "{}").action(gatewayAction(async (e, t, n) => {
const r = e === "openclaw.setup.detect" && n.getOptionValueSource("timeout") === "default" ? {
...t,
timeout: String(SETUP_INFERENCE_DETECT_RPC_TIMEOUT_MS)
} : t;
const i = resolveGatewayRpcOptionsWithLocalPort(r, n);
const a = await callGatewayReadOnlyCli(e, i, parseGatewayCallParams(String(t.params ?? "{}")));
if (i.json) {
defaultRuntime.writeJson(a);
return;
}
const o = isRich();
defaultRuntime.log(`${colorize(o, theme.heading, "Gateway call")}: ${colorize(o, theme.muted, String(e))}`);
defaultRuntime.writeJson(a);
}, "Gateway call failed")));
gatewayCallOpts(t.command("suspend").description("Prepare the Gateway for cooperative host suspension").option("--request-id <id>", "Stable suspension request id").option("--wait <seconds>", "Wait up to this many seconds for active work to drain").action(gatewayAction(async (e, t) => {
const n = resolveGatewayRpcOptionsWithLocalPort(e, t);
await runGatewaySuspend({
rpcOpts: n,
requestId: e.requestId,
waitSeconds: e.wait,
json: Boolean(n.json)
}, {
callGateway: callGatewayReadOnlyCli,
runtime: defaultRuntime
});
}, "Gateway suspend failed")));
gatewayCallOpts(t.command("resume").description("Release a cooperative Gateway suspension").argument("<suspensionId>", "Suspension id returned by gateway suspend").action(gatewayAction(async (e, t, n) => {
const r = resolveGatewayRpcOptionsWithLocalPort(t, n);
await runGatewayResume({
rpcOpts: r,
suspensionId: String(e),
json: Boolean(r.json)
}, {
callGateway: callGatewayReadOnlyCli,
runtime: defaultRuntime
});
}, "Gateway resume failed")));
gatewayCallOpts(t.command("usage-cost").description("Fetch usage cost summary from session logs").option("--days <days>", "Number of days to include", "30").option("--agent <id>", "Scope the cost summary to a specific agent id").option("--all-agents", "Aggregate the cost summary across all agents", false).action(gatewayAction(async (e, t) => {
const n = resolveGatewayRpcOptionsWithLocalPort(e, t);
const r = parseDaysOption(e.days);
const i = typeof e.agent === "string" ? e.agent.trim() : void 0;
if (i && e.allAgents) throw new Error("Use --agent or --all-agents, not both");
const a = await callGatewayReadOnlyCli("usage.cost", n, {
days: r,
...i ? { agentId: i } : {},
...e.allAgents ? { agentScope: "all" } : {}
});
await printGatewayResult(n.json, a, async (e) => (await loadCostUsageRenderer()).renderGatewayCostUsageSummary(a, r, e));
}, "Gateway usage cost failed")));
gatewayCallOpts(t.command("health").description("Fetch Gateway health").action(gatewayAction(async (e, t) => {
const n = resolveGatewayRpcOptionsWithLocalPort(e, t);
let r;
try {
r = await callGatewayReadOnlyCli("health", n);
} catch (e) {
const { emitReachableGatewayAuthDiagnostic: t, readNonObservingHealthConfig: r } = await import("./health-DfcXdtuz.mjs");
if (await t({
error: e,
config: n.config ?? await r(),
runtime: defaultRuntime,
timeoutMs: parseTimeoutMsWithFallback(n.timeout, 1e4, { invalidType: "error" }),
token: n.token,
password: n.password,
localPortOverride: n.localPortOverride,
json: Boolean(n.json)
})) return;
throw e;
}
if (n.json) {
defaultRuntime.writeJson(r);
return;
}
const [{ formatHealthChannelLines: i }, { styleHealthChannelLine: a }] = await Promise.all([import("./health-DfcXdtuz.mjs"), import("./terminal-core/health-style.js")]);
const o = isRich();
const s = r && typeof r === "object" ? r : {};
const c = typeof s.durationMs === "number" ? s.durationMs : null;
defaultRuntime.log(colorize(o, theme.heading, "Gateway Health"));
defaultRuntime.log(`${colorize(o, theme.success, "OK")}${c != null ? ` (${c}ms)` : ""}`);
if (s.channels && typeof s.channels === "object") for (const e of i(s)) defaultRuntime.log(a(e, o));
}, void 0)));
gatewayCallOpts(t.command("stability").description("Fetch payload-free Gateway stability diagnostics").option("--limit <limit>", "Maximum number of recent events", "25").option("--type <type>", "Filter by diagnostic event type").option("--since-seq <seq>", "Only include events after this sequence").option("--bundle [path]", "Read a persisted stability bundle instead of calling Gateway; pass \"latest\" for newest").option("--export", "Write a shareable support diagnostics export", false).option("--output <path>", "Diagnostics export output .zip path").action(gatewayAction(async (e, t) => {
const { normalizeDiagnosticStabilityQuery: n, selectDiagnosticStabilitySnapshot: r } = await import("./diagnostic-stability-B_Qw7ud0.mjs");
const i = resolveGatewayRpcOptions(e, t);
const a = n({
limit: e.limit,
sinceSeq: e.sinceSeq,
type: e.type
}, { defaultLimit: 25 });
const o = normalizeStabilityBundleTarget(e.bundle);
if (e.export) {
await writeSupportExportFromCli({
json: i.json,
output: e.output,
stabilityBundle: o ?? "latest",
rpc: i
});
return;
}
if (o) {
const { readDiagnosticStabilityBundleFileSync: e, readLatestDiagnosticStabilityBundleSync: t } = await loadStabilityBundleModule();
const n = o === "latest" ? t() : e(o);
if (n.status === "missing") throw new Error(`No stability bundles found in ${n.dir}`);
if (n.status === "failed") throw new Error(n.error instanceof Error ? n.error.message : String(n.error));
const s = r(n.bundle.snapshot, a);
await printGatewayResult(i.json, {
path: n.path,
mtimeMs: n.mtimeMs,
bundle: {
...n.bundle,
snapshot: s
}
}, (e) => {
const { bundle: t, path: r } = n;
const i = [
`pid=${t.process.pid}`,
...t.process.openclawVersion ? [`openclaw=${t.process.openclawVersion}`] : [],
...t.process.buildId ? [`build=${t.process.buildId}`] : [],
...t.process.commit ? [`commit=${t.process.commit}`] : [],
`node=${t.process.node}`,
`${t.process.platform}/${t.process.arch}`,
`uptime=${Math.round(t.process.uptimeMs / 1e3)}s`
].join(" ");
const a = [
colorize(e, theme.heading, "Stability bundle"),
`${colorize(e, theme.muted, "Path:")} ${r}`,
`${colorize(e, theme.muted, "Generated:")} ${t.generatedAt}`,
`${colorize(e, theme.muted, "Reason:")} ${t.reason}`,
`${colorize(e, theme.muted, "Process:")} ${i}`,
`${colorize(e, theme.muted, "Host:")} ${t.host.hostname}`
];
if (t.error) {
const n = [t.error.name ? `name=${t.error.name}` : "", t.error.code ? `code=${t.error.code}` : ""].filter(Boolean);
if (n.length > 0) a.push(`${colorize(e, theme.muted, "Error:")} ${n.join(" ")}`);
}
const o = t.evidence?.memoryPressure;
if (o) {
a.push(`${colorize(e, theme.muted, "Memory pressure:")} ${o.level}/${o.reason} rss=${formatStabilityBytes(o.memory.rssBytes)} heap=${formatStabilityBytes(o.memory.heapUsedBytes)} threshold=${formatStabilityBytes(o.thresholdBytes)}`);
if (o.heapStatistics) a.push(`${colorize(e, theme.muted, "V8 heap:")} used=${formatStabilityBytes(o.heapStatistics.usedHeapSizeBytes)} limit=${formatStabilityBytes(o.heapStatistics.heapSizeLimitBytes)} available=${formatStabilityBytes(o.heapStatistics.totalAvailableSizeBytes)}`);
if (o.activeResources) {
const t = Object.entries(o.activeResources.byType).map(([e, t]) => `${e}=${t}`).join(", ");
a.push(`${colorize(e, theme.muted, "Active resources:")} total=${o.activeResources.total}${t ? ` · ${t}` : ""}`);
}
if (o.topSessionFiles?.length) {
const t = o.topSessionFiles.slice(0, 5).map((e) => `${e.relativePath}=${formatStabilityBytes(e.sizeBytes)}`).join(", ");
a.push(`${colorize(e, theme.muted, "Largest session files:")} ${t}`);
}
}
a.push("", ...renderStabilitySummary(s, e));
return a;
});
return;
}
const s = await callGatewayReadOnlyCli("diagnostics.stability", resolveGatewayRpcOptionsWithLocalPort(i, t), {
limit: a.limit,
...a.type ? { type: a.type } : {},
...a.sinceSeq !== void 0 ? { sinceSeq: a.sinceSeq } : {}
});
await printGatewayResult(i.json, s, (e) => renderStabilitySummary(s, e));
}, "Gateway stability failed")));
t.command("diagnostics").description("Export local support diagnostics").command("export").description("Write a shareable, payload-free diagnostics .zip").option("--output <path>", "Output .zip path").option("--log-lines <count>", "Maximum sanitized log lines to include", "5000").option("--log-bytes <bytes>", "Maximum log bytes to inspect", "1000000").option("--url <url>", "Gateway WebSocket URL for health snapshot").option("--token <token>", "Gateway token for health snapshot").option("--password <password>", "Gateway password for health snapshot").option("--timeout <ms>", "Status/health snapshot timeout in ms", "3000").option("--no-stability-bundle", "Skip persisted stability bundle lookup").option("--json", "Output JSON", false).action(gatewayAction(async (e, t) => {
const n = resolveGatewayRpcOptions(e, t);
await writeSupportExportFromCli({
json: e.json,
output: e.output,
logLines: e.logLines,
logBytes: e.logBytes,
stabilityBundle: e.stabilityBundle === false ? false : "latest",
rpc: n
});
}, "Gateway diagnostics export failed"));
t.command("probe").description("Show gateway reachability, auth capability, and read-check summary (local + remote)").option("--url <url>", "Explicit Gateway WebSocket URL (still checks localhost)").option("--port <port>", "Local Gateway port").option("--ssh <target>", "SSH target for remote gateway tunnel (user@host or user@host:port)").option("--ssh-identity <path>", "SSH identity file path").option("--ssh-auto", "Try to derive an SSH target from Bonjour discovery", false).option("--token <token>", "Gateway token (applies to all checks)").option("--password <password>", "Gateway password (applies to all checks)").option("--timeout <ms>", "Overall check budget in ms", "3000").option("--json", "Output JSON", false).action(gatewayAction(async (e, t) => {
const n = resolveGatewayRpcOptions(e, t);
const { gatewayStatusCommand: r } = await import("./gateway-status-DOizSlRk.mjs");
await r({
...n,
port: e.port ?? inheritOptionFromParent(t, "port")
}, defaultRuntime);
}, void 0));
t.command("discover").description("Discover gateways via Bonjour (local + wide-area if configured)").option("--timeout <ms>", "Per-command timeout in ms", "2000").option("--json", "Output JSON", false).action(gatewayAction(async (e) => {
const [{ readSourceConfigBestEffort: t }, { discoverGatewayBeacons: n, resolveGatewayDiscoveryEndpoint: r }, { resolveWideAreaDiscoveryDomain: i }, { dedupeBeacons: a, renderBeaconLines: o }, { withProgress: s }] = await Promise.all([
import("./read-best-effort-config.runtime.js"),
import("./bonjour-discovery-j7O-RMdI.mjs"),
loadWideAreaDnsModule(),
import("./discover-DMhf3qKA.mjs"),
import("./progress-CNwY7Ykv.mjs")
]);
const c = i({ configDomain: (await t()).discovery?.wideArea?.domain });
const l = parseTimeoutMsWithFallback(e.timeout, 2e3, { invalidType: "error" });
const u = ["local.", ...c ? [c] : []];
const d = a(await s({
label: "Scanning for gateways…",
indeterminate: true,
enabled: e.json !== true,
delayMs: 0
}, async () => await n({
timeoutMs: l,
wideAreaDomain: c
}))).toSorted((e, t) => (e.displayName || e.instanceName).localeCompare(t.displayName || t.instanceName));
if (e.json) {
const e = d.map((e) => ({
...e,
wsUrl: r(e)?.wsUrl ?? null
}));
defaultRuntime.writeJson({
timeoutMs: l,
domains: u,
count: e.length,
beacons: e
});
return;
}
const f = isRich();
defaultRuntime.log(colorize(f, theme.heading, "Gateway Discovery"));
defaultRuntime.log(colorize(f, theme.muted, `Found ${d.length} gateway(s) · domains: ${u.join(", ")}`));
if (d.length === 0) return;
for (const e of d) for (const t of o(e, f)) defaultRuntime.log(t);
}, "gateway discover failed"));
}
//#endregion
export { registerGatewayCli };