Skip to content

Commit 738f5f7

Browse files
committed
fix: prevent channel login exec wedges
1 parent ed98762 commit 738f5f7

13 files changed

Lines changed: 517 additions & 14 deletions

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,8 @@ Docs: https://docs.openclaw.ai
4545
- Discord: own the Carbon interaction listener and hand off Discord slash/component handling asynchronously, so compaction or long session locks no longer trip `InteractionEventListener` listener timeouts. Fixes #73204. Thanks @slideshow-dingo.
4646
- Compaction/diagnostics: keep unknown compaction failure classifications stable while logging sanitized detail for unclassified provider errors such as missing Ollama provider adapters. Thanks @gzsiang.
4747
- Models/fallbacks: record first-class `model.fallback_step` trajectory events with from/to models, failure detail, chain position, and final outcome so support exports preserve the primary model failure even when a later fallback also fails. Fixes #71744. Thanks @nikolaykazakovvs-ux.
48+
- Gateway/agents: block agent `exec` from launching interactive `openclaw channels login` flows and abort active agent runs after invalid-config recovery restores last-known-good config, preventing known channel-login and reload paths from wedging replies. Refs #72338. Thanks @midhunmonachan.
49+
- Gateway/diagnostics: emit payload-free liveness warnings with event-loop delay, event-loop utilization, CPU-core ratio, and active-session counts so live-but-stalled Gateways capture CPU-spin context in stability bundles. Refs #72338. Thanks @midhunmonachan and @DougButdorf.
4850
- Gateway/startup: keep value-option foreground starts on the gateway fast path and skip proxy bootstrap unless proxy env is configured, reducing normal gateway startup RSS and avoiding full CLI graph loading. Thanks @vincentkoc.
4951
- Heartbeat/models: show heartbeat model bleed guidance on context-overflow resets when the last runtime model matches configured `heartbeat.model`, so smaller local heartbeat models point users to `isolatedSession` or `lightContext` instead of only compaction-buffer tuning. Fixes #67314. Thanks @Knightmare6890.
5052
- Subagents/models: persist `sessions_spawn.model` and configured subagent models as child-session model overrides before the first turn, so spawned subagents actually run on the requested provider/model instead of reverting to the target agent default. Fixes #73180. Thanks @danielzinhu99.

‎docs/cli/channels.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ openclaw channels logout --channel whatsapp
9292

9393
- `channels login` supports `--verbose`.
9494
- `channels login` and `logout` can infer the channel when only one supported login target is configured.
95+
- Run `channels login` from a terminal on the gateway host. Agent `exec` blocks this interactive login flow; channel-native agent login tools, such as `whatsapp_login`, should be used from chat when available.
9596

9697
## Troubleshooting
9798

‎docs/gateway/diagnostics.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,12 @@ export keeps only that a message was omitted and the byte count.
7171
The Gateway records a bounded, payload-free stability stream by default when
7272
diagnostics are enabled. It is for operational facts, not content.
7373

74+
The same diagnostic heartbeat records liveness warnings when the Gateway keeps
75+
running but the Node.js event loop or CPU looks saturated. These
76+
`diagnostic.liveness.warning` events include event-loop delay, event-loop
77+
utilization, CPU-core ratio, and active/waiting/queued session counts. They do
78+
not restart the Gateway by themselves.
79+
7480
Inspect the live recorder:
7581

7682
```bash

‎docs/gateway/health.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ Short guide to verify channel connectivity without guessing.
2424
- Creds on disk: `ls -l ~/.openclaw/credentials/whatsapp/<accountId>/creds.json` (mtime should be recent).
2525
- Session store: `ls -l ~/.openclaw/agents/<agentId>/sessions/sessions.json` (path can be overridden in config). Count and recent recipients are surfaced via `status`.
2626
- Relink flow: `openclaw channels logout && openclaw channels login --verbose` when status codes 409–515 or `loggedOut` appear in logs. (Note: the QR login flow auto-restarts once for status 515 after pairing.)
27-
- Diagnostics are enabled by default. The gateway records operational facts unless `diagnostics.enabled: false` is set. Memory events record RSS/heap byte counts, threshold pressure, and growth pressure. Oversized-payload events record what was rejected, truncated, or chunked, plus sizes and limits when available. They do not record the message text, attachment contents, webhook body, raw request or response body, tokens, cookies, or secret values. The same heartbeat starts the bounded stability recorder, which is available through `openclaw gateway stability` or the `diagnostics.stability` Gateway RPC. Fatal Gateway exits, shutdown timeouts, and restart startup failures persist the latest recorder snapshot under `~/.openclaw/logs/stability/` when events exist; inspect the newest saved bundle with `openclaw gateway stability --bundle latest`.
27+
- Diagnostics are enabled by default. The gateway records operational facts unless `diagnostics.enabled: false` is set. Memory events record RSS/heap byte counts, threshold pressure, and growth pressure. Liveness warnings record event-loop delay, event-loop utilization, CPU-core ratio, and active/waiting/queued session counts when the process is running but saturated. Oversized-payload events record what was rejected, truncated, or chunked, plus sizes and limits when available. They do not record the message text, attachment contents, webhook body, raw request or response body, tokens, cookies, or secret values. The same heartbeat starts the bounded stability recorder, which is available through `openclaw gateway stability` or the `diagnostics.stability` Gateway RPC. Fatal Gateway exits, shutdown timeouts, and restart startup failures persist the latest recorder snapshot under `~/.openclaw/logs/stability/` when events exist; inspect the newest saved bundle with `openclaw gateway stability --bundle latest`.
2828
- For bug reports, run `openclaw gateway diagnostics export` and attach the generated zip. The export combines a Markdown summary, the newest stability bundle, sanitized log metadata, sanitized Gateway status/health snapshots, and config shape. It is meant to be shared: chat text, webhook bodies, tool outputs, credentials, cookies, account/message identifiers, and secret values are omitted or redacted. See [Diagnostics Export](/gateway/diagnostics).
2929

3030
## Health monitor config

‎docs/tools/exec.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ Notes:
7878
- Host execution (`gateway`/`node`) rejects `env.PATH` and loader overrides (`LD_*`/`DYLD_*`) to
7979
prevent binary hijacking or injected code.
8080
- OpenClaw sets `OPENCLAW_SHELL=exec` in the spawned command environment (including PTY and sandbox execution) so shell/profile rules can detect exec-tool context.
81+
- `openclaw channels login` is blocked from `exec` because it is an interactive channel-auth flow; run it in a terminal on the gateway host, or use the channel-native login tool from chat when one exists.
8182
- Important: sandboxing is **off by default**. If sandboxing is off, implicit `host=auto`
8283
resolves to `gateway`. Explicit `host=sandbox` still fails closed instead of silently
8384
running on the gateway host. Enable sandboxing or use `host=gateway` with approvals.

‎src/agents/bash-tools.exec.script-preflight.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ const isWin = process.platform === "win32";
2424

2525
const describeNonWin = isWin ? describe.skip : describe;
2626
const describeWin = isWin ? describe : describe.skip;
27+
const parseOpenClawChannelsLoginShellCommand = __testing.parseOpenClawChannelsLoginShellCommand;
2728
const validateExecScriptPreflight = __testing.validateScriptFileForShellBleed;
2829
const createPreflightTool = () =>
2930
createExecTool({ host: "gateway", security: "full", ask: "on-miss" });
@@ -66,6 +67,35 @@ async function expectSymlinkSwapDuringPreflightToAvoidErrors(params: {
6667
});
6768
}
6869

70+
describe("exec interactive OpenClaw channel login guard", () => {
71+
it("recognizes direct and package-runner channel login commands before execution", () => {
72+
expect(
73+
parseOpenClawChannelsLoginShellCommand("openclaw channels login --channel whatsapp"),
74+
).toBe(true);
75+
expect(
76+
parseOpenClawChannelsLoginShellCommand(
77+
"pnpm exec openclaw channels login --channel whatsapp --verbose",
78+
),
79+
).toBe(true);
80+
expect(parseOpenClawChannelsLoginShellCommand("openclaw channels status --deep")).toBe(false);
81+
});
82+
83+
it("blocks interactive channel login commands from exec", async () => {
84+
const tool = createPreflightTool();
85+
86+
await expect(
87+
tool.execute("call-openclaw-channel-login", {
88+
command: "openclaw channels login --channel whatsapp --verbose",
89+
}),
90+
).rejects.toThrow(/exec cannot run interactive OpenClaw channel login commands/);
91+
await expect(
92+
tool.execute("call-wrapped-openclaw-channel-login", {
93+
command: "sudo -u openclaw bash -lc 'openclaw channels login --channel whatsapp'",
94+
}),
95+
).rejects.toThrow(/exec cannot run interactive OpenClaw channel login commands/);
96+
});
97+
});
98+
6999
describeNonWin("exec script preflight", () => {
70100
it("blocks shell env var injection tokens in python scripts before execution", async () => {
71101
await withTempDir("openclaw-exec-preflight-", async (tmp) => {

‎src/agents/bash-tools.exec.ts‎

Lines changed: 80 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1074,7 +1074,69 @@ function parseExecApprovalShellCommand(raw: string): ParsedExecApprovalCommand |
10741074
};
10751075
}
10761076

1077-
function rejectExecApprovalShellCommand(command: string): void {
1077+
function normalizeCommandBaseName(token: string | undefined): string {
1078+
if (!token) {
1079+
return "";
1080+
}
1081+
const base = normalizeLowercaseStringOrEmpty(token.split(/[\\/]/u).at(-1));
1082+
return base.replace(/\.(?:cmd|exe)$/u, "");
1083+
}
1084+
1085+
function stripOpenClawPackageRunner(argv: string[]): string[] {
1086+
const commandName = normalizeCommandBaseName(argv[0]);
1087+
if (commandName === "openclaw") {
1088+
return argv;
1089+
}
1090+
if (
1091+
(commandName === "pnpm" || commandName === "npm" || commandName === "yarn") &&
1092+
normalizeCommandBaseName(argv[1]) === "openclaw"
1093+
) {
1094+
return argv.slice(1);
1095+
}
1096+
if (
1097+
(commandName === "pnpm" || commandName === "npm" || commandName === "yarn") &&
1098+
(argv[1] === "exec" || argv[1] === "dlx" || argv[1] === "run") &&
1099+
normalizeCommandBaseName(argv[2]) === "openclaw"
1100+
) {
1101+
return argv.slice(2);
1102+
}
1103+
if (commandName === "npx" || commandName === "bunx") {
1104+
let idx = 1;
1105+
while (idx < argv.length) {
1106+
const token = argv[idx];
1107+
if (token === "--") {
1108+
idx += 1;
1109+
break;
1110+
}
1111+
if (!token.startsWith("-") || token === "-") {
1112+
break;
1113+
}
1114+
idx += 1;
1115+
if ((token === "-p" || token === "--package") && idx < argv.length) {
1116+
idx += 1;
1117+
}
1118+
}
1119+
if (normalizeCommandBaseName(argv[idx]) === "openclaw") {
1120+
return argv.slice(idx);
1121+
}
1122+
}
1123+
return argv;
1124+
}
1125+
1126+
function parseOpenClawChannelsLoginShellCommand(raw: string): boolean {
1127+
const argv = splitShellArgs(raw);
1128+
if (!argv) {
1129+
return false;
1130+
}
1131+
const openclawArgv = stripOpenClawPackageRunner(argv);
1132+
return (
1133+
normalizeCommandBaseName(openclawArgv[0]) === "openclaw" &&
1134+
(openclawArgv[1] === "channels" || openclawArgv[1] === "channel") &&
1135+
openclawArgv[2] === "login"
1136+
);
1137+
}
1138+
1139+
function rejectUnsafeControlShellCommand(command: string): void {
10781140
const isEnvAssignmentToken = (token: string): boolean =>
10791141
/^[A-Za-z_][A-Za-z0-9_]*=.*$/u.test(token);
10801142
const shellWrappers = new Set(["bash", "dash", "fish", "ksh", "sh", "zsh"]);
@@ -1295,15 +1357,22 @@ function rejectExecApprovalShellCommand(command: string): void {
12951357
return argv ? buildCandidates(argv) : [line];
12961358
});
12971359
for (const candidate of candidates) {
1298-
if (!parseExecApprovalShellCommand(candidate)) {
1299-
continue;
1360+
if (parseExecApprovalShellCommand(candidate)) {
1361+
throw new Error(
1362+
[
1363+
"exec cannot run /approve commands.",
1364+
"Show the /approve command to the user as chat text, or route it through the approval command handler instead of shell execution.",
1365+
].join(" "),
1366+
);
1367+
}
1368+
if (parseOpenClawChannelsLoginShellCommand(candidate)) {
1369+
throw new Error(
1370+
[
1371+
"exec cannot run interactive OpenClaw channel login commands.",
1372+
"Run `openclaw channels login` in a terminal on the gateway host, or use the channel-specific login agent tool when available (for WhatsApp: `whatsapp_login`).",
1373+
].join(" "),
1374+
);
13001375
}
1301-
throw new Error(
1302-
[
1303-
"exec cannot run /approve commands.",
1304-
"Show the /approve command to the user as chat text, or route it through the approval command handler instead of shell execution.",
1305-
].join(" "),
1306-
);
13071376
}
13081377
}
13091378

@@ -1532,7 +1601,7 @@ export function createExecTool(
15321601
const rawWorkdir = explicitWorkdir ?? defaultWorkdir ?? process.cwd();
15331602
workdir = resolveWorkdir(rawWorkdir, warnings);
15341603
}
1535-
rejectExecApprovalShellCommand(params.command);
1604+
rejectUnsafeControlShellCommand(params.command);
15361605

15371606
const inheritedBaseEnv = coerceEnv(process.env);
15381607
const hostEnvResult =
@@ -1813,5 +1882,6 @@ export function createExecTool(
18131882
export const execTool = createExecTool();
18141883

18151884
export const __testing = {
1885+
parseOpenClawChannelsLoginShellCommand,
18161886
validateScriptFileForShellBleed,
18171887
};
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import { afterEach, describe, expect, it, vi } from "vitest";
2+
import {
3+
__testing as embeddedRunTesting,
4+
clearActiveEmbeddedRun,
5+
setActiveEmbeddedRun,
6+
type EmbeddedPiQueueHandle,
7+
} from "../agents/pi-embedded-runner/runs.js";
8+
import { __testing } from "./server-reload-handlers.js";
9+
10+
describe("gateway reload recovery handlers", () => {
11+
afterEach(() => {
12+
embeddedRunTesting.resetActiveEmbeddedRuns();
13+
});
14+
15+
it("aborts active agent runs after last-known-good config recovery", () => {
16+
const sessionId = "config-recovery-session";
17+
const sessionKey = "agent:main:telegram:direct:123";
18+
let handle!: EmbeddedPiQueueHandle;
19+
handle = {
20+
abort: vi.fn(() => {
21+
clearActiveEmbeddedRun(sessionId, handle, sessionKey);
22+
}),
23+
isCompacting: () => false,
24+
isStreaming: () => false,
25+
queueMessage: async () => {},
26+
};
27+
const logReload = { info: vi.fn(), warn: vi.fn() };
28+
setActiveEmbeddedRun(sessionId, handle, sessionKey);
29+
30+
__testing.abortActiveAgentRunsAfterConfigRecovery({
31+
reason: "invalid-config",
32+
logReload,
33+
});
34+
35+
expect(handle.abort).toHaveBeenCalledOnce();
36+
expect(logReload.warn).toHaveBeenCalledWith(
37+
"config recovery aborted active agent run(s) after reload-invalid-config",
38+
);
39+
});
40+
41+
it("does not warn when config recovery has no active agent runs to abort", () => {
42+
const logReload = { info: vi.fn(), warn: vi.fn() };
43+
44+
__testing.abortActiveAgentRunsAfterConfigRecovery({
45+
reason: "invalid-config",
46+
logReload,
47+
});
48+
49+
expect(logReload.warn).not.toHaveBeenCalled();
50+
});
51+
});

‎src/gateway/server-reload-handlers.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { resetModelCatalogCache } from "../agents/model-catalog.js";
22
import { disposeAllSessionMcpRuntimes } from "../agents/pi-bundle-mcp-tools.js";
33
import { getActiveEmbeddedRunCount } from "../agents/pi-embedded-runner/run-state.js";
4+
import { abortEmbeddedPiRun } from "../agents/pi-embedded-runner/runs.js";
45
import { getTotalPendingReplies } from "../auto-reply/reply/dispatcher-registry.js";
56
import type { CliDeps } from "../cli/deps.types.js";
67
import { isRestartEnabled } from "../config/commands.flags.js";
@@ -59,6 +60,23 @@ const MCP_RUNTIME_RELOAD_DISPOSE_TIMEOUT_MS = 5_000;
5960
const CHANNEL_RELOAD_DEFERRAL_POLL_MS = 500;
6061
const CHANNEL_RELOAD_STILL_PENDING_WARN_MS = 30_000;
6162

63+
function abortActiveAgentRunsAfterConfigRecovery(params: {
64+
reason: string;
65+
logReload: GatewayReloadLog;
66+
}) {
67+
const aborted = abortEmbeddedPiRun(undefined, { mode: "all" });
68+
if (!aborted) {
69+
return;
70+
}
71+
params.logReload.warn(
72+
`config recovery aborted active agent run(s) after reload-${params.reason}`,
73+
);
74+
}
75+
76+
export const __testing = {
77+
abortActiveAgentRunsAfterConfigRecovery,
78+
};
79+
6280
async function disposeMcpRuntimesWithTimeout(params: {
6381
dispose: () => Promise<void>;
6482
timeoutMs: number;
@@ -418,6 +436,7 @@ export function startManagedGatewayConfigReloader(params: ManagedGatewayConfigRe
418436
await params.recoverSnapshot({ snapshot, reason: `reload-${reason}` }),
419437
promoteSnapshot: async (snapshot, _reason) => await params.promoteSnapshot(snapshot),
420438
onRecovered: ({ reason, snapshot, recoveredSnapshot }) => {
439+
abortActiveAgentRunsAfterConfigRecovery({ reason, logReload: params.logReload });
421440
enqueueConfigRecoveryNotice({
422441
cfg: recoveredSnapshot.config,
423442
phase: "reload",

‎src/infra/diagnostic-events.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,24 @@ export type DiagnosticHeartbeatEvent = DiagnosticBaseEvent & {
166166
queued: number;
167167
};
168168

169+
export type DiagnosticLivenessWarningReason = "event_loop_delay" | "event_loop_utilization" | "cpu";
170+
171+
export type DiagnosticLivenessWarningEvent = DiagnosticBaseEvent & {
172+
type: "diagnostic.liveness.warning";
173+
reasons: DiagnosticLivenessWarningReason[];
174+
intervalMs: number;
175+
eventLoopDelayP99Ms?: number;
176+
eventLoopDelayMaxMs?: number;
177+
eventLoopUtilization?: number;
178+
cpuUserMs?: number;
179+
cpuSystemMs?: number;
180+
cpuTotalMs?: number;
181+
cpuCoreRatio?: number;
182+
active: number;
183+
waiting: number;
184+
queued: number;
185+
};
186+
169187
export type DiagnosticToolLoopEvent = DiagnosticBaseEvent & {
170188
type: "tool.loop";
171189
sessionKey?: string;
@@ -441,6 +459,7 @@ export type DiagnosticEventPayload =
441459
| DiagnosticLaneDequeueEvent
442460
| DiagnosticRunAttemptEvent
443461
| DiagnosticHeartbeatEvent
462+
| DiagnosticLivenessWarningEvent
444463
| DiagnosticToolLoopEvent
445464
| DiagnosticToolExecutionStartedEvent
446465
| DiagnosticToolExecutionCompletedEvent

0 commit comments

Comments
 (0)