Skip to content

Commit b5864ba

Browse files
authored
fix(skills): fail closed for unavailable remote Gateway (#117567)
* fix(cli): respect explicit Gateway ownership * fix(gateway): fence offline CLI fallbacks * fix(gateway): restrict local recovery closes * fix(cli): preserve offline Gateway ownership and log recovery
1 parent b57a40b commit b5864ba

13 files changed

Lines changed: 1214 additions & 145 deletions

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2414,7 +2414,7 @@ src/cli/gateway-cli/qa-parent-watchdog.ts 3
24142414
src/cli/gateway-cli/register.ts 4
24152415
src/cli/gateway-cli/run.ts 12
24162416
src/cli/gateway-cli/suspend-cli.ts 2
2417-
src/cli/hooks-cli.ts 3
2417+
src/cli/hooks-cli.ts 2
24182418
src/cli/logs-cli.ts 1
24192419
src/cli/mcp-cli.ts 1
24202420
src/cli/models-cli.ts 19

‎docs/cli/hooks.md‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,13 @@ Bare `openclaw hooks` and `openclaw hooks --json` use the same list operation as
2323
`openclaw hooks list`. The command discovers hooks from workspace, managed,
2424
extra, and bundled directories.
2525

26+
Hook reports (`hooks`, `list`, `info`, and `check`) first request the selected
27+
Gateway's inventory. Configured remote Gateways and explicit
28+
`OPENCLAW_GATEWAY_URL` targets are authoritative: missing URLs, connection or
29+
authentication failures, and unsupported methods fail instead of showing
30+
client-local hooks. An implicitly selected local Gateway may fall back to local
31+
discovery when it is offline or does not support the current hook-report method.
32+
2633
- `--eligible`: only hooks whose requirements are met.
2734
- `--agent <id>`: inspect hooks for that agent's workspace. Required when multiple agents are configured without an implicit owner.
2835
- `--json`: structured output.
@@ -126,7 +133,7 @@ grep '"action":"new"' ~/.openclaw/logs/commands.log | jq . # filter by action
126133

127134
- `hooks list --json`, `info --json`, and `check --json` write structured JSON directly to stdout.
128135
- Failed hook reports use the standard [CLI JSON failure envelope](/cli#json-failures); missing hook info also includes the requested `hook` name.
129-
- `hooks list`, `info`, and `check` pass `--agent` to a running Gateway and preserve it when falling back to local read-only discovery against an older or unavailable Gateway.
136+
- `hooks list`, `info`, and `check` pass `--agent` to a running Gateway and preserve it when an implicit local Gateway requires older-version or offline read-only discovery.
130137

131138
## Related
132139

‎docs/cli/skills.md‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -86,10 +86,19 @@ and verification. Claimed or ClawHub-scanned skills use `@owner/<slug>`.
8686
./path` copies a local skill directory. By default, `install`,
8787
`update`, and `verify` target the active workspace `skills/` directory; with
8888
`--global`, they target the shared managed skills directory. `list`/`info`/`check`
89-
still inspect the local skills visible to the current workspace and config.
90-
Workspace-backed commands resolve the target workspace from `--agent <id>`,
91-
then the current working directory when it is inside a configured agent
92-
workspace, then the default agent.
89+
and bare `openclaw skills` request the selected Gateway's authoritative skill
90+
inventory. A configured remote Gateway or an explicit `OPENCLAW_GATEWAY_URL`
91+
never falls back to client-local skills: missing URLs, connection failures, and
92+
authentication errors remain visible. Only an implicitly selected local Gateway
93+
can fall back to local inventory when it is unavailable. Workspace-backed
94+
commands resolve the target workspace from `--agent <id>`, then the current
95+
working directory when it is inside a configured agent workspace, then the
96+
default agent.
97+
98+
Curator `status`, `pin`, `unpin`, and `restore`, plus Workshop `apply`, preserve
99+
the same target boundary. They never read or mutate client-local state after an
100+
explicitly selected Gateway fails; intentional offline behavior remains
101+
available only for an implicitly selected local Gateway.
93102

94103
Git and local directory installs expect `SKILL.md` at the source root. The
95104
install slug comes from `SKILL.md` frontmatter `name` when it is valid, then

‎src/cli/hooks-cli.toggle.test.ts‎

Lines changed: 173 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
// Hook command tests cover metadata config keys and missing-hook exit status.
22
import { Command } from "commander";
3-
import { beforeEach, describe, expect, it, vi } from "vitest";
3+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4+
import { GatewayClientRequestError } from "../../packages/gateway-client/src/request-error.js";
45
import type { OpenClawConfig } from "../config/types.openclaw.js";
6+
import { GatewayTransportError } from "../gateway/transport-error.js";
57
import { resolveConfiguredInternalHookNames } from "../hooks/configured.js";
68
import type { HookStatusEntry, HookStatusReport } from "../hooks/hooks-status.js";
79
import { ExpectedCliError } from "./failure-output.js";
@@ -45,6 +47,12 @@ vi.mock("../config/config.js", () => ({
4547

4648
vi.mock("../gateway/call.js", () => ({
4749
callGateway: mocks.callGateway,
50+
isGatewayClientRequestError: (error: unknown) =>
51+
error instanceof Error && error.name === "GatewayClientRequestError",
52+
isGatewayCredentialsRequiredError: (error: unknown) =>
53+
error instanceof Error && error.name === "GatewayCredentialsRequiredError",
54+
isImplicitLocalGatewayTarget: async ({ config }: { config?: OpenClawConfig }) =>
55+
!process.env.OPENCLAW_GATEWAY_URL && config?.gateway?.mode !== "remote",
4856
}));
4957

5058
vi.mock("../hooks/hooks-status.js", () => ({
@@ -135,6 +143,16 @@ function createHooksProgram(): Command {
135143
return program;
136144
}
137145

146+
function createGatewayTransportError(kind: "closed" | "timeout", code = 1006) {
147+
return new GatewayTransportError({
148+
kind,
149+
message:
150+
kind === "closed" ? `gateway closed (${code}): unavailable` : "gateway timeout after 1500ms",
151+
connectionDetails: { url: "ws://127.0.0.1:18789", urlSource: "local loopback", message: "" },
152+
...(kind === "closed" ? { code, reason: "unavailable" } : { timeoutMs: 1_500 }),
153+
});
154+
}
155+
138156
function configureExplicitFleet() {
139157
const config = {
140158
...sourceConfig,
@@ -159,10 +177,14 @@ function configureExplicitFleet() {
159177
}
160178

161179
describe("hooks CLI metadata config keys", () => {
180+
afterEach(() => {
181+
vi.unstubAllEnvs();
182+
});
183+
162184
beforeEach(() => {
163185
vi.clearAllMocks();
164186
capture.resetRuntimeCapture();
165-
mocks.callGateway.mockRejectedValue(new Error("gateway unavailable"));
187+
mocks.callGateway.mockRejectedValue(createGatewayTransportError("closed"));
166188
mocks.buildWorkspaceHookStatus.mockReturnValue(report);
167189
mocks.getRuntimeConfig.mockReturnValue(sourceConfig);
168190
mocks.listAgentIds.mockReturnValue(["main"]);
@@ -452,10 +474,7 @@ describe("hooks CLI metadata config keys", () => {
452474
}
453475
if (testCase.phase === "gateway") {
454476
mocks.callGateway.mockRejectedValue(
455-
Object.assign(new Error(testCase.message), {
456-
name: "GatewayClientRequestError",
457-
gatewayCode: "INVALID_REQUEST",
458-
}),
477+
new GatewayClientRequestError({ code: "INVALID_REQUEST", message: testCase.message }),
459478
);
460479
}
461480
if (testCase.phase === "report") {
@@ -542,6 +561,149 @@ describe("hooks CLI metadata config keys", () => {
542561
expect(mocks.buildWorkspaceHookStatus).not.toHaveBeenCalled();
543562
});
544563

564+
const explicitGatewayHookFailures = [
565+
{
566+
label: "configured remote missing URL",
567+
config: { ...sourceConfig, gateway: { mode: "remote" as const } },
568+
message: "gateway remote mode misconfigured: gateway.remote.url missing",
569+
},
570+
{
571+
label: "configured remote transport failure",
572+
config: {
573+
...sourceConfig,
574+
gateway: { mode: "remote" as const, remote: { url: "ws://127.0.0.1:9" } },
575+
},
576+
message: "Gateway not reachable: ws://127.0.0.1:9",
577+
},
578+
{
579+
label: "configured remote auth failure",
580+
config: { ...sourceConfig, gateway: { mode: "remote" as const } },
581+
message: "gateway authentication failed",
582+
},
583+
{
584+
label: "configured remote unsupported method",
585+
config: { ...sourceConfig, gateway: { mode: "remote" as const } },
586+
message: "unknown method: hooks.status",
587+
unsupported: true,
588+
},
589+
{
590+
label: "environment-selected transport failure",
591+
config: sourceConfig,
592+
url: "ws://127.0.0.1:9",
593+
message: "Gateway not reachable: ws://127.0.0.1:9",
594+
},
595+
{
596+
label: "environment-selected auth failure",
597+
config: sourceConfig,
598+
url: "ws://127.0.0.1:9",
599+
message: "gateway authentication failed",
600+
},
601+
{
602+
label: "environment-selected unsupported method",
603+
config: sourceConfig,
604+
url: "ws://127.0.0.1:9",
605+
message: "unknown method: hooks.status",
606+
unsupported: true,
607+
},
608+
];
609+
const hookReadCommands = [
610+
{ label: "default", argv: ["hooks"] },
611+
{ label: "list", argv: ["hooks", "list"] },
612+
{ label: "info", argv: ["hooks", "info", "display-name"] },
613+
{ label: "check", argv: ["hooks", "check"] },
614+
];
615+
616+
it.each(
617+
explicitGatewayHookFailures.flatMap((target) =>
618+
hookReadCommands.flatMap((command) =>
619+
[false, true].map((json) => ({
620+
target,
621+
command,
622+
json,
623+
label: `${command.label} ${json ? "JSON" : "human"}: ${target.label}`,
624+
})),
625+
),
626+
),
627+
)("does not substitute local hooks after $label", async ({ target, command, json }) => {
628+
mocks.getRuntimeConfig.mockReturnValue(target.config);
629+
if (target.url) {
630+
vi.stubEnv("OPENCLAW_GATEWAY_URL", target.url);
631+
}
632+
const error = target.unsupported
633+
? new GatewayClientRequestError({ code: "INVALID_REQUEST", message: target.message })
634+
: new Error(target.message);
635+
mocks.callGateway.mockRejectedValue(error);
636+
637+
const failure = await createHooksProgram()
638+
.parseAsync([...command.argv, ...(json ? ["--json"] : [])], { from: "user" })
639+
.then(
640+
() => undefined,
641+
(caughtError: unknown) => caughtError,
642+
);
643+
expect(failure).toMatchObject({
644+
name: "ExpectedCliError",
645+
message: target.message,
646+
});
647+
648+
expect(mocks.buildWorkspaceHookStatus).not.toHaveBeenCalled();
649+
expect(capture.defaultRuntime.writeStdout).not.toHaveBeenCalled();
650+
expect(mocks.requestExitAfterOneShotOutput).not.toHaveBeenCalled();
651+
});
652+
653+
it.each([
654+
{
655+
label: "request validation",
656+
error: new GatewayClientRequestError({
657+
code: "INVALID_REQUEST",
658+
message: 'invalid hooks.status params: unknown agent id "retired"',
659+
}),
660+
},
661+
{
662+
label: "internal server failure",
663+
error: new GatewayClientRequestError({
664+
code: "INTERNAL_ERROR",
665+
message: "hook inventory crashed",
666+
}),
667+
},
668+
{ label: "pairing close", error: createGatewayTransportError("closed", 1008) },
669+
{ label: "authentication rotation", error: createGatewayTransportError("closed", 4001) },
670+
{ label: "plain pairing close", error: new Error("gateway closed (1008): pairing required") },
671+
{
672+
label: "plain authentication close",
673+
error: new Error("gateway closed (4001): auth changed"),
674+
},
675+
{ label: "unknown failure", error: new Error("gateway unavailable") },
676+
])("does not substitute implicit-local hooks after $label", async ({ error }) => {
677+
mocks.callGateway.mockRejectedValue(error);
678+
679+
await expect(
680+
createHooksProgram().parseAsync(["hooks", "list", "--json"], { from: "user" }),
681+
).rejects.toMatchObject({ message: error.message });
682+
683+
expect(mocks.buildWorkspaceHookStatus).not.toHaveBeenCalled();
684+
expect(mocks.requestExitAfterOneShotOutput).not.toHaveBeenCalled();
685+
});
686+
687+
it.each([
688+
{
689+
label: "missing credentials before connecting",
690+
error: Object.assign(new Error("gateway requires credentials"), {
691+
name: "GatewayCredentialsRequiredError",
692+
method: "hooks.status",
693+
configPath: "/tmp/openclaw.json",
694+
}),
695+
},
696+
{ label: "typed timeout", error: createGatewayTransportError("timeout") },
697+
{ label: "pending-request close", error: new Error("gateway closed (1006): abnormal closure") },
698+
{ label: "pending-request timeout", error: new Error("gateway timeout after 1500ms") },
699+
])("retains implicit-local hook discovery after $label", async ({ error }) => {
700+
mocks.callGateway.mockRejectedValue(error);
701+
702+
await createHooksProgram().parseAsync(["hooks", "list", "--json"], { from: "user" });
703+
704+
expect(mocks.buildWorkspaceHookStatus).toHaveBeenCalledOnce();
705+
});
706+
545707
it.each([
546708
["list", ["hooks", "list", "--agent", "research", "--json"]],
547709
["info", ["hooks", "info", "display-name", "--agent", "research", "--json"]],
@@ -652,9 +814,9 @@ describe("hooks CLI metadata config keys", () => {
652814
});
653815

654816
it("does not replace an authoritative Gateway ownership error with a local report", async () => {
655-
const error = Object.assign(new Error('unknown agent id "retired"'), {
656-
name: "GatewayClientRequestError",
657-
gatewayCode: "INVALID_REQUEST",
817+
const error = new GatewayClientRequestError({
818+
code: "INVALID_REQUEST",
819+
message: 'unknown agent id "retired"',
658820
});
659821
mocks.callGateway.mockRejectedValue(error);
660822

@@ -672,12 +834,10 @@ describe("hooks CLI metadata config keys", () => {
672834
it.each([
673835
"unknown method: hooks.status",
674836
"invalid hooks.status params: unexpected property agentId",
837+
"invalid hooks.status params: at root: unexpected property 'agentId'",
675838
])("uses the selected local fallback for an older Gateway: %s", async (message) => {
676839
mocks.callGateway.mockRejectedValue(
677-
Object.assign(new Error(message), {
678-
name: "GatewayClientRequestError",
679-
gatewayCode: "INVALID_REQUEST",
680-
}),
840+
new GatewayClientRequestError({ code: "INVALID_REQUEST", message }),
681841
);
682842

683843
await createHooksProgram().parseAsync(["hooks", "list", "--agent", "main", "--json"], {

‎src/cli/hooks-cli.ts‎

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
} from "../agents/agent-scope.js";
1515
import { getRuntimeConfig, readConfigFileSnapshot, replaceConfigFile } from "../config/config.js";
1616
import type { OpenClawConfig } from "../config/types.openclaw.js";
17+
import { isGatewayRpcUnavailableError } from "../gateway/transport-error.js";
1718
import {
1819
buildWorkspaceHookStatus,
1920
type HookStatusEntry,
@@ -110,8 +111,13 @@ function buildHooksReport(config: OpenClawConfig, target: HooksReportTarget): Ho
110111
async function loadHooksReport(agentId?: string): Promise<HookStatusReport> {
111112
const config = getRuntimeConfig({ skipPluginValidation: true });
112113
const target = resolveHooksReportTarget(config, agentId);
114+
const {
115+
callGateway,
116+
isGatewayClientRequestError,
117+
isGatewayCredentialsRequiredError,
118+
isImplicitLocalGatewayTarget,
119+
} = await import("../gateway/call.js");
113120
try {
114-
const { callGateway } = await import("../gateway/call.js");
115121
return await callGateway<HookStatusReport>({
116122
config,
117123
method: "hooks.status",
@@ -121,19 +127,24 @@ async function loadHooksReport(agentId?: string): Promise<HookStatusReport> {
121127
mode: GATEWAY_CLIENT_MODES.CLI,
122128
});
123129
} catch (error) {
130+
const isLegacyHookReport =
131+
isGatewayClientRequestError(error) &&
132+
error.gatewayCode === "INVALID_REQUEST" &&
133+
(error.message === "unknown method: hooks.status" ||
134+
/^invalid hooks\.status params: (?:unexpected property agentId|at root: unexpected property 'agentId')$/u.test(
135+
error.message,
136+
));
124137
if (
125-
error instanceof Error &&
126-
error.name === "GatewayClientRequestError" &&
127138
!(
128-
(error as Error & { gatewayCode?: unknown }).gatewayCode === "INVALID_REQUEST" &&
129-
/^(?:unknown method: hooks\.status|invalid hooks\.status params(?::|$))/iu.test(
130-
error.message,
131-
)
132-
)
139+
isGatewayCredentialsRequiredError(error) ||
140+
isGatewayRpcUnavailableError(error) ||
141+
isLegacyHookReport
142+
) ||
143+
!(await isImplicitLocalGatewayTarget({ config }))
133144
) {
134145
throw error;
135146
}
136-
// Unavailable and older Gateways retain the selected owner for local read-only discovery.
147+
// Only implicit local Gateways may use offline or older-Gateway discovery.
137148
return buildHooksReport(config, target);
138149
}
139150
}

0 commit comments

Comments
 (0)