Skip to content

Commit 15ca695

Browse files
committed
perf(cli): route gateway health JSON before Commander
1 parent a119037 commit 15ca695

7 files changed

Lines changed: 364 additions & 1 deletion

File tree

‎src/cli/command-catalog.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ type CliNetworkProxyPolicyResolver =
1818
type CliRoutedCommandId =
1919
| "health"
2020
| "status"
21+
| "gateway-health"
2122
| "gateway-status"
2223
| "sessions"
2324
| "agents-list"
@@ -196,7 +197,12 @@ export const cliCommandCatalog: readonly CliCommandCatalogEntry[] = [
196197
{ commandPath: ["gateway", "diagnostics"], exact: true, policy: { networkProxy: "bypass" } },
197198
{ commandPath: ["gateway", "discover"], exact: true, policy: { networkProxy: "bypass" } },
198199
{ commandPath: ["gateway", "export"], exact: true, policy: { networkProxy: "bypass" } },
199-
{ commandPath: ["gateway", "health"], exact: true, policy: { networkProxy: "bypass" } },
200+
{
201+
commandPath: ["gateway", "health"],
202+
exact: true,
203+
policy: { networkProxy: "bypass" },
204+
route: { id: "gateway-health" },
205+
},
200206
{ commandPath: ["gateway", "install"], exact: true, policy: { networkProxy: "bypass" } },
201207
{ commandPath: ["gateway", "probe"], exact: true, policy: { networkProxy: "bypass" } },
202208
{ commandPath: ["gateway", "restart"], exact: true, policy: { networkProxy: "bypass" } },
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
// Gateway health route tests cover the machine-readable fast path and its error contract.
2+
import { describe, expect, it, vi } from "vitest";
3+
import { runGatewayHealthJsonRoute } from "./health-route.js";
4+
5+
function createRuntime() {
6+
return {
7+
writeJson: vi.fn(),
8+
exit: vi.fn(),
9+
};
10+
}
11+
12+
describe("runGatewayHealthJsonRoute", () => {
13+
it("writes successful JSON without loading error-only dependencies", async () => {
14+
const runtime = createRuntime();
15+
const callGateway = vi.fn(async () => ({ ok: true, durationMs: 6 }));
16+
const readBestEffortConfig = vi.fn(async () => ({}));
17+
const emitReachableGatewayAuthDiagnostic = vi.fn(async () => false);
18+
const formatGatewayClientRequestErrorJson = vi.fn();
19+
const formatGatewayTransportErrorJson = vi.fn();
20+
21+
await runGatewayHealthJsonRoute(
22+
{
23+
rpc: { json: true, timeout: "10000" },
24+
},
25+
runtime as never,
26+
{
27+
callGateway,
28+
readBestEffortConfig,
29+
emitReachableGatewayAuthDiagnostic: emitReachableGatewayAuthDiagnostic as never,
30+
formatGatewayClientRequestErrorJson: formatGatewayClientRequestErrorJson as never,
31+
formatGatewayTransportErrorJson: formatGatewayTransportErrorJson as never,
32+
},
33+
);
34+
35+
expect(callGateway).toHaveBeenCalledWith("health", { json: true, timeout: "10000" });
36+
expect(runtime.writeJson).toHaveBeenCalledWith({ ok: true, durationMs: 6 });
37+
expect(readBestEffortConfig).not.toHaveBeenCalled();
38+
expect(emitReachableGatewayAuthDiagnostic).not.toHaveBeenCalled();
39+
expect(formatGatewayClientRequestErrorJson).not.toHaveBeenCalled();
40+
expect(formatGatewayTransportErrorJson).not.toHaveBeenCalled();
41+
});
42+
43+
it("projects a local port into the routed config", async () => {
44+
const runtime = createRuntime();
45+
const callGateway = vi.fn(async () => ({ ok: true }));
46+
const readBestEffortConfig = vi.fn(async () => ({
47+
gateway: { auth: { mode: "token" as const } },
48+
}));
49+
50+
await runGatewayHealthJsonRoute(
51+
{
52+
rpc: { json: true, timeout: "10000" },
53+
localPortOverride: 19083,
54+
},
55+
runtime as never,
56+
{ callGateway, readBestEffortConfig },
57+
);
58+
59+
expect(callGateway).toHaveBeenCalledWith(
60+
"health",
61+
expect.objectContaining({
62+
localPortOverride: 19083,
63+
config: {
64+
gateway: { auth: { mode: "token" }, mode: "local", port: 19083 },
65+
},
66+
}),
67+
);
68+
});
69+
70+
it("preserves structured transport errors", async () => {
71+
const runtime = createRuntime();
72+
const error = new Error("gateway unavailable");
73+
const callGateway = vi.fn(async () => {
74+
throw error;
75+
});
76+
const payload = { ok: false, error: { type: "gateway_transport_error" } };
77+
78+
await runGatewayHealthJsonRoute({ rpc: { json: true, timeout: "10000" } }, runtime as never, {
79+
callGateway,
80+
readBestEffortConfig: async () => ({}),
81+
emitReachableGatewayAuthDiagnostic: vi.fn(async () => false) as never,
82+
formatGatewayClientRequestErrorJson: vi.fn(() => null) as never,
83+
formatGatewayTransportErrorJson: vi.fn(() => payload) as never,
84+
});
85+
86+
expect(runtime.writeJson).toHaveBeenCalledWith(payload);
87+
expect(runtime.exit).toHaveBeenCalledWith(1);
88+
});
89+
});
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
// Route-first machine-readable Gateway health command.
2+
import type { OpenClawConfig } from "../../config/types.openclaw.js";
3+
import type { RuntimeEnv } from "../../runtime.js";
4+
import type { GatewayRpcOpts } from "./call.js";
5+
6+
export type GatewayHealthJsonRouteArgs = {
7+
rpc: GatewayRpcOpts;
8+
localPortOverride?: number;
9+
};
10+
11+
type GatewayHealthRouteDependencies = {
12+
callGateway?: typeof import("./call.js").callGatewayCli;
13+
readBestEffortConfig?: () => Promise<OpenClawConfig>;
14+
emitReachableGatewayAuthDiagnostic?: typeof import("../../commands/health.js").emitReachableGatewayAuthDiagnostic;
15+
formatGatewayClientRequestErrorJson?: typeof import("../../gateway/call.js").formatGatewayClientRequestErrorJson;
16+
formatGatewayTransportErrorJson?: typeof import("../../gateway/call.js").formatGatewayTransportErrorJson;
17+
};
18+
19+
async function resolveRouteRpcOptions(
20+
args: GatewayHealthJsonRouteArgs,
21+
deps: GatewayHealthRouteDependencies,
22+
): Promise<GatewayRpcOpts> {
23+
if (args.localPortOverride === undefined) {
24+
return args.rpc;
25+
}
26+
const readBestEffortConfig =
27+
deps.readBestEffortConfig ??
28+
(await import("../../config/read-best-effort-config.runtime.js")).readBestEffortConfig;
29+
const config = await readBestEffortConfig();
30+
return {
31+
...args.rpc,
32+
localPortOverride: args.localPortOverride,
33+
config: {
34+
...config,
35+
gateway: {
36+
...config.gateway,
37+
mode: "local",
38+
port: args.localPortOverride,
39+
},
40+
},
41+
};
42+
}
43+
44+
/** Run the successful JSON path without loading text presentation modules. */
45+
export async function runGatewayHealthJsonRoute(
46+
args: GatewayHealthJsonRouteArgs,
47+
runtime: RuntimeEnv,
48+
deps: GatewayHealthRouteDependencies = {},
49+
): Promise<void> {
50+
const rpc = await resolveRouteRpcOptions(args, deps);
51+
try {
52+
const callGateway = deps.callGateway ?? (await import("./call.js")).callGatewayCli;
53+
runtime.writeJson(await callGateway("health", rpc));
54+
} catch (error) {
55+
const [healthModule, configModule, callModule] = await Promise.all([
56+
deps.emitReachableGatewayAuthDiagnostic ? undefined : import("../../commands/health.js"),
57+
deps.readBestEffortConfig
58+
? undefined
59+
: import("../../config/read-best-effort-config.runtime.js"),
60+
deps.formatGatewayClientRequestErrorJson && deps.formatGatewayTransportErrorJson
61+
? undefined
62+
: import("../../gateway/call.js"),
63+
]);
64+
const emitReachableGatewayAuthDiagnostic =
65+
deps.emitReachableGatewayAuthDiagnostic ?? healthModule?.emitReachableGatewayAuthDiagnostic;
66+
const readBestEffortConfig = deps.readBestEffortConfig ?? configModule?.readBestEffortConfig;
67+
if (!emitReachableGatewayAuthDiagnostic || !readBestEffortConfig) {
68+
throw error;
69+
}
70+
const handled = await emitReachableGatewayAuthDiagnostic({
71+
error,
72+
config: rpc.config ?? (await readBestEffortConfig()),
73+
runtime,
74+
timeoutMs: Number(rpc.timeout ?? "10000"),
75+
token: rpc.token,
76+
password: rpc.password,
77+
localPortOverride: rpc.localPortOverride,
78+
json: true,
79+
});
80+
if (handled) {
81+
return;
82+
}
83+
const formatGatewayClientRequestErrorJson =
84+
deps.formatGatewayClientRequestErrorJson ?? callModule?.formatGatewayClientRequestErrorJson;
85+
const formatGatewayTransportErrorJson =
86+
deps.formatGatewayTransportErrorJson ?? callModule?.formatGatewayTransportErrorJson;
87+
const payload =
88+
formatGatewayClientRequestErrorJson?.(error) ?? formatGatewayTransportErrorJson?.(error);
89+
if (payload) {
90+
runtime.writeJson(payload);
91+
runtime.exit(1);
92+
return;
93+
}
94+
throw error;
95+
}
96+
}

‎src/cli/program/route-args.test.ts‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
parseChannelsStatusRouteArgs,
77
parseConfigGetRouteArgs,
88
parseConfigUnsetRouteArgs,
9+
parseGatewayHealthRouteArgs,
910
parseGatewayStatusRouteArgs,
1011
parseHealthRouteArgs,
1112
parseModelsListRouteArgs,
@@ -222,6 +223,83 @@ describe("route-args", () => {
222223
).toBeNull();
223224
});
224225

226+
it("parses JSON gateway health route args and defers unsupported shapes", () => {
227+
expect(
228+
parseGatewayHealthRouteArgs([
229+
"node",
230+
"openclaw",
231+
"gateway",
232+
"health",
233+
"--url",
234+
"ws://127.0.0.1:18789",
235+
"--token",
236+
"abc",
237+
"--password",
238+
"def",
239+
"--timeout",
240+
"5000",
241+
"--expect-final",
242+
"--json",
243+
]),
244+
).toEqual({
245+
rpc: {
246+
url: "ws://127.0.0.1:18789",
247+
token: "abc",
248+
password: "def",
249+
timeout: "5000",
250+
expectFinal: true,
251+
json: true,
252+
},
253+
localPortOverride: undefined,
254+
});
255+
expect(
256+
parseGatewayHealthRouteArgs([
257+
"node",
258+
"openclaw",
259+
"gateway",
260+
"--port",
261+
"19083",
262+
"health",
263+
"--json",
264+
]),
265+
).toEqual({
266+
rpc: {
267+
url: undefined,
268+
token: undefined,
269+
password: undefined,
270+
timeout: "10000",
271+
expectFinal: false,
272+
json: true,
273+
},
274+
localPortOverride: 19083,
275+
});
276+
expect(parseGatewayHealthRouteArgs(["node", "openclaw", "gateway", "health"])).toBeNull();
277+
expect(
278+
parseGatewayHealthRouteArgs([
279+
"node",
280+
"openclaw",
281+
"gateway",
282+
"health",
283+
"--url",
284+
"ws://127.0.0.1:18789",
285+
"--port",
286+
"19083",
287+
"--json",
288+
]),
289+
).toBeNull();
290+
expect(
291+
parseGatewayHealthRouteArgs([
292+
"node",
293+
"openclaw",
294+
"gateway",
295+
"health",
296+
"--timeout",
297+
"5s",
298+
"--json",
299+
]),
300+
).toBeNull();
301+
});
302+
225303
it("parses sessions and agents list route args", () => {
226304
expect(
227305
parseSessionsRouteArgs([

‎src/cli/program/route-args.ts‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
getVerboseFlag,
88
hasFlag,
99
} from "../argv.js";
10+
import { parseGatewayPortOption } from "../gateway-port-option.js";
1011
import { parseStrictPositiveIntOrUndefined } from "./helpers.js";
1112

1213
type OptionalFlagParse = {
@@ -178,6 +179,60 @@ export function parseGatewayStatusRouteArgs(argv: string[]) {
178179
};
179180
}
180181

182+
/** Parse machine-readable `openclaw gateway health` calls for route-first execution. */
183+
export function parseGatewayHealthRouteArgs(argv: string[]) {
184+
if (!hasFlag(argv, "--json")) {
185+
return null;
186+
}
187+
const positionals = getRoutedCommandPositionals(argv, {
188+
commandPath: ["gateway", "health"],
189+
booleanFlags: ["--expect-final", "--json"],
190+
valueFlags: ["--url", "--token", "--password", "--timeout", "--port"],
191+
});
192+
if (!positionals || positionals.length !== 0) {
193+
return null;
194+
}
195+
const url = parseOptionalFlagValue(argv, "--url");
196+
const token = parseOptionalFlagValue(argv, "--token");
197+
const password = parseOptionalFlagValue(argv, "--password");
198+
const timeout = parseOptionalFlagValue(argv, "--timeout");
199+
const port = parseOptionalFlagValue(argv, "--port");
200+
if (!url.ok || !token.ok || !password.ok || !timeout.ok || !port.ok) {
201+
return null;
202+
}
203+
if (
204+
timeout.value !== undefined &&
205+
parseStrictPositiveIntOrUndefined(timeout.value) === undefined
206+
) {
207+
return null;
208+
}
209+
let localPortOverride: number | undefined;
210+
if (port.value !== undefined) {
211+
try {
212+
localPortOverride = parseGatewayPortOption(port.value);
213+
} catch {
214+
return null;
215+
}
216+
if (localPortOverride === undefined) {
217+
return null;
218+
}
219+
}
220+
if (url.value && localPortOverride !== undefined) {
221+
return null;
222+
}
223+
return {
224+
rpc: {
225+
url: url.value,
226+
token: token.value,
227+
password: password.value,
228+
timeout: timeout.value ?? "10000",
229+
expectFinal: hasFlag(argv, "--expect-final"),
230+
json: true as const,
231+
},
232+
localPortOverride,
233+
};
234+
}
235+
181236
/** Parse `openclaw sessions` filters for JSON/list route execution. */
182237
export function parseSessionsRouteArgs(argv: string[]) {
183238
const positionals = getRoutedCommandPositionals(argv, {

‎src/cli/program/routed-command-definitions.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
parseChannelsStatusRouteArgs,
88
parseConfigGetRouteArgs,
99
parseConfigUnsetRouteArgs,
10+
parseGatewayHealthRouteArgs,
1011
parseGatewayStatusRouteArgs,
1112
parseHealthRouteArgs,
1213
parseModelsListRouteArgs,
@@ -115,6 +116,13 @@ export const routedCommandDefinitions = {
115116
await runDaemonStatus(args);
116117
},
117118
}),
119+
"gateway-health": defineRoutedCommand({
120+
parseArgs: parseGatewayHealthRouteArgs,
121+
runParsedArgs: async (args) => {
122+
const { runGatewayHealthJsonRoute } = await import("../gateway-cli/health-route.js");
123+
await runGatewayHealthJsonRoute(args, defaultRuntime);
124+
},
125+
}),
118126
sessions: defineRoutedCommand({
119127
parseArgs: parseSessionsRouteArgs,
120128
runParsedArgs: async (args) => {

0 commit comments

Comments
 (0)