Skip to content

Commit 85336be

Browse files
authored
fix(cli): honor automation gateway port options (#125474)
1 parent 02ec1b6 commit 85336be

13 files changed

Lines changed: 197 additions & 34 deletions

‎docs/cli/cron.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,11 @@ Run `openclaw automations --help` for the full command surface. See [Automations
1818
All automation mutations (`add`/`create`, `update`/`edit`, `remove`, `run`) require `operator.admin`. Command-payload runs execute directly in the Gateway process, not as an agent `tools.exec` tool call; `tools.exec.*` and exec approvals still govern model-visible exec tools.
1919
</Note>
2020

21+
Every automation subcommand accepts the shared Gateway connection options. Use
22+
`--port <port>` for a Gateway on a non-default local port, or `--url <url>` for
23+
an explicit WebSocket URL; do not combine them. Connection options such as
24+
`--port`, `--url`, and `--token` may appear before or after the subcommand.
25+
2126
## Create jobs quickly
2227

2328
`openclaw automations create` is an alias for `openclaw automations add`. For new jobs, put the schedule first and the prompt second:

‎src/cli/cron-cli.test.ts‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,30 @@ function buildProgram() {
157157
return program;
158158
}
159159

160+
const CRON_GATEWAY_COMMANDS = [
161+
{ name: "status", args: [] },
162+
{ name: "list", args: [] },
163+
{ name: "add", args: [] },
164+
{ name: "rm", args: ["job-1"] },
165+
{ name: "enable", args: ["job-1"] },
166+
{ name: "disable", args: ["job-1"] },
167+
{ name: "get", args: ["job-1"] },
168+
{ name: "show", args: ["job-1"] },
169+
{ name: "runs", args: ["--id", "job-1"] },
170+
{ name: "run", args: ["job-1"] },
171+
{ name: "scratch", args: ["job-1"] },
172+
{ name: "edit", args: ["job-1"] },
173+
] as const;
174+
175+
function findCronCommand(program: Command, name: string): Command {
176+
const cron = program.commands.find((command) => command.name() === "cron");
177+
const command = cron?.commands.find((candidate) => candidate.name() === name);
178+
if (!command) {
179+
throw new Error(`missing cron command: ${name}`);
180+
}
181+
return command;
182+
}
183+
160184
function createCronJob(id: string, name: string): CronJob {
161185
const now = Date.now();
162186
return {
@@ -338,6 +362,65 @@ async function runCronRunAndCaptureExit(params: {
338362
}
339363

340364
describe("cron cli", () => {
365+
it.each(CRON_GATEWAY_COMMANDS)(
366+
"inherits parent Gateway options for cron $name",
367+
async ({ name, args }) => {
368+
const program = buildProgram();
369+
const command = findCronCommand(program, name);
370+
command.action(() => {});
371+
372+
await program.parseAsync(
373+
["automations", "--port", "65267", "--token", "parent-token", name, ...args],
374+
{ from: "user" },
375+
);
376+
377+
expect(command.opts()).toMatchObject({ port: "65267", token: "parent-token" });
378+
},
379+
);
380+
381+
it.each(CRON_GATEWAY_COMMANDS)(
382+
"accepts leaf Gateway options for cron $name",
383+
async ({ name, args }) => {
384+
const program = buildProgram();
385+
const command = findCronCommand(program, name);
386+
command.action(() => {});
387+
388+
await program.parseAsync(
389+
["automations", name, ...args, "--port", "65268", "--token", "leaf-token"],
390+
{ from: "user" },
391+
);
392+
393+
expect(command.opts()).toMatchObject({
394+
port: "65268",
395+
token: "leaf-token",
396+
});
397+
},
398+
);
399+
400+
it("prefers explicit leaf Gateway options over cron parent options", async () => {
401+
const program = buildProgram();
402+
const command = findCronCommand(program, "add");
403+
command.action(() => {});
404+
405+
await program.parseAsync(
406+
[
407+
"cron",
408+
"--port",
409+
"65267",
410+
"--token",
411+
"parent-token",
412+
"add",
413+
"--port",
414+
"65268",
415+
"--token",
416+
"leaf-token",
417+
],
418+
{ from: "user" },
419+
);
420+
421+
expect(command.opts()).toMatchObject({ port: "65268", token: "leaf-token" });
422+
});
423+
341424
it("documents the gateway-host timezone default for cron --tz help", () => {
342425
const program = buildProgram();
343426
const cronCommand = program.commands.find((command) => command.name() === "cron");

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

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
import type { Command } from "commander";
33
import { formatDocsLink } from "../../../packages/terminal-core/src/links.js";
44
import { theme } from "../../../packages/terminal-core/src/theme.js";
5+
import { inheritOptionFromParent } from "../command-options.js";
6+
import { addGatewayClientOptions } from "../gateway-rpc.js";
57
import { setCommandJsonMode } from "../program/json-mode.js";
68
import { applyParentDefaultHelpAction } from "../program/parent-default-help.js";
79
import { isCronMachineOutput } from "./output-mode.js";
@@ -14,6 +16,25 @@ import { registerCronEditCommand } from "./register.cron-edit.js";
1416
import { registerCronScratchCommand } from "./register.cron-scratch.js";
1517
import { registerCronSimpleCommands } from "./register.cron-simple.js";
1618

19+
const CRON_GATEWAY_OPTION_NAMES = [
20+
"url",
21+
"port",
22+
"token",
23+
"password",
24+
"timeout",
25+
"expectFinal",
26+
] as const;
27+
28+
function inheritCronGatewayOptions(command: Command): void {
29+
for (const name of CRON_GATEWAY_OPTION_NAMES) {
30+
const inherited = inheritOptionFromParent(command, name);
31+
const source = command.parent?.getOptionValueSource(name);
32+
if (inherited !== undefined && source && source !== "default") {
33+
command.setOptionValueWithSource(name, inherited, source);
34+
}
35+
}
36+
}
37+
1738
export function registerCronCli(program: Command) {
1839
const cron = program
1940
.command("cron")
@@ -25,6 +46,9 @@ export function registerCronCli(program: Command) {
2546
`\n${theme.muted("Docs:")} ${formatDocsLink("/cli/cron", "docs.openclaw.ai/cli/cron")}\n${theme.muted("Upgrade tip:")} run \`openclaw doctor --fix\` to normalize legacy automation storage.\n`,
2647
);
2748

49+
addGatewayClientOptions(cron);
50+
cron.hook("preAction", (_parent, command) => inheritCronGatewayOptions(command));
51+
2852
registerCronStatusCommand(cron);
2953
registerCronListCommand(cron);
3054
registerCronAddCommand(cron);

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

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -156,13 +156,8 @@ function expectLocalGatewayCall(method: string, port: number, params?: unknown)
156156
if (params !== undefined) {
157157
expect(actualParams).toEqual(params);
158158
}
159-
const gatewayOpts = opts as
160-
| { config?: { gateway?: { port?: number } }; localPortOverride?: number }
161-
| undefined;
159+
const gatewayOpts = opts as { localPortOverride?: number } | undefined;
162160
expect(gatewayOpts?.localPortOverride).toBe(port);
163-
expect(gatewayOpts?.config).toEqual({
164-
gateway: { mode: "local", port },
165-
});
166161
}
167162

168163
describe("gateway register option collisions", () => {
@@ -225,7 +220,7 @@ describe("gateway register option collisions", () => {
225220
},
226221
},
227222
{
228-
name: "projects gateway call --port into local config",
223+
name: "projects gateway call --port into the local override",
229224
argv: ["gateway", "call", "health", "--port", "19084", "--json"],
230225
assert: () => {
231226
expectLocalGatewayCall("health", 19084, {});
@@ -293,7 +288,7 @@ describe("gateway register option collisions", () => {
293288
},
294289
},
295290
{
296-
name: "projects gateway health --port into local config",
291+
name: "projects gateway health --port into the local override",
297292
argv: ["gateway", "health", "--port", "19081", "--json"],
298293
assert: () => {
299294
expectLocalGatewayCall("health", 19081);
@@ -344,7 +339,7 @@ describe("gateway register option collisions", () => {
344339
expect(defaultRuntime.exit).toHaveBeenCalledWith(1);
345340
});
346341

347-
it("uses the effective local port config for gateway health auth diagnostics", async () => {
342+
it("uses the effective local port override for gateway health auth diagnostics", async () => {
348343
const authError = new Error("gateway auth required");
349344
callGatewayCli.mockRejectedValueOnce(authError);
350345
emitReachableGatewayAuthDiagnostic.mockResolvedValueOnce(true);
@@ -356,9 +351,7 @@ describe("gateway register option collisions", () => {
356351
expect(emitReachableGatewayAuthDiagnostic).toHaveBeenCalledTimes(1);
357352
expect(emitReachableGatewayAuthDiagnostic).toHaveBeenCalledWith({
358353
error: authError,
359-
config: {
360-
gateway: { mode: "local", port: 19081 },
361-
},
354+
config: {},
362355
runtime: defaultRuntime,
363356
timeoutMs: 10000,
364357
token: undefined,

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

Lines changed: 6 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -199,10 +199,10 @@ function resolveGatewayRpcOptions<T extends { token?: string; password?: string
199199
};
200200
}
201201

202-
async function resolveGatewayRpcOptionsWithLocalPort(
202+
function resolveGatewayRpcOptionsWithLocalPort(
203203
opts: GatewayRpcOpts & { port?: unknown },
204204
command?: Command,
205-
): Promise<GatewayRpcOpts> {
205+
): GatewayRpcOpts {
206206
const rpcOpts = resolveGatewayRpcOptions(opts, command);
207207
const port = parseGatewayPortOption(opts.port ?? inheritOptionFromParent(command, "port"));
208208
if (port === undefined) {
@@ -211,19 +211,9 @@ async function resolveGatewayRpcOptionsWithLocalPort(
211211
if (typeof opts.url === "string" && opts.url.trim()) {
212212
throw new Error("Use either --url or --port, not both.");
213213
}
214-
const { readBestEffortConfig } = await loadConfigModule();
215-
const config = await readBestEffortConfig();
216214
return {
217215
...rpcOpts,
218216
localPortOverride: port,
219-
config: {
220-
...config,
221-
gateway: {
222-
...config.gateway,
223-
mode: "local",
224-
port,
225-
},
226-
},
227217
};
228218
}
229219

@@ -587,7 +577,7 @@ export function registerGatewayCli(program: Command, deps: GatewayCliDependencie
587577
command.getOptionValueSource("timeout") === "default"
588578
? { ...opts, timeout: String(SETUP_INFERENCE_DETECT_RPC_TIMEOUT_MS) }
589579
: opts;
590-
const rpcOpts = await resolveGatewayRpcOptionsWithLocalPort(callOpts, command);
580+
const rpcOpts = resolveGatewayRpcOptionsWithLocalPort(callOpts, command);
591581
const params = parseGatewayCallParams(String(opts.params ?? "{}"));
592582
const result = await callGatewayReadOnlyCli(method, rpcOpts, params);
593583
if (rpcOpts.json) {
@@ -616,7 +606,7 @@ export function registerGatewayCli(program: Command, deps: GatewayCliDependencie
616606
.action(async (opts, command) => {
617607
await runGatewayCommand(
618608
async () => {
619-
const rpcOpts = await resolveGatewayRpcOptionsWithLocalPort(opts, command);
609+
const rpcOpts = resolveGatewayRpcOptionsWithLocalPort(opts, command);
620610
await runGatewaySuspend(
621611
{
622612
rpcOpts,
@@ -642,7 +632,7 @@ export function registerGatewayCli(program: Command, deps: GatewayCliDependencie
642632
.action(async (suspensionId, opts, command) => {
643633
await runGatewayCommand(
644634
async () => {
645-
const rpcOpts = await resolveGatewayRpcOptionsWithLocalPort(opts, command);
635+
const rpcOpts = resolveGatewayRpcOptionsWithLocalPort(opts, command);
646636
await runGatewayResume(
647637
{ rpcOpts, suspensionId: String(suspensionId), json: Boolean(rpcOpts.json) },
648638
{ callGateway: callGatewayReadOnlyCli, runtime: defaultRuntime },
@@ -700,7 +690,7 @@ export function registerGatewayCli(program: Command, deps: GatewayCliDependencie
700690
.action(async (opts, command) => {
701691
await runGatewayCommand(
702692
async () => {
703-
const rpcOpts = await resolveGatewayRpcOptionsWithLocalPort(opts, command);
693+
const rpcOpts = resolveGatewayRpcOptionsWithLocalPort(opts, command);
704694
let result: unknown;
705695
try {
706696
result = await callGatewayReadOnlyCli("health", rpcOpts);

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

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,19 @@ describe("addGatewayClientOptions", () => {
4141
});
4242
},
4343
);
44+
45+
it("registers and parses a local Gateway port", async () => {
46+
const program = new Command().exitOverride();
47+
const action = vi.fn((_opts: GatewayRpcOpts) => {});
48+
addGatewayClientOptions(program.command("gateway-command")).action(action);
49+
50+
await program.parseAsync(["gateway-command", "--port", "19083"], { from: "user" });
51+
52+
expect(action).toHaveBeenCalledWith(
53+
expect.objectContaining({ port: "19083" }),
54+
expect.anything(),
55+
);
56+
});
4457
});
4558

4659
describe("callGatewayFromCliRuntime", () => {
@@ -95,6 +108,25 @@ describe("callGatewayFromCliRuntime", () => {
95108
);
96109
});
97110

111+
it("projects --port to the canonical local Gateway override", async () => {
112+
await callGatewayFromCliRuntime("cron.status", { port: "19083" });
113+
114+
expect(callGatewayMock).toHaveBeenCalledWith(
115+
expect.objectContaining({ localPortOverride: 19_083 }),
116+
);
117+
});
118+
119+
it("rejects combining --url and --port before opening a Gateway connection", async () => {
120+
await expect(
121+
callGatewayFromCliRuntime("cron.status", {
122+
url: "ws://127.0.0.1:19083",
123+
port: "19083",
124+
}),
125+
).rejects.toThrow("Use either --url or --port, not both.");
126+
127+
expect(callGatewayMock).not.toHaveBeenCalled();
128+
});
129+
98130
it.each([
99131
{ name: "token", auth: { token: "test-gateway-token" } },
100132
{ name: "password", auth: { password: "test-gateway-password" } },

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

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
} from "../../packages/gateway-protocol/src/client-info.js";
66
import type { OpenClawConfig } from "../config/types.openclaw.js";
77
import { callGateway, isImplicitLocalGatewayTarget } from "../gateway/call.js";
8+
import { parseGatewayPortOption } from "./gateway-port-option.js";
89
import type { GatewayRpcOpts } from "./gateway-rpc.types.js";
910
import { parseTimeoutMsWithFallback } from "./parse-timeout.js";
1011
import { withProgress } from "./progress.js";
@@ -36,13 +37,21 @@ type GatewayCliTransportRpcOpts = Omit<GatewayRpcOpts, "timeout"> & {
3637

3738
const DEFAULT_GATEWAY_RPC_TIMEOUT_MS = 30_000;
3839

40+
function resolveLocalPortOverride(opts: GatewayCliTransportRpcOpts): number | undefined {
41+
const port = opts.localPortOverride ?? parseGatewayPortOption(opts.port);
42+
if (port !== undefined && typeof opts.url === "string" && opts.url.trim()) {
43+
throw new Error("Use either --url or --port, not both.");
44+
}
45+
return port;
46+
}
47+
3948
export async function isImplicitLocalGatewayTargetFromCliRuntime(
4049
opts: GatewayCliTransportRpcOpts,
4150
): Promise<boolean> {
4251
return await isImplicitLocalGatewayTarget({
4352
config: opts.config,
4453
url: opts.url,
45-
localPortOverride: opts.localPortOverride,
54+
localPortOverride: resolveLocalPortOverride(opts),
4655
});
4756
}
4857

@@ -52,6 +61,7 @@ export async function callGatewayFromCliRuntime(
5261
params?: unknown,
5362
extra?: CallGatewayFromCliRuntimeExtra,
5463
) {
64+
const localPortOverride = resolveLocalPortOverride(opts);
5565
// Progress is disabled for JSON output so stdout stays parseable.
5666
const showProgress = extra?.progress ?? opts.json !== true;
5767
const timeoutMs =
@@ -87,7 +97,7 @@ export async function callGatewayFromCliRuntime(
8797
sharedStateMode: extra?.sharedStateMode,
8898
signal: extra?.signal,
8999
timeoutMs,
90-
localPortOverride: opts.localPortOverride,
100+
localPortOverride,
91101
clientName: extra?.clientName ?? GATEWAY_CLIENT_NAMES.CLI,
92102
mode: extra?.mode ?? GATEWAY_CLIENT_MODES.CLI,
93103
}),

‎src/cli/gateway-rpc.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ async function loadGatewayRpcRuntime(): Promise<GatewayRpcRuntimeModule> {
2424
export function addGatewayClientOptions(cmd: Command, defaults?: { timeoutMs?: number }) {
2525
return cmd
2626
.option("--url <url>", "Gateway WebSocket URL (defaults to gateway.remote.url when configured)")
27+
.option("--port <port>", "Local Gateway port")
2728
.option("--token <token>", "Gateway token (if required)")
2829
.option("--password <password>", "Gateway password (if required)")
2930
.option("--timeout <ms>", "Timeout in ms", String(defaults?.timeoutMs ?? 30_000))

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
/** Common gateway RPC flags accepted by direct gateway command helpers. */
33
export type GatewayRpcOpts = {
44
url?: string;
5+
port?: string;
56
token?: string;
67
password?: string;
78
timeout?: string;

0 commit comments

Comments
 (0)