Skip to content

Commit e4100ac

Browse files
fix(exec): select capable nodes and report the execution target (#131767)
* fix(exec): require target for multiple executable nodes * test(exec): align node target reporting assertions --------- Co-authored-by: Peter Steinberger <[email protected]> Co-authored-by: vyctorbrzezowski <[email protected]>
1 parent d154a42 commit e4100ac

13 files changed

Lines changed: 486 additions & 62 deletions

‎docs/nodes/index.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -977,7 +977,9 @@ Notes:
977977

978978
## Exec node binding
979979

980-
When multiple nodes are available, you can bind exec to a specific node. This sets the default node for `exec host=node` (and can be overridden per agent).
980+
With no node target set, `exec host=node` selects the sole paired, connected node that supports `system.run`. Other paired devices do not make the selection ambiguous. If multiple executable nodes are connected, choose a target per call or bind exec to a specific node; the active Canvas target does not select the exec host. A bound or explicit target that is offline or cannot execute commands is rejected rather than redirected to another node.
981+
982+
A binding sets the default node for `exec host=node` and can be overridden per agent.
981983

982984
Global default:
983985

@@ -992,7 +994,7 @@ openclaw config get agents.entries
992994
openclaw config set 'agents.entries.main.tools.exec.node' "node-id-or-name"
993995
```
994996

995-
Unset to allow any node:
997+
Unset the binding to use the sole eligible node, or choose a target per call when multiple eligible nodes are connected:
996998

997999
```bash
9981000
openclaw config unset tools.exec.node

‎docs/plugins/codex-harness.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,9 @@ cleanup of commands that deliberately detach from that ownership.
6969
With the default `tools.exec.host: "auto"` and no active OpenClaw sandbox,
7070
Codex also receives `node_exec` for commands on paired nodes. Native shell
7171
remains on the Codex app-server host and workspace
72-
(Gateway-local for the default stdio deployment); `node_exec` selects a node by
73-
name or id, keeps OpenClaw's node approval policy in force, and waits for the
72+
(Gateway-local for the default stdio deployment); `node_exec` selects the sole
73+
connected node that supports `system.run`, or requires a name or id when several
74+
are eligible. It keeps OpenClaw's node approval policy in force and waits for the
7475
remote command to finish. Remote-node background follow-up is not available. If
7576
a finite runtime allowlist disables native Code Mode and leaves the turn without
7677
an execution environment, OpenClaw keeps its policy-filtered `exec` and

‎docs/tools/exec.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ Notes:
6565
- With no extra config, `host=auto` still "just works": no sandbox means it resolves to `gateway`; a live sandbox means it stays in the sandbox.
6666
- `elevated` escapes the sandbox onto the configured host path: `gateway` by default, or `node` when `tools.exec.host=node` (or the session default is `host=node`). It is only available when elevated access is enabled for the current session/provider.
6767
- `gateway`/`node` approvals are controlled by the host approvals file.
68-
- `node` requires a paired node (companion app or headless node host). If multiple nodes are available, set `exec.node` or `tools.exec.node` to select one.
68+
- `node` requires a paired, connected node that supports `system.run` (companion app or headless node host). With no target set, exec selects the sole eligible node. If multiple eligible nodes are connected, set `exec.node`, `tools.exec.node`, or `/exec node=...` to select one; it never uses the active Canvas target. An explicit or bound target must itself be connected and executable. Completed results identify the selected node alongside command output.
6969
- `exec host=node` is the only shell-execution path for nodes; the legacy `nodes.run` wrapper has been removed.
7070
- On non-Windows hosts, exec uses `SHELL` when set; if `SHELL` is `fish`, it prefers `bash` (or `sh`) from `PATH` to avoid fish-incompatible bashisms, then falls back to `SHELL` if neither exists.
7171
- On Windows hosts, exec prefers PowerShell 7 (`pwsh`) discovery (Program Files, ProgramW6432, then PATH), then falls back to Windows PowerShell 5.1.

‎extensions/codex/src/app-server/dynamic-tool-build.test.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1827,7 +1827,9 @@ describe("Codex app-server dynamic tool build", () => {
18271827
{ type: "inputText", text: "Unknown OpenClaw tool: node_process" },
18281828
]);
18291829
const nodeExec = tools.find((tool) => tool.name === "node_exec");
1830-
expect(nodeExec?.description).toContain("Select the node by name or id");
1830+
expect(nodeExec?.description).toContain(
1831+
"The sole connected node that can execute commands is selected automatically; select by name or id when several can.",
1832+
);
18311833
expect(nodeExec?.parameters).toMatchObject({
18321834
type: "object",
18331835
properties: {

‎extensions/codex/src/app-server/shell-dynamic-tools.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ export function createNodeExecAliasDynamicTool(
5656
name: CODEX_NODE_EXEC_DYNAMIC_TOOL_NAME,
5757
description: pinnedNode
5858
? "Run a shell command to completion on the OpenClaw configured remote node for this session. This tool always uses OpenClaw host=node internally and follows the existing node exec approval and allowlist policy. Remote-node background follow-up is unavailable. Use Codex's native shell for local app-server work."
59-
: "Run a shell command to completion on an OpenClaw remote node. Select the node by name or id when multiple nodes are available. This tool always uses OpenClaw host=node internally and follows the existing node exec approval and allowlist policy. Remote-node background follow-up is unavailable. Use Codex's native shell for local app-server work.",
59+
: "Run a shell command to completion on an OpenClaw remote node. The sole connected node that can execute commands is selected automatically; select by name or id when several can. This tool always uses OpenClaw host=node internally and follows the existing node exec approval and allowlist policy. Remote-node background follow-up is unavailable. Use Codex's native shell for local app-server work.",
6060
execute,
6161
};
6262
}

‎src/agents/bash-tools.exec-host-node-phases.test.ts‎

Lines changed: 140 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@ import {
33
formatNodeInvokeFailureFollowup,
44
invokeNodeSystemRun,
55
} from "./bash-tools.exec-host-node-failure.js";
6-
import { dispatchNodeSystemRun } from "./bash-tools.exec-host-node-phases.js";
6+
import {
7+
dispatchNodeSystemRun,
8+
resolveNodeExecutionTarget,
9+
} from "./bash-tools.exec-host-node-phases.js";
710

811
const callGatewayToolMock = vi.hoisted(() => vi.fn());
912

@@ -115,6 +118,127 @@ describe("invokeNodeSystemRun failure classification", () => {
115118
});
116119
});
117120

121+
describe("node execution target resolution", () => {
122+
beforeEach(() => {
123+
callGatewayToolMock.mockReset();
124+
});
125+
126+
it("requires an explicit target when multiple connected nodes support system.run", async () => {
127+
callGatewayToolMock.mockResolvedValueOnce({
128+
nodes: [
129+
{
130+
nodeId: "mac-a",
131+
displayName: "Desk Mac",
132+
platform: "macos",
133+
caps: ["canvas"],
134+
commands: ["system.run"],
135+
connected: true,
136+
connectedAtMs: 1_000,
137+
active: true,
138+
},
139+
{
140+
nodeId: "mac-b",
141+
displayName: "Travel Mac",
142+
platform: "macos",
143+
caps: ["canvas"],
144+
commands: ["system.run"],
145+
connected: true,
146+
connectedAtMs: 2_000,
147+
},
148+
],
149+
});
150+
151+
await expect(resolveNodeExecutionTarget(createDirectNodeRun().request)).rejects.toThrow(
152+
/multiple.*mac-a.*mac-b/i,
153+
);
154+
expect(callGatewayToolMock).toHaveBeenCalledTimes(1);
155+
expect(callGatewayToolMock).toHaveBeenCalledWith("node.list", {}, {}, { signal: undefined });
156+
});
157+
158+
it.each([
159+
{ name: "alone", siblings: [] },
160+
{
161+
name: "beside a connected non-executor",
162+
siblings: [
163+
{
164+
nodeId: "canvas-only",
165+
caps: ["canvas"],
166+
commands: ["canvas.present"],
167+
connected: true,
168+
},
169+
],
170+
},
171+
{
172+
name: "beside an offline non-executor",
173+
siblings: [
174+
{
175+
nodeId: "canvas-only",
176+
caps: ["canvas"],
177+
commands: ["canvas.present"],
178+
connected: false,
179+
},
180+
],
181+
},
182+
])("selects the sole headless executor $name", async ({ siblings }) => {
183+
callGatewayToolMock.mockResolvedValueOnce({
184+
nodes: [
185+
...siblings,
186+
{
187+
nodeId: "exec-node",
188+
platform: "linux",
189+
caps: ["system"],
190+
commands: ["system.run"],
191+
connected: true,
192+
},
193+
],
194+
});
195+
196+
await expect(resolveNodeExecutionTarget(createDirectNodeRun().request)).resolves.toMatchObject({
197+
nodeId: "exec-node",
198+
});
199+
});
200+
201+
it("honors an explicit executable node among multiple candidates", async () => {
202+
callGatewayToolMock.mockResolvedValueOnce({
203+
nodes: [
204+
{ nodeId: "node-a", commands: ["system.run"], connected: true },
205+
{ nodeId: "node-b", commands: ["system.run"], connected: true },
206+
],
207+
});
208+
209+
await expect(
210+
resolveNodeExecutionTarget({ ...createDirectNodeRun().request, requestedNode: "node-a" }),
211+
).resolves.toMatchObject({ nodeId: "node-a" });
212+
});
213+
214+
it.each(["build-worker", "node-shared-"])(
215+
"rejects an ambiguous configured binding %s before filtering executable nodes",
216+
async (boundNode) => {
217+
callGatewayToolMock.mockResolvedValueOnce({
218+
nodes: [
219+
{
220+
nodeId: "node-shared-exec",
221+
displayName: "build-worker",
222+
commands: ["system.run"],
223+
connected: true,
224+
},
225+
{
226+
nodeId: "node-shared-canvas",
227+
displayName: "build-worker",
228+
commands: ["canvas.present"],
229+
connected: true,
230+
},
231+
],
232+
});
233+
234+
await expect(
235+
resolveNodeExecutionTarget({ ...createDirectNodeRun().request, boundNode }),
236+
).rejects.toThrow(/ambiguous node/);
237+
expect(callGatewayToolMock).toHaveBeenCalledTimes(1);
238+
},
239+
);
240+
});
241+
118242
type DirectNodeRun = Parameters<typeof dispatchNodeSystemRun>[0];
119243

120244
function createDirectNodeRun(signal?: AbortSignal): DirectNodeRun {
@@ -206,8 +330,20 @@ describe("direct node run", () => {
206330
const result = await dispatchNodeSystemRun(createDirectNodeRun());
207331
const visibleText = result.content[0]?.type === "text" ? result.content[0].text : "";
208332

209-
expect(visibleText).toBe(`${stdout}\n${stderr}\n${errorText}\n(Command exited with code 1)`);
210-
expect(result.details).toMatchObject({ aggregated: visibleText });
333+
const output = `${stdout}\n${stderr}\n${errorText}\n(Command exited with code 1)`;
334+
expect(visibleText).toBe(`Node: node-1\n${output}`);
335+
expect(result.details).toMatchObject({ aggregated: output, nodeId: "node-1" });
336+
});
337+
338+
it("identifies the node in the successful result the model reads", async () => {
339+
const result = await dispatchNodeSystemRun(createDirectNodeRun());
340+
341+
expect(result.content).toEqual([{ type: "text", text: "Node: node-1\nok" }]);
342+
expect(result.details).toMatchObject({
343+
status: "completed",
344+
aggregated: "ok",
345+
nodeId: "node-1",
346+
});
211347
});
212348

213349
it("renders a nonzero exit code in the model-visible text", async () => {
@@ -233,6 +369,7 @@ describe("direct node run", () => {
233369
const visibleText = result.content[0]?.type === "text" ? result.content[0].text : "";
234370

235371
expect(visibleText).toContain("Command timed out.");
372+
expect(visibleText).toContain("Node: node-1");
236373
expect(result.details).toMatchObject({ status: "failed", timedOut: true });
237374
});
238375

‎src/agents/bash-tools.exec-host-node-phases.ts‎

Lines changed: 37 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ import {
3737
extractShellCommandFromArgv,
3838
resolveSystemRunCommandRequest,
3939
} from "../infra/system-run-command.js";
40+
import { resolveEligibleNodeFromList } from "../shared/node-resolve.js";
4041
import { addSafeTimeoutDelayGraceMs } from "../utils/timer-delay.js";
4142
import {
4243
formatNodeInvokeFailureToolResult,
@@ -230,6 +231,7 @@ function formatNodeRunToolResult(params: {
230231
raw: unknown;
231232
startedAt: number;
232233
cwd: string | undefined;
234+
nodeId: string;
233235
warnings?: string[];
234236
}): AgentToolResult<ExecToolDetails> {
235237
const payload =
@@ -253,20 +255,22 @@ function formatNodeRunToolResult(params: {
253255
: "";
254256
const output = [stdout, stderr, errorText, outcomeNote].filter(Boolean).join("\n");
255257
return {
258+
// Tool details are UI metadata; the model needs the execution target in content.
256259
content: [
257260
{
258261
type: "text",
259-
text: renderExecUpdateText({
262+
text: `Node: ${params.nodeId}\n${renderExecUpdateText({
260263
tailText: output,
261264
warnings: params.warnings ?? [],
262-
}),
265+
})}`,
263266
},
264267
],
265268
details: {
266269
status: success ? "completed" : "failed",
267270
exitCode,
268271
durationMs: Date.now() - params.startedAt,
269272
aggregated: output,
273+
nodeId: params.nodeId,
270274
...(timedOut ? { timedOut: true } : {}),
271275
cwd: params.cwd,
272276
} satisfies ExecToolDetails,
@@ -285,15 +289,9 @@ export async function resolveNodeExecutionTarget(
285289
}
286290
// Canonicalize boundNode and requestedNode (which may be display names, IPs,
287291
// or partial ID prefixes) to full device IDs before comparing.
288-
let resolvedBoundNodeId: string | undefined;
289-
if (params.boundNode) {
290-
try {
291-
resolvedBoundNodeId = resolveNodeIdFromList(nodes, params.boundNode);
292-
} catch {
293-
// boundNode comes from config; if it cannot be resolved, fall through
294-
// to the existing nodeQuery resolution which produces a clearer error.
295-
}
296-
}
292+
const resolvedBoundNodeId = params.boundNode
293+
? resolveNodeIdFromList(nodes, params.boundNode)
294+
: undefined;
297295
let resolvedRequestedNodeId: string | undefined;
298296
if (params.requestedNode) {
299297
try {
@@ -305,53 +303,45 @@ export async function resolveNodeExecutionTarget(
305303
);
306304
}
307305
}
308-
const canonicalBound = resolvedBoundNodeId ?? params.boundNode;
309-
if (canonicalBound && resolvedRequestedNodeId && canonicalBound !== resolvedRequestedNodeId) {
310-
throw new Error(
311-
`exec node not allowed (bound to ${canonicalBound}, requested resolved to ${resolvedRequestedNodeId})`,
312-
);
313-
}
314-
// Prefer resolved IDs; fall back to raw boundNode so stale/unresolvable
315-
// values still reach resolveNodeIdFromList (which produces a clear
316-
// "unknown node" error) instead of silently picking a default node.
317-
const nodeQuery = resolvedBoundNodeId || resolvedRequestedNodeId || params.boundNode;
318-
let nodeId: string;
319-
try {
320-
nodeId = resolveNodeIdFromList(nodes, nodeQuery, !nodeQuery);
321-
} catch (err) {
322-
if (!nodeQuery && String(err).includes("node required")) {
323-
throw new Error(
324-
"exec host=node requires a node id when multiple nodes are available (set tools.exec.node or exec.node).",
325-
{ cause: err },
326-
);
327-
}
328-
throw err;
329-
}
330-
const nodeInfo = nodes.find((entry) => entry.nodeId === nodeId);
331-
if (nodeInfo?.connected === false) {
332-
throw new Error(
333-
`exec host=node requires a connected node (${nodeId} is currently disconnected). Start or reconnect the companion app or node host, or select a connected node.`,
334-
);
335-
}
336-
const declaredCommands = Array.isArray(nodeInfo?.commands) ? nodeInfo.commands : [];
337-
const supportsSystemRun = declaredCommands.includes("system.run");
338-
if (!supportsSystemRun) {
306+
if (
307+
resolvedBoundNodeId &&
308+
resolvedRequestedNodeId &&
309+
resolvedBoundNodeId !== resolvedRequestedNodeId
310+
) {
339311
throw new Error(
340-
"exec host=node requires a node that supports system.run (companion app or node host).",
312+
`exec node not allowed (bound to ${resolvedBoundNodeId}, requested resolved to ${resolvedRequestedNodeId})`,
341313
);
342314
}
315+
const nodeInfo = resolveEligibleNodeFromList(
316+
nodes,
317+
resolvedBoundNodeId ?? resolvedRequestedNodeId,
318+
(node) => node.connected === true && node.commands?.includes("system.run") === true,
319+
{
320+
ineligibleExact: (query, eligibleIds) =>
321+
`exec host=node requires a connected node that supports system.run (${query} is not eligible; eligible node ids: ${eligibleIds}).`,
322+
nameResolveFailed: (reason, eligibleIds) =>
323+
`${reason} (eligible connected system.run node ids: ${eligibleIds})`,
324+
noneEligible: () =>
325+
"exec host=node requires a connected node that supports system.run (none available). Start or reconnect the companion app or node host.",
326+
multipleEligible: (eligible) =>
327+
`exec host=node requires a node when multiple executable nodes are connected: ${eligible
328+
.map((node) => (node.displayName ? `${node.nodeId} (${node.displayName})` : node.nodeId))
329+
.join(", ")}. Set exec.node, tools.exec.node, or /exec node=...`,
330+
},
331+
);
332+
const nodeId = nodeInfo.nodeId;
343333

344334
const runTimeoutSec = resolveNodeRunTimeoutSec(params.timeoutSec, params.defaultTimeoutSec);
345335
const invokeDeadlineMs = resolveNodeInvokeDeadlineMs(runTimeoutSec, params.defaultTimeoutSec);
346336
return {
347337
nodeId,
348-
platform: nodeInfo?.platform,
349-
argv: buildNodeShellCommand(params.command, nodeInfo?.platform),
338+
platform: nodeInfo.platform,
339+
argv: buildNodeShellCommand(params.command, nodeInfo.platform),
350340
env: params.requestedEnv ? { ...params.requestedEnv } : undefined,
351341
invokeDeadlineMs,
352342
invokeWaitMs: resolveNodeInvokeWaitMs(invokeDeadlineMs),
353343
runTimeoutSec,
354-
supportsSystemRunPrepare: declaredCommands.includes("system.run.prepare"),
344+
supportsSystemRunPrepare: nodeInfo.commands?.includes("system.run.prepare") === true,
355345
};
356346
}
357347

@@ -441,6 +431,7 @@ export async function dispatchNodeSystemRun(params: {
441431
raw: result.raw,
442432
startedAt,
443433
cwd: params.request.workdir,
434+
nodeId: params.target.nodeId,
444435
warnings: [...params.request.warnings, ...(params.request.foregroundWarnings ?? [])],
445436
});
446437
}

‎src/agents/bash-tools.exec-host-node.cancellation.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ describe("node-host dispatch cancellation", () => {
218218
);
219219

220220
expect(result.details).toMatchObject({ status: "completed", exitCode: 0, aggregated: "ok" });
221-
expect(result.content).toEqual([{ type: "text", text: "ok" }]);
221+
expect(result.content).toEqual([{ type: "text", text: "Node: node-1\nok" }]);
222222
expect(callGatewayToolMock).toHaveBeenCalledWith(
223223
"node.invoke",
224224
{ timeoutMs: 40_000 },
@@ -242,7 +242,7 @@ describe("node-host dispatch cancellation", () => {
242242
);
243243

244244
expect(result.details).toMatchObject({ status: "completed", exitCode: 0, aggregated: "ok" });
245-
expect(result.content).toEqual([{ type: "text", text: "ok" }]);
245+
expect(result.content).toEqual([{ type: "text", text: "Node: node-1\nok" }]);
246246
expect(callGatewayToolMock).toHaveBeenCalledWith(
247247
"node.invoke",
248248
{ timeoutMs: 40_000 },

0 commit comments

Comments
 (0)