Skip to content

Commit a0e337b

Browse files
committed
refactor(cli): unify gateway RPC transport
1 parent 3f9b242 commit a0e337b

23 files changed

Lines changed: 229 additions & 352 deletions

‎src/cli/devices-cli.runtime.ts‎

Lines changed: 7 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,14 @@ import {
55
normalizeStringifiedOptionalString,
66
} from "@openclaw/normalization-core/string-coerce";
77
import { uniqueStrings } from "@openclaw/normalization-core/string-normalization";
8-
import {
9-
GATEWAY_CLIENT_MODES,
10-
GATEWAY_CLIENT_NAMES,
11-
} from "../../packages/gateway-protocol/src/client-info.js";
128
import {
139
readConnectPairingRequiredMessage,
1410
type ConnectPairingRequiredDetails,
1511
} from "../../packages/gateway-protocol/src/connect-error-details.js";
1612
import { sanitizeForLog } from "../../packages/terminal-core/src/ansi.js";
1713
import { getTerminalTableWidth, renderTable } from "../../packages/terminal-core/src/table.js";
1814
import { theme } from "../../packages/terminal-core/src/theme.js";
19-
import {
20-
buildGatewayConnectionDetails,
21-
callGateway,
22-
formatGatewayTransportErrorJson,
23-
} from "../gateway/call.js";
15+
import { buildGatewayConnectionDetails, formatGatewayTransportErrorJson } from "../gateway/call.js";
2416
import {
2517
ADMIN_SCOPE,
2618
PAIRING_SCOPE,
@@ -46,8 +38,7 @@ import {
4638
import { parseNodeList } from "../shared/node-list-parse.js";
4739
import type { NodeListNode } from "../shared/node-list-types.js";
4840
import { formatCliCommand } from "./command-format.js";
49-
import { parseTimeoutMsWithFallback } from "./parse-timeout.js";
50-
import { withProgress } from "./progress.js";
41+
import { callGatewayFromCliWithTransport } from "./gateway-rpc.js";
5142
import { quoteCliArg } from "./quote-cli-arg.js";
5243

5344
type DevicesRpcOpts = {
@@ -137,25 +128,11 @@ const callGatewayCli = async (
137128
params?: unknown,
138129
callOpts?: { scopes?: OperatorScope[] },
139130
) =>
140-
withProgress(
141-
{
142-
label: `Devices ${method}`,
143-
indeterminate: true,
144-
enabled: opts.json !== true,
145-
},
146-
async () =>
147-
await callGateway({
148-
url: opts.url,
149-
token: opts.token,
150-
password: opts.password,
151-
method,
152-
params,
153-
timeoutMs: parseTimeoutMsWithFallback(opts.timeout, DEFAULT_DEVICES_TIMEOUT_MS),
154-
clientName: GATEWAY_CLIENT_NAMES.CLI,
155-
mode: GATEWAY_CLIENT_MODES.CLI,
156-
scopes: callOpts?.scopes,
157-
}),
158-
);
131+
callGatewayFromCliWithTransport(method, opts, params, {
132+
label: `Devices ${method}`,
133+
defaultTimeoutMs: DEFAULT_DEVICES_TIMEOUT_MS,
134+
scopes: callOpts?.scopes,
135+
});
159136

160137
function isPendingNodeApprovalState(
161138
state: unknown,

‎src/cli/gateway-cli/call.ts‎

Lines changed: 0 additions & 52 deletions
This file was deleted.

‎src/cli/gateway-cli/health-route.test.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,12 @@ describe("runGatewayHealthJsonRoute", () => {
3737
},
3838
);
3939

40-
expect(callGateway).toHaveBeenCalledWith("health", { json: true, timeout: "10000" });
40+
expect(callGateway).toHaveBeenCalledWith(
41+
"health",
42+
{ json: true, timeout: "10000" },
43+
undefined,
44+
{ defaultTimeoutMs: 10_000 },
45+
);
4146
expect(runtime.writeJson).toHaveBeenCalledWith({ ok: true, durationMs: 6 }, 2);
4247
expect(readBestEffortConfig).not.toHaveBeenCalled();
4348
expect(emitReachableGatewayAuthDiagnostic).not.toHaveBeenCalled();
@@ -70,6 +75,8 @@ describe("runGatewayHealthJsonRoute", () => {
7075
gateway: { auth: { mode: "token" }, mode: "local", port: 19083 },
7176
},
7277
}),
78+
undefined,
79+
{ defaultTimeoutMs: 10_000 },
7380
);
7481
});
7582

‎src/cli/gateway-cli/health-route.ts‎

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,18 @@
11
// Route-first machine-readable Gateway health command.
22
import type { OpenClawConfig } from "../../config/types.openclaw.js";
33
import { type RuntimeEnv, writeRuntimeJson } from "../../runtime.js";
4-
import type { GatewayRpcOpts } from "./call.js";
4+
5+
type GatewayHealthRpcOpts = Parameters<
6+
typeof import("../gateway-rpc.js").callGatewayFromCliWithTransport
7+
>[1];
58

69
type GatewayHealthJsonRouteArgs = {
7-
rpc: GatewayRpcOpts;
10+
rpc: GatewayHealthRpcOpts;
811
localPortOverride?: number;
912
};
1013

1114
type GatewayHealthRouteDependencies = {
12-
callGateway?: typeof import("./call.js").callGatewayCli;
15+
callGateway?: typeof import("../gateway-rpc.js").callGatewayFromCliWithTransport;
1316
readBestEffortConfig?: () => Promise<OpenClawConfig>;
1417
emitReachableGatewayAuthDiagnostic?: typeof import("../../commands/health.js").emitReachableGatewayAuthDiagnostic;
1518
formatGatewayAuthErrorJson?: typeof import("../../gateway/call.js").formatGatewayAuthErrorJson;
@@ -20,7 +23,7 @@ type GatewayHealthRouteDependencies = {
2023
async function resolveRouteRpcOptions(
2124
args: GatewayHealthJsonRouteArgs,
2225
deps: GatewayHealthRouteDependencies,
23-
): Promise<GatewayRpcOpts> {
26+
): Promise<GatewayHealthRpcOpts> {
2427
if (args.localPortOverride === undefined) {
2528
return args.rpc;
2629
}
@@ -48,11 +51,15 @@ export async function runGatewayHealthJsonRoute(
4851
runtime: RuntimeEnv,
4952
deps: GatewayHealthRouteDependencies = {},
5053
): Promise<void> {
51-
let rpc: GatewayRpcOpts | undefined;
54+
let rpc: GatewayHealthRpcOpts | undefined;
5255
try {
5356
rpc = await resolveRouteRpcOptions(args, deps);
54-
const callGateway = deps.callGateway ?? (await import("./call.js")).callGatewayCli;
55-
writeRuntimeJson(runtime, await callGateway("health", rpc));
57+
const callGateway =
58+
deps.callGateway ?? (await import("../gateway-rpc.js")).callGatewayFromCliWithTransport;
59+
writeRuntimeJson(
60+
runtime,
61+
await callGateway("health", rpc, undefined, { defaultTimeoutMs: 10_000 }),
62+
);
5663
} catch (error) {
5764
if (!rpc) {
5865
runtime.error(String(error));

‎src/cli/gateway-cli/register.option-collisions.test.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,9 @@ vi.mock("../../commands/gateway-status.js", () => ({
4646
mocks.gatewayStatusCommand(opts, runtime),
4747
}));
4848

49-
vi.mock("./call.js", () => ({
50-
callGatewayCli: (method: string, opts: unknown, params?: unknown) =>
49+
vi.mock("../gateway-rpc.js", async () => ({
50+
...(await vi.importActual<typeof import("../gateway-rpc.js")>("../gateway-rpc.js")),
51+
callGatewayFromCliWithTransport: (method: string, opts: unknown, params?: unknown) =>
5152
mocks.callGatewayCli(method, opts, params),
5253
}));
5354

‎src/cli/gateway-cli/register.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,15 +21,17 @@ import { sleep } from "../../utils/sleep.js";
2121
import { inheritOptionFromParent } from "../command-options.js";
2222
import { addGatewayServiceCommands } from "../daemon-cli/register-service-commands.js";
2323
import { parseGatewayPortOption } from "../gateway-port-option.js";
24+
import { callGatewayFromCliWithTransport } from "../gateway-rpc.js";
2425
import { formatHelpExamples } from "../help-format.js";
2526
import { parseTimeoutMsWithFallback } from "../parse-timeout.js";
2627
import { setCommandJsonMode } from "../program/json-mode.js";
27-
import type { GatewayRpcOpts } from "./call.js";
2828
import type { GatewayDiscoverOpts } from "./discover.js";
2929
import { isGatewayMachineOutput } from "./output-mode.js";
3030
import { addGatewayRestartHandoffCommands } from "./register-restart-handoff.js";
3131
import { addGatewayRunCommand } from "./run-command.js";
3232

33+
type GatewayRpcOpts = Parameters<typeof callGatewayFromCliWithTransport>[1];
34+
3335
const configModuleLoader = createLazyImportLoader(
3436
() => import("../../config/read-best-effort-config.runtime.js"),
3537
);
@@ -120,8 +122,9 @@ function gatewayCallOpts(cmd: Command, defaultTimeoutMs = DEFAULT_GATEWAY_RPC_TI
120122
}
121123

122124
async function callGatewayCli(method: string, opts: GatewayRpcOpts, params?: unknown) {
123-
const mod = await import("./call.js");
124-
return mod.callGatewayCli(method, opts, params);
125+
return await callGatewayFromCliWithTransport(method, opts, params, {
126+
defaultTimeoutMs: DEFAULT_GATEWAY_RPC_TIMEOUT_MS,
127+
});
125128
}
126129

127130
function parseGatewayCallParams(value = "{}"): unknown {

‎src/cli/gateway-rpc.runtime.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,42 @@ describe("callGatewayFromCliRuntime", () => {
5656
);
5757
});
5858

59+
it("accepts a caller-specific default timeout", async () => {
60+
await callGatewayFromCliRuntime("health", {}, undefined, { defaultTimeoutMs: 10_000 });
61+
62+
expect(callGatewayMock).toHaveBeenCalledWith(
63+
expect.objectContaining({ method: "health", timeoutMs: 10_000 }),
64+
);
65+
});
66+
67+
it("forwards specialized connection and authorization context", async () => {
68+
const config = { gateway: { mode: "local" as const } };
69+
await callGatewayFromCliRuntime(
70+
"node.list",
71+
{ config, localPortOverride: 19_083 },
72+
{},
73+
{
74+
timeoutMs: null,
75+
scopes: ["operator.read", "operator.pairing"],
76+
useStoredDeviceAuth: true,
77+
requiredStoredDeviceAuthScopes: ["operator.read", "operator.pairing"],
78+
requireLocalBackendSharedAuth: true,
79+
},
80+
);
81+
82+
expect(callGatewayMock).toHaveBeenCalledWith(
83+
expect.objectContaining({
84+
config,
85+
localPortOverride: 19_083,
86+
timeoutMs: null,
87+
scopes: ["operator.read", "operator.pairing"],
88+
useStoredDeviceAuth: true,
89+
requiredStoredDeviceAuthScopes: ["operator.read", "operator.pairing"],
90+
requireLocalBackendSharedAuth: true,
91+
}),
92+
);
93+
});
94+
5995
it.each([
6096
{ name: "token", auth: { token: "test-gateway-token" } },
6197
{ name: "password", auth: { password: "test-gateway-password" } },

‎src/cli/gateway-rpc.runtime.ts‎

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {
33
GATEWAY_CLIENT_MODES,
44
GATEWAY_CLIENT_NAMES,
55
} from "../../packages/gateway-protocol/src/client-info.js";
6+
import type { OpenClawConfig } from "../config/types.openclaw.js";
67
import { callGateway } from "../gateway/call.js";
78
import type { GatewayRpcOpts } from "./gateway-rpc.types.js";
89
import { parseTimeoutMsWithFallback } from "./parse-timeout.js";
@@ -16,29 +17,51 @@ type CallGatewayFromCliRuntimeExtra = {
1617
expectFinal?: boolean;
1718
progress?: boolean;
1819
scopes?: Parameters<typeof callGateway>[0]["scopes"];
20+
defaultTimeoutMs?: number;
21+
timeoutMs?: number | null;
22+
label?: string;
23+
useStoredDeviceAuth?: boolean;
24+
requiredStoredDeviceAuthScopes?: Parameters<
25+
typeof callGateway
26+
>[0]["requiredStoredDeviceAuthScopes"];
27+
requireLocalBackendSharedAuth?: boolean;
28+
};
29+
30+
type GatewayCliTransportRpcOpts = Omit<GatewayRpcOpts, "timeout"> & {
31+
config?: OpenClawConfig;
32+
timeout?: string | null;
33+
localPortOverride?: number;
1934
};
2035

2136
const DEFAULT_GATEWAY_RPC_TIMEOUT_MS = 30_000;
2237

2338
export async function callGatewayFromCliRuntime(
2439
method: string,
25-
opts: GatewayRpcOpts,
40+
opts: GatewayCliTransportRpcOpts,
2641
params?: unknown,
2742
extra?: CallGatewayFromCliRuntimeExtra,
2843
) {
2944
// Progress is disabled for JSON output so stdout stays parseable.
3045
const showProgress = extra?.progress ?? opts.json !== true;
31-
const timeoutMs = parseTimeoutMsWithFallback(opts.timeout, DEFAULT_GATEWAY_RPC_TIMEOUT_MS, {
32-
invalidType: "error",
33-
});
46+
const timeoutMs =
47+
extra?.timeoutMs !== undefined
48+
? extra.timeoutMs
49+
: opts.timeout === null
50+
? null
51+
: parseTimeoutMsWithFallback(
52+
opts.timeout,
53+
extra?.defaultTimeoutMs ?? DEFAULT_GATEWAY_RPC_TIMEOUT_MS,
54+
{ invalidType: "error" },
55+
);
3456
return await withProgress(
3557
{
36-
label: `Gateway ${method}`,
58+
label: extra?.label ?? `Gateway ${method}`,
3759
indeterminate: true,
3860
enabled: showProgress,
3961
},
4062
async () =>
4163
await callGateway({
64+
config: opts.config,
4265
url: opts.url,
4366
token: opts.token,
4467
password: opts.password,
@@ -47,8 +70,12 @@ export async function callGatewayFromCliRuntime(
4770
deviceIdentity: extra?.deviceIdentity,
4871
expectFinal: extra?.expectFinal ?? Boolean(opts.expectFinal),
4972
scopes: extra?.scopes,
73+
useStoredDeviceAuth: extra?.useStoredDeviceAuth,
74+
requiredStoredDeviceAuthScopes: extra?.requiredStoredDeviceAuthScopes,
75+
requireLocalBackendSharedAuth: extra?.requireLocalBackendSharedAuth,
5076
signal: extra?.signal,
5177
timeoutMs,
78+
localPortOverride: opts.localPortOverride,
5279
clientName: extra?.clientName ?? GATEWAY_CLIENT_NAMES.CLI,
5380
mode: extra?.mode ?? GATEWAY_CLIENT_MODES.CLI,
5481
}),

‎src/cli/gateway-rpc.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,16 @@ export async function callGatewayFromCli(
4343
progress?: boolean;
4444
scopes?: OperatorScope[];
4545
},
46+
) {
47+
return await callGatewayFromCliWithTransport(method, opts, params, extra);
48+
}
49+
50+
/** Internal CLI facade for callers that need transport or auth policy overrides. */
51+
export async function callGatewayFromCliWithTransport(
52+
method: string,
53+
opts: Parameters<GatewayRpcRuntimeModule["callGatewayFromCliRuntime"]>[1],
54+
params?: unknown,
55+
extra?: Parameters<GatewayRpcRuntimeModule["callGatewayFromCliRuntime"]>[3],
4656
) {
4757
const runtime = await loadGatewayRpcRuntime();
4858
return await runtime.callGatewayFromCliRuntime(method, opts, params, extra);

‎src/cli/help-cold-imports.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,10 @@ vi.mock("./gateway-cli/run.js", () => {
2020
};
2121
});
2222

23-
vi.mock("./gateway-cli/call.js", () => {
23+
vi.mock("./gateway-rpc.runtime.js", () => {
2424
loaded.mark("gateway-call-runtime");
2525
return {
26-
callGatewayCli: vi.fn(async () => ({})),
26+
callGatewayFromCliRuntime: vi.fn(async () => ({})),
2727
};
2828
});
2929

0 commit comments

Comments
 (0)