Skip to content

Commit a6b0272

Browse files
committed
fix(cli): guard embedded agent state ownership
1 parent cb9bf8c commit a6b0272

6 files changed

Lines changed: 277 additions & 23 deletions

File tree

‎docs/cli/agent.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,7 @@ openclaw agent --agent ops --message "Run locally" --local
165165
- Pass exactly one of `--message` or `--message-file`. `--message-file` strips a leading UTF-8 BOM and preserves multiline content; it rejects files that are not valid UTF-8. Files larger than 4 MiB are rejected before dispatch.
166166
- Slash commands (for example `/compact`) cannot run through `--message`. The CLI rejects them and points you at the first-class command instead (`openclaw sessions compact <key>` for compaction).
167167
- `--local` runs are one-shot: bundled MCP loopback resources and warm Claude stdio sessions opened for the run are retired after the reply, so scripted invocations do not leave local child processes running. Gateway-backed runs keep Gateway-owned MCP loopback resources under the running Gateway process instead.
168+
- `--local` requires exclusive ownership of the configured state directory. It refuses to start while a Gateway or another `agent --local` run owns that directory, then holds the same state lock for the full embedded turn. Run without `--local` to use the active Gateway, or stop it first with `openclaw gateway stop`.
168169
- Standalone embedded execution with `--local` refuses to reuse an existing main session while restart recovery is pending. Run the turn through a healthy Gateway, or reset it there with `/new` or `/reset`; an independent embedded process cannot safely coordinate that recovery owner with the Gateway scanner.
169170
- With `--agent`, `--channel` and `--to` together, session routing follows the channel's canonical recipient and `session.dmScope`. Channels with a stable outbound-only recipient identity use a provider-owned session isolated from the agent's main session. `--reply-channel` and `--reply-account` affect delivery only.
170171
- `--session-key` selects an explicit session key. Agent-prefixed keys must use `agent:<agent-id>:<session-key>`, and `--agent` must match the key's agent id when both are given. Bare non-sentinel keys scope to `--agent` when supplied, or to the configured default agent otherwise; for example `--agent ops --session-key incident-42` routes to `agent:ops:incident-42`. The literal keys `global` and `unknown` stay unscoped only when no `--agent` is supplied.

‎src/cli/gateway-cli/run.supervised-lock.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,30 @@ describe("supervised gateway lock recovery", () => {
102102
expect(testing.resolveGatewayLockErrorExitCode(failure)).toBe(78);
103103
});
104104

105+
it("preserves an agent-embedded owner error under a supervisor", async () => {
106+
const err = new GatewayLockError(
107+
"another openclaw agent --local run is active (pid 123); lock timeout after 5000ms",
108+
);
109+
const startLoop = vi.fn(async () => {
110+
throw err;
111+
});
112+
const probeHealth = vi.fn(async () => true);
113+
114+
await expect(
115+
testing.runGatewayLoopWithSupervisedLockRecovery({
116+
startLoop,
117+
supervisor: "systemd",
118+
port: 18789,
119+
healthHost: "127.0.0.1",
120+
log: createLogger(),
121+
probeHealth,
122+
}),
123+
).rejects.toBe(err);
124+
125+
expect(startLoop).toHaveBeenCalledTimes(1);
126+
expect(probeHealth).not.toHaveBeenCalled();
127+
});
128+
105129
it("bounds supervised retries when the existing gateway stays unhealthy", async () => {
106130
let now = 0;
107131
const startLoop = vi.fn(async () => {

‎src/commands/agent-via-gateway.test.ts‎

Lines changed: 105 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
hasExecutionIdentityAdmissionSink,
1212
} from "../audit/execution-identity-admission.js";
1313
import type { OpenClawConfig } from "../config/config.js";
14+
import { acquireGatewayLock, type GatewayLockOptions } from "../infra/gateway-lock.js";
1415
import { loggingState } from "../logging/state.js";
1516
import type { RuntimeEnv } from "../runtime.js";
1617
import { AGENT_HARNESS_SESSION_KEY_RESERVED_MESSAGE } from "../sessions/agent-harness-session-key.js";
@@ -121,6 +122,23 @@ function mockLocalAgentReply(text = "local") {
121122
});
122123
}
123124

125+
function createLocalGatewayLockOptions(
126+
stateDir: string,
127+
overrides: Partial<GatewayLockOptions> = {},
128+
): GatewayLockOptions {
129+
return {
130+
allowInTests: true,
131+
env: {
132+
...process.env,
133+
OPENCLAW_CONFIG_PATH: path.join(stateDir, "openclaw.json"),
134+
OPENCLAW_STATE_DIR: stateDir,
135+
},
136+
lockDir: path.join(stateDir, "gateway-locks"),
137+
timeoutMs: 100,
138+
...overrides,
139+
};
140+
}
141+
124142
function requireFirstCallArg(mock: { mock: { calls: unknown[][] } }, label: string): unknown {
125143
const [call] = mock.mock.calls;
126144
if (!call) {
@@ -464,6 +482,81 @@ describe("agentCliCommand", () => {
464482
});
465483
});
466484

485+
it("refuses --local before embedded startup when a live Gateway owns the state directory", async () => {
486+
await withTempStore(async ({ dir }) => {
487+
const lockOptions = createLocalGatewayLockOptions(dir, {
488+
readProcessStartTime: () => 123_456,
489+
});
490+
const gatewayLock = await acquireGatewayLock({
491+
...lockOptions,
492+
port: 28789,
493+
});
494+
expect(gatewayLock).not.toBeNull();
495+
if (!gatewayLock) {
496+
throw new Error("Expected live Gateway fixture lock");
497+
}
498+
499+
try {
500+
await expect(
501+
agentCliCommand({ message: "hi", to: "+1555", local: true, json: true }, jsonRuntime, {
502+
localGatewayLockOptions: lockOptions,
503+
}),
504+
).rejects.toThrow(
505+
`A Gateway is running for this state directory (pid ${process.pid}, port 28789). Run without --local to use it, or stop the Gateway first (openclaw gateway stop).`,
506+
);
507+
expect(agentCommand).not.toHaveBeenCalled();
508+
expect(startOneShotDiagnosticsExporters).not.toHaveBeenCalled();
509+
expect(jsonRuntime.writeJson).not.toHaveBeenCalled();
510+
} finally {
511+
await gatewayLock.release();
512+
}
513+
});
514+
});
515+
516+
it("holds one agent-embedded state lock for the run and rejects a concurrent --local run", async () => {
517+
await withTempStore(async ({ dir }) => {
518+
const lockOptions = createLocalGatewayLockOptions(dir);
519+
let finishFirstRun: ((value: Awaited<ReturnType<typeof AgentCommand>>) => void) | undefined;
520+
agentCommand.mockImplementationOnce(
521+
async () =>
522+
await new Promise<Awaited<ReturnType<typeof AgentCommand>>>((resolve) => {
523+
finishFirstRun = resolve;
524+
}),
525+
);
526+
527+
const firstRun = agentCliCommand({ message: "first", to: "+1555", local: true }, runtime, {
528+
localGatewayLockOptions: lockOptions,
529+
});
530+
await waitForAgentCommandCall();
531+
532+
const stateLockPath = path.join(lockOptions.lockDir!, "gateway.state.lock");
533+
const payload = JSON.parse(fs.readFileSync(stateLockPath, "utf8")) as {
534+
pid?: number;
535+
role?: string;
536+
};
537+
expect(payload).toMatchObject({ pid: process.pid, role: "agent-embedded" });
538+
539+
await expect(
540+
agentCliCommand({ message: "second", to: "+1555", local: true }, runtime, {
541+
localGatewayLockOptions: { ...lockOptions, pollIntervalMs: 2, timeoutMs: 15 },
542+
}),
543+
).rejects.toThrow(
544+
`another openclaw agent --local run is active (pid ${process.pid}); lock timeout after 15ms`,
545+
);
546+
expect(agentCommand).toHaveBeenCalledTimes(1);
547+
548+
if (!finishFirstRun) {
549+
throw new Error("Expected first embedded run to start");
550+
}
551+
finishFirstRun({
552+
payloads: [{ text: "done" }],
553+
meta: { durationMs: 1 },
554+
} as Awaited<ReturnType<typeof AgentCommand>>);
555+
await firstRun;
556+
expect(fs.existsSync(stateLockPath)).toBe(false);
557+
});
558+
});
559+
467560
it("rejects inline and file messages together", async () => {
468561
await expect(
469562
agentCliCommand(
@@ -1537,9 +1630,13 @@ describe("agentCliCommand", () => {
15371630
});
15381631
});
15391632

1540-
it("passes SIGTERM abort signals into local agent runs", async () => {
1541-
await withTempStore(async () => {
1633+
it.each([
1634+
["SIGTERM", 143],
1635+
["SIGINT", 130],
1636+
] as const)("releases the local state lock after %s aborts the run", async (signal, exitCode) => {
1637+
await withTempStore(async ({ dir }) => {
15421638
const signals = createSignalProcess();
1639+
const lockOptions = createLocalGatewayLockOptions(dir);
15431640
agentCommand.mockImplementationOnce(async (opts: { abortSignal?: AbortSignal }) => {
15441641
expect(opts.abortSignal).toBeInstanceOf(AbortSignal);
15451642
return await new Promise((_, reject) => {
@@ -1557,13 +1654,17 @@ describe("agentCliCommand", () => {
15571654

15581655
const run = agentCliCommand({ message: "hi", to: "+1555", local: true }, runtime, {
15591656
process: signals.processLike,
1657+
localGatewayLockOptions: lockOptions,
15601658
});
15611659
await waitForAgentCommandCall();
1562-
signals.emit("SIGTERM");
1660+
const stateLockPath = path.join(lockOptions.lockDir!, "gateway.state.lock");
1661+
expect(fs.existsSync(stateLockPath)).toBe(true);
1662+
signals.emit(signal);
15631663

15641664
await run;
1665+
expect(fs.existsSync(stateLockPath)).toBe(false);
15651666
expect(callGateway).not.toHaveBeenCalled();
1566-
expect(runtime.exit).toHaveBeenCalledWith(143);
1667+
expect(runtime.exit).toHaveBeenCalledWith(exitCode);
15671668
expect(signals.listenerCount("SIGTERM")).toBe(0);
15681669
expect(signals.listenerCount("SIGINT")).toBe(0);
15691670
});

‎src/commands/agent-via-gateway.ts‎

Lines changed: 64 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import { isGatewaySecretRefUnavailableError } from "../gateway/credentials.js";
3030
import { ADMIN_SCOPE } from "../gateway/operator-scopes.js";
3131
import { createAbortError } from "../infra/abort-signal.js";
3232
import { readFileDescriptorBounded } from "../infra/boundary-file-read.js";
33+
import type { GatewayLockIdentity, GatewayLockOptions } from "../infra/gateway-lock.js";
3334
import { parseStrictNonNegativeInteger } from "../infra/parse-finite-number.js";
3435
import { routeLogsToStderr } from "../logging/console.js";
3536
import {
@@ -103,6 +104,7 @@ type AgentCliProcessLike = {
103104
};
104105
type AgentCliDeps = CliDeps & {
105106
process?: AgentCliProcessLike;
107+
localGatewayLockOptions?: GatewayLockOptions;
106108
};
107109
type AgentGatewayCallIdentity = Pick<
108110
Parameters<typeof callGateway>[0],
@@ -136,6 +138,9 @@ const agentSessionModuleCache = createLazyPromiseLoader(() => agentSessionModule
136138
const runtimeConfigModuleLoader = createLazyPromiseLoader(() => import("../config/io.js"), {
137139
cacheRejections: true,
138140
});
141+
const gatewayLockModuleLoader = createLazyPromiseLoader(() => import("../infra/gateway-lock.js"), {
142+
cacheRejections: true,
143+
});
139144
const replyPayloadModuleLoader = createLazyPromiseLoader(
140145
() => import("openclaw/plugin-sdk/reply-payload"),
141146
{ cacheRejections: true },
@@ -213,6 +218,42 @@ async function loadRuntimeConfig(): Promise<OpenClawConfig> {
213218
return getRuntimeConfig();
214219
}
215220

221+
function formatActiveGatewayLocalRefusal(identity: GatewayLockIdentity): string {
222+
return `A Gateway is running for this state directory (pid ${identity.pid}, port ${identity.port}). Run without --local to use it, or stop the Gateway first (${formatCliCommand("openclaw gateway stop")}).`;
223+
}
224+
225+
async function acquireEmbeddedAgentStateLock(
226+
options: GatewayLockOptions | undefined,
227+
signal: AbortSignal,
228+
) {
229+
const { acquireGatewayLock, GatewayLockError, readActiveGatewayLockIdentity } =
230+
await gatewayLockModuleLoader.load();
231+
const env = options?.env ?? process.env;
232+
if (options?.allowInTests !== true && (env.VITEST || env.NODE_ENV === "test")) {
233+
return null;
234+
}
235+
const activeGateway = await readActiveGatewayLockIdentity(options);
236+
if (activeGateway) {
237+
throw new GatewayLockError(formatActiveGatewayLocalRefusal(activeGateway));
238+
}
239+
try {
240+
return await acquireGatewayLock({
241+
...options,
242+
role: "agent-embedded",
243+
sleep: options?.sleep ?? (async (ms) => await delayMs(ms, signal)),
244+
});
245+
} catch (error) {
246+
if (!(error instanceof GatewayLockError)) {
247+
throw error;
248+
}
249+
const racedGateway = await readActiveGatewayLockIdentity(options);
250+
if (racedGateway) {
251+
throw new GatewayLockError(formatActiveGatewayLocalRefusal(racedGateway), error);
252+
}
253+
throw error;
254+
}
255+
}
256+
216257
const loadReplyPayloadModule = replyPayloadModuleLoader.load;
217258

218259
/** Test-only hooks for resetting lazy imports and shortening retry timing. */
@@ -222,6 +263,7 @@ export const agentViaGatewayTesting = {
222263
localAuditModuleLoader.clear();
223264
agentSessionModuleCache.clear();
224265
runtimeConfigModuleLoader.clear();
266+
gatewayLockModuleLoader.clear();
225267
replyPayloadModuleLoader.clear();
226268
agentSessionModuleLoader = defaultAgentSessionModuleLoader;
227269
},
@@ -989,20 +1031,29 @@ export async function agentCliCommand(
9891031
const signalBridge = createAgentCliSignalBridge(resolveAgentCliProcessLike(deps));
9901032
try {
9911033
if (dispatchOpts.local === true) {
992-
const result = await runEmbeddedAgentCommand(
993-
{
994-
...gatewayDispatchOpts,
995-
agentId: gatewayDispatchOpts.agent,
996-
replyAccountId: gatewayDispatchOpts.replyAccount,
997-
cleanupBundleMcpOnRunEnd: true,
998-
cleanupCliLiveSessionOnRunEnd: true,
999-
oneShotCliRun: true,
1000-
abortSignal: signalBridge.signal,
1001-
},
1002-
runtime,
1003-
deps,
1004-
{ suppressStdoutDiagnosticLogs: dispatchOpts.json === true },
1034+
const stateLock = await acquireEmbeddedAgentStateLock(
1035+
deps?.localGatewayLockOptions,
1036+
signalBridge.signal,
10051037
);
1038+
let result: Awaited<ReturnType<typeof runEmbeddedAgentCommand>>;
1039+
try {
1040+
result = await runEmbeddedAgentCommand(
1041+
{
1042+
...gatewayDispatchOpts,
1043+
agentId: gatewayDispatchOpts.agent,
1044+
replyAccountId: gatewayDispatchOpts.replyAccount,
1045+
cleanupBundleMcpOnRunEnd: true,
1046+
cleanupCliLiveSessionOnRunEnd: true,
1047+
oneShotCliRun: true,
1048+
abortSignal: signalBridge.signal,
1049+
},
1050+
runtime,
1051+
deps,
1052+
{ suppressStdoutDiagnosticLogs: dispatchOpts.json === true },
1053+
);
1054+
} finally {
1055+
await stateLock?.release();
1056+
}
10061057
return returnAfterSignalExit(result, signalBridge.getReceivedSignal(), runtime);
10071058
}
10081059

‎src/infra/gateway-lock.roles.test.ts‎

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,12 @@ import path from "node:path";
44
import { setTimeout as nativeSleep } from "node:timers/promises";
55
import { afterAll, beforeAll, describe, expect, it } from "vitest";
66
import { createSuiteTempRootTracker } from "../test-helpers/temp-dir.js";
7-
import { acquireGatewayLock, GatewayLockError, readActiveGatewayLockPort } from "./gateway-lock.js";
7+
import {
8+
acquireGatewayLock,
9+
GatewayLockError,
10+
readActiveGatewayLockIdentity,
11+
readActiveGatewayLockPort,
12+
} from "./gateway-lock.js";
813

914
const fixtureRootTracker = createSuiteTempRootTracker({
1015
prefix: "openclaw-gateway-lock-workshop-",
@@ -118,4 +123,61 @@ describe("Gateway lock roles", () => {
118123
await lock.release();
119124
}
120125
});
126+
127+
it("keeps agent-embedded ownership distinct from a running Gateway", async () => {
128+
const stateDir = await fixtureRootTracker.make("agent-embedded-role");
129+
const lockDir = path.join(fixtureRoot, "__locks");
130+
const configPath = path.join(stateDir, "openclaw.json");
131+
await fs.writeFile(configPath, "{}", "utf8");
132+
const env = {
133+
...process.env,
134+
OPENCLAW_CONFIG_PATH: configPath,
135+
OPENCLAW_STATE_DIR: stateDir,
136+
};
137+
const readProcessCmdline = () => ["openclaw", "agent", "--local", "--message", "hello"];
138+
const lock = await acquireGatewayLock({
139+
allowInTests: true,
140+
env,
141+
lockDir,
142+
platform: "darwin",
143+
port: 28789,
144+
readProcessCmdline,
145+
readProcessStartTime: () => null,
146+
role: "agent-embedded",
147+
timeoutMs: 30,
148+
});
149+
expect(lock).not.toBeNull();
150+
if (!lock) {
151+
throw new Error("Expected embedded agent Gateway lock");
152+
}
153+
154+
try {
155+
await expect(
156+
readActiveGatewayLockIdentity({
157+
env,
158+
lockDir,
159+
platform: "darwin",
160+
readProcessCmdline,
161+
readProcessStartTime: () => null,
162+
}),
163+
).resolves.toBeUndefined();
164+
await expect(
165+
acquireGatewayLock({
166+
allowInTests: true,
167+
env,
168+
lockDir,
169+
platform: "darwin",
170+
pollIntervalMs: 2,
171+
readProcessCmdline,
172+
readProcessStartTime: () => null,
173+
sleep: nativeSleep,
174+
timeoutMs: 15,
175+
}),
176+
).rejects.toThrow(
177+
`another openclaw agent --local run is active (pid ${process.pid}); lock timeout after 15ms`,
178+
);
179+
} finally {
180+
await lock.release();
181+
}
182+
});
121183
});

0 commit comments

Comments
 (0)