Skip to content

Commit 64dc17a

Browse files
committed
refactor(cli): consolidate Gateway fallback and hook ownership
1 parent 971feb5 commit 64dc17a

4 files changed

Lines changed: 103 additions & 162 deletions

File tree

‎config/assertion-safety-baseline.txt‎

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

‎src/cli/gateway-rpc.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import type {
44
GatewayClientMode,
55
GatewayClientName,
66
} from "../../packages/gateway-protocol/src/client-info.js";
7+
import type { OpenClawConfig } from "../config/types.openclaw.js";
78
import type { OperatorScope } from "../gateway/operator-scopes.js";
89
import type { DeviceIdentity } from "../infra/device-identity.js";
910
import { createLazyImportLoader } from "../shared/lazy-promise.js";
@@ -55,6 +56,33 @@ export async function isImplicitLocalGatewayTargetFromCli(opts: GatewayRpcOpts):
5556
return await runtime.isImplicitLocalGatewayTargetFromCliRuntime(opts);
5657
}
5758

59+
/** Local fallback is safe only for unavailable or explicitly supported older local Gateways. */
60+
export async function canFallbackToImplicitLocalGateway(params: {
61+
config: OpenClawConfig;
62+
error: unknown;
63+
legacyMethod?: string;
64+
legacyAgentId?: boolean;
65+
}): Promise<boolean> {
66+
const gateway = await import("../gateway/call.js");
67+
const { isGatewayRpcUnavailableError } = await import("../gateway/transport-error.js");
68+
const { config, error, legacyMethod, legacyAgentId } = params;
69+
const isLegacyError =
70+
legacyMethod !== undefined &&
71+
gateway.isGatewayClientRequestError(error) &&
72+
error.gatewayCode === "INVALID_REQUEST" &&
73+
(error.message === `unknown method: ${legacyMethod}` ||
74+
(legacyAgentId === true &&
75+
(error.message === `invalid ${legacyMethod} params: unexpected property agentId` ||
76+
error.message ===
77+
`invalid ${legacyMethod} params: at root: unexpected property 'agentId'`)));
78+
return (
79+
(gateway.isGatewayCredentialsRequiredError(error) ||
80+
isGatewayRpcUnavailableError(error) ||
81+
isLegacyError) &&
82+
(await gateway.isImplicitLocalGatewayTarget({ config }))
83+
);
84+
}
85+
5886
/** Internal CLI facade for callers that need transport or auth policy overrides. */
5987
export async function callGatewayFromCliWithTransport(
6088
method: string,

‎src/cli/hooks-cli.ts‎

Lines changed: 32 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ 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";
1817
import {
1918
buildWorkspaceHookStatus,
2019
type HookStatusEntry,
@@ -31,6 +30,7 @@ import { summarizeStringEntries } from "../shared/string-sample.js";
3130
import { resolveOptionFromCommand } from "./cli-utils.js";
3231
import { formatCliCommand } from "./command-format.js";
3332
import { ExpectedCliError, rethrowExpectedCliError } from "./failure-output.js";
33+
import { canFallbackToImplicitLocalGateway } from "./gateway-rpc.js";
3434
import {
3535
formatHookInfo,
3636
formatHookMissingSummary,
@@ -111,12 +111,7 @@ function buildHooksReport(config: OpenClawConfig, target: HooksReportTarget): Ho
111111
async function loadHooksReport(agentId?: string): Promise<HookStatusReport> {
112112
const config = getRuntimeConfig({ skipPluginValidation: true });
113113
const target = resolveHooksReportTarget(config, agentId);
114-
const {
115-
callGateway,
116-
isGatewayClientRequestError,
117-
isGatewayCredentialsRequiredError,
118-
isImplicitLocalGatewayTarget,
119-
} = await import("../gateway/call.js");
114+
const { callGateway } = await import("../gateway/call.js");
120115
try {
121116
return await callGateway<HookStatusReport>({
122117
config,
@@ -127,20 +122,13 @@ async function loadHooksReport(agentId?: string): Promise<HookStatusReport> {
127122
mode: GATEWAY_CLIENT_MODES.CLI,
128123
});
129124
} 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-
));
137125
if (
138-
!(
139-
isGatewayCredentialsRequiredError(error) ||
140-
isGatewayRpcUnavailableError(error) ||
141-
isLegacyHookReport
142-
) ||
143-
!(await isImplicitLocalGatewayTarget({ config }))
126+
!(await canFallbackToImplicitLocalGateway({
127+
config,
128+
error,
129+
legacyMethod: "hooks.status",
130+
legacyAgentId: true,
131+
}))
144132
) {
145133
throw error;
146134
}
@@ -196,30 +184,6 @@ function resolveHookForToggle(
196184
return hook;
197185
}
198186

199-
function buildConfigWithHookEnabled(params: {
200-
config: OpenClawConfig;
201-
hookName: string;
202-
enabled: boolean;
203-
ensureHooksEnabled?: boolean;
204-
}): OpenClawConfig {
205-
const entries = { ...params.config.hooks?.internal?.entries };
206-
entries[params.hookName] = { ...entries[params.hookName], enabled: params.enabled };
207-
208-
const internal = {
209-
...params.config.hooks?.internal,
210-
...(params.ensureHooksEnabled ? { enabled: true } : {}),
211-
entries,
212-
};
213-
214-
return {
215-
...params.config,
216-
hooks: {
217-
...params.config.hooks,
218-
internal,
219-
},
220-
};
221-
}
222-
223187
function writeHooksOutput(value: string, json: boolean | undefined): void {
224188
if (json) {
225189
defaultRuntime.writeStdout(value);
@@ -248,50 +212,39 @@ async function runOneShotHooksCliAction(
248212
// runCli finishes shared teardown and drains both output streams.
249213
requestExitAfterOneShotOutput(defaultRuntime, exitCode);
250214
}
251-
async function enableHook(hookName: string, agentId?: string): Promise<void> {
252-
const snapshot = await readConfigFileSnapshot();
253-
const config = (snapshot.sourceConfig ?? snapshot.config) as OpenClawConfig;
254-
const hook = resolveHookForToggle(
255-
buildHooksReport(config, resolveHooksReportTarget(config, agentId)),
256-
hookName,
257-
{ requireEligible: true },
258-
);
259-
const nextConfig = buildConfigWithHookEnabled({
260-
config,
261-
hookName: hook.hookKey,
262-
enabled: true,
263-
ensureHooksEnabled: true,
264-
});
265-
266-
await replaceConfigFile({
267-
nextConfig,
268-
...(snapshot.hash !== undefined ? { baseHash: snapshot.hash } : {}),
269-
});
270-
defaultRuntime.log(
271-
`${theme.success("✓")} Enabled hook: ${hook.emoji ? `${hook.emoji} ${theme.command(hook.name)}` : decorativePrefix("🔗", theme.command(hook.name))}`,
272-
);
273-
}
274-
275-
async function disableHook(hookName: string, agentId?: string): Promise<void> {
215+
async function setHookEnabled(hookName: string, enabled: boolean, agentId?: string): Promise<void> {
276216
const snapshot = await readConfigFileSnapshot();
277217
const config = (snapshot.sourceConfig ?? snapshot.config) as OpenClawConfig;
278218
const hook = resolveHookForToggle(
279219
buildHooksReport(config, resolveHooksReportTarget(config, agentId)),
280220
hookName,
221+
{ requireEligible: enabled },
281222
);
282-
const nextConfig = buildConfigWithHookEnabled({
283-
config,
284-
hookName: hook.hookKey,
285-
enabled: false,
286-
});
223+
const entries = { ...config.hooks?.internal?.entries };
224+
entries[hook.hookKey] = { ...entries[hook.hookKey], enabled };
225+
const nextConfig: OpenClawConfig = {
226+
...config,
227+
hooks: {
228+
...config.hooks,
229+
internal: {
230+
...config.hooks?.internal,
231+
...(enabled ? { enabled: true } : {}),
232+
entries,
233+
},
234+
},
235+
};
287236

288237
await replaceConfigFile({
289238
nextConfig,
290239
...(snapshot.hash !== undefined ? { baseHash: snapshot.hash } : {}),
291240
});
292-
defaultRuntime.log(
293-
`${theme.warn(decorativePrefix("⏸", "Disabled hook:"))} ${hook.emoji ? `${hook.emoji} ${theme.command(hook.name)}` : decorativePrefix("🔗", theme.command(hook.name))}`,
294-
);
241+
const prefix = enabled
242+
? `${theme.success("✓")} Enabled hook:`
243+
: theme.warn(decorativePrefix("⏸", "Disabled hook:"));
244+
const name = hook.emoji
245+
? `${hook.emoji} ${theme.command(hook.name)}`
246+
: decorativePrefix("🔗", theme.command(hook.name));
247+
defaultRuntime.log(`${prefix} ${name}`);
295248
}
296249

297250
export function registerHooksCli(program: Command): void {
@@ -371,7 +324,7 @@ export function registerHooksCli(program: Command): void {
371324
.option("--agent <id>", "Agent id whose workspace to inspect")
372325
.action(async (name, _opts: { agent?: string }, command: Command) =>
373326
runOneShotHooksCliAction(async () => {
374-
await enableHook(name, resolveHooksAgentOption(command));
327+
await setHookEnabled(name, true, resolveHooksAgentOption(command));
375328
}),
376329
);
377330

@@ -381,7 +334,7 @@ export function registerHooksCli(program: Command): void {
381334
.option("--agent <id>", "Agent id whose workspace to inspect")
382335
.action(async (name, _opts: { agent?: string }, command: Command) =>
383336
runOneShotHooksCliAction(async () => {
384-
await disableHook(name, resolveHooksAgentOption(command));
337+
await setHookEnabled(name, false, resolveHooksAgentOption(command));
385338
}),
386339
);
387340

0 commit comments

Comments
 (0)