Skip to content

Commit 83d279a

Browse files
authored
fix(cli): honor channel resolve agent ownership (#125109)
* fix(cli): honor channel resolve agent ownership Forward explicit channel owners through command-time secret collection and later workspace/channel resolution, preventing AGENT_SELECTION_REQUIRED in multi-agent configurations. * fix(cli): narrow explicit agent option value Use runtime string narrowing for the Commander option so agent-owner forwarding remains assertion-free and satisfies the assertion-safety ratchet. * docs(cli): document channel resolve agent owner
1 parent 7b18510 commit 83d279a

14 files changed

Lines changed: 159 additions & 16 deletions

‎docs/cli/channels.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ it does not guess one agent workspace.
4040

4141
- `channels status`: `--channel <name>`, `--probe`, `--timeout <ms>` (default `10000`), `--json`
4242
- `channels capabilities`: `--channel <name>`, `--account <id>` (requires `--channel`), `--target <dest>` (requires `--channel`), `--timeout <ms>` (default `10000`, capped at `30000`), `--json`
43-
- `channels resolve <entries...>`: `--channel <name>`, `--account <id>`, `--kind <auto|user|group>` (default `auto`), `--json`
43+
- `channels resolve <entries...>`: `--channel <name>`, `--account <id>`, `--agent <id>`, `--kind <auto|user|group|channel>` (default `auto`), `--json`
4444
- `channels logs`: `--channel <name|all>` (default `all`), `--lines <n>` (default `200`), `--json`
4545

4646
`channels status --probe` is the live path: on a reachable gateway it runs per-account
@@ -202,11 +202,14 @@ Resolve channel/user names to IDs using the provider directory:
202202
openclaw channels resolve --channel slack "#general" "@jane"
203203
openclaw channels resolve --channel discord "My Server/#support" "@someone"
204204
openclaw channels resolve --channel matrix "Project Room"
205+
openclaw channels --agent ops resolve --channel slack "#general"
206+
openclaw channels resolve --agent ops --channel slack "#general"
205207
```
206208

207209
Notes:
208210

209-
- Use `--kind user|group|auto` to force the target type.
211+
- In multi-agent configurations, use `--agent <id>` in either parent or leaf position to select the agent-owned workspace and channel plugin context.
212+
- Use `--kind user|group|channel|auto` to force the target type.
210213
- Resolution prefers active matches when multiple entries share the same name.
211214
- `channels resolve` is read-only. If a selected account is configured via SecretRef but that credential is unavailable in the current command path, the command returns degraded unresolved results with notes instead of aborting the entire run.
212215
- `channels resolve` does not install channel plugins. Use `channels add --channel <name>` before resolving names for an installable catalog channel.

‎src/cli/channels-cli.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,21 @@ describe("registerChannelsCli", () => {
107107
},
108108
);
109109

110+
it.each([
111+
["parent", ["channels", "--agent", "ops", "resolve", "room"]],
112+
["leaf", ["channels", "resolve", "--agent", "ops", "room"]],
113+
])("forwards the %s --agent option to channel resolution", async (_label, args) => {
114+
const program = new Command().name("openclaw").enablePositionalOptions().exitOverride();
115+
116+
await registerChannelsCli(program, ["node", "openclaw", ...args]);
117+
await program.parseAsync(args, { from: "user" });
118+
119+
expect(channelsResolveCommandMock).toHaveBeenCalledWith(
120+
expect.objectContaining({ agent: "ops", entries: ["room"] }),
121+
runtimeMock,
122+
);
123+
});
124+
110125
it("rejects unsupported resolve target kinds before dispatching", async () => {
111126
const writeErr = vi.fn();
112127
const program = new Command().name("openclaw").exitOverride().configureOutput({ writeErr });

‎src/cli/channels-cli.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import {
1717
type ChannelSetupCliOption,
1818
} from "./channels-cli-add-args.js";
1919
import { runCommandWithRuntime } from "./cli-utils.js";
20-
import { hasExplicitOptions } from "./command-options.js";
20+
import { hasExplicitOptions, inheritOptionFromParent } from "./command-options.js";
2121
import { formatHelpExamples } from "./help-format.js";
2222
import { applyParentDefaultHelpAction } from "./program/parent-default-help.js";
2323
import { normalizeWindowsArgv } from "./windows-argv.js";
@@ -156,6 +156,7 @@ export async function registerChannelsCli(
156156
const channels = program
157157
.command("channels")
158158
.description("Manage connected chat channels and accounts")
159+
.option("--agent <id>", "Agent owner for channel commands that require workspace context")
159160
.addHelpText(
160161
"after",
161162
() =>
@@ -222,17 +223,26 @@ export async function registerChannelsCli(
222223
.argument("<entries...>", "Entries to resolve (names or ids)")
223224
.option("--channel <name>", `Channel (${channelNames})`)
224225
.option("--account <id>", "Account id (accountId)")
226+
.option("--agent <id>", "Agent owner for channel resolution")
225227
.addOption(
226228
new Option("--kind <kind>", "Target kind (auto|user|group|channel)")
227229
.choices(["auto", "user", "group", "channel"])
228230
.default("auto"),
229231
)
230232
.option("--json", "Output JSON", false)
231-
.action(async (entries, opts) => {
233+
.action(async (entries, opts, command) => {
232234
await runChannelsCommand(async () => {
233235
const { channelsResolveCommand } = await loadChannelsCommands();
236+
const agentSource = command.getOptionValueSource("agent");
237+
const agent =
238+
agentSource && agentSource !== "default"
239+
? typeof opts.agent === "string"
240+
? opts.agent
241+
: undefined
242+
: inheritOptionFromParent<string>(command, "agent");
234243
await channelsResolveCommand(
235244
{
245+
agent,
236246
channel: opts.channel as string | undefined,
237247
account: opts.account as string | undefined,
238248
kind: opts.kind as "auto" | "user" | "group" | "channel",

‎src/cli/command-config-resolution.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ describe("resolveCommandConfigWithSecrets", () => {
3535
config,
3636
commandName: "status",
3737
targetIds,
38+
agentId: "ops",
3839
mode: "read_only_status",
3940
runtime,
4041
});
@@ -43,6 +44,7 @@ describe("resolveCommandConfigWithSecrets", () => {
4344
config,
4445
commandName: "status",
4546
targetIds,
47+
agentId: "ops",
4648
mode: "read_only_status",
4749
});
4850
expect(runtime.error).toHaveBeenCalledWith("[secrets] resolved channels.telegram.token");

‎src/cli/command-config-resolution.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ export async function resolveCommandConfigWithSecrets<TConfig extends OpenClawCo
1212
config: TConfig;
1313
commandName: string;
1414
targetIds: Set<string>;
15+
agentId?: string;
1516
mode?: CommandSecretResolutionMode;
1617
allowedPaths?: Set<string>;
1718
forcedActivePaths?: Set<string>;
@@ -30,6 +31,7 @@ export async function resolveCommandConfigWithSecrets<TConfig extends OpenClawCo
3031
config: params.config,
3132
commandName: params.commandName,
3233
targetIds: params.targetIds,
34+
...(params.agentId !== undefined ? { agentId: params.agentId } : {}),
3335
...(params.mode ? { mode: params.mode } : {}),
3436
...(params.allowedPaths ? { allowedPaths: params.allowedPaths } : {}),
3537
...(params.forcedActivePaths ? { forcedActivePaths: params.forcedActivePaths } : {}),

‎src/cli/command-secret-gateway.test.ts‎

Lines changed: 69 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import os from "node:os";
44
import path from "node:path";
55
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
66
import type { OpenClawConfig } from "../config/config.js";
7+
import { collectConfigAssignments as collectRuntimeConfigAssignments } from "../secrets/runtime-config-collectors.js";
78
import { withSecureTestNodeExecPath } from "../secrets/test-node-command.test-support.js";
89
import { withEnvAsync } from "../test-utils/env.js";
910
import {
@@ -166,6 +167,9 @@ describe("resolveCommandSecretRefsViaGateway", () => {
166167
function setSingleSecretTargetDeps(params: {
167168
path: string;
168169
pathSegments: readonly string[];
170+
collectConfigAssignments?: NonNullable<
171+
Parameters<typeof commandSecretGatewayTesting.setDepsForTest>[0]["collectConfigAssignments"]
172+
>;
169173
resolveManifestContractOwnerPluginId?: NonNullable<
170174
Parameters<
171175
typeof commandSecretGatewayTesting.setDepsForTest
@@ -207,9 +211,11 @@ describe("resolveCommandSecretRefsViaGateway", () => {
207211
],
208212
} as never;
209213
},
210-
collectConfigAssignments: ({ context }) => {
211-
context.assignments.push({ path: params.path } as never);
212-
},
214+
collectConfigAssignments:
215+
params.collectConfigAssignments ??
216+
(({ context }) => {
217+
context.assignments.push({ path: params.path } as never);
218+
}),
213219
discoverConfigSecretTargetsByIds: (config) =>
214220
[
215221
{
@@ -331,6 +337,66 @@ describe("resolveCommandSecretRefsViaGateway", () => {
331337
expect(readTalkProviderApiKey(result.resolvedConfig)).toBe("sk-live");
332338
});
333339

340+
it("uses the explicit agent owner during channels resolve secret preflight", async () => {
341+
const channelPath = "channels.telegram.botToken";
342+
const channelPathSegments = ["channels", "telegram", "botToken"];
343+
const config = {
344+
agents: {
345+
entries: {
346+
ops: { sandbox: { backend: "docker" } },
347+
research: { sandbox: { backend: "docker" } },
348+
},
349+
defaults: {
350+
sandbox: {
351+
backend: "ssh",
352+
ssh: {
353+
identityData: {
354+
source: "env",
355+
provider: "default",
356+
id: "STALE_SANDBOX_IDENTITY",
357+
},
358+
},
359+
},
360+
},
361+
},
362+
channels: {
363+
telegram: {
364+
botToken: { source: "env", provider: "default", id: "TELEGRAM_BOT_TOKEN" },
365+
},
366+
},
367+
} as unknown as OpenClawConfig;
368+
const restoreDeps = setSingleSecretTargetDeps({
369+
path: channelPath,
370+
pathSegments: channelPathSegments,
371+
collectConfigAssignments: (params) => collectRuntimeConfigAssignments(params),
372+
});
373+
callGateway.mockResolvedValueOnce({
374+
assignments: [
375+
{
376+
path: channelPath,
377+
pathSegments: channelPathSegments,
378+
value: "resolved-telegram-token",
379+
},
380+
],
381+
diagnostics: [],
382+
});
383+
384+
try {
385+
const result = await resolveCommandSecretRefsViaGateway({
386+
config,
387+
commandName: "channels resolve",
388+
targetIds: new Set([channelPath]),
389+
agentId: "ops",
390+
mode: "read_only_operational",
391+
});
392+
393+
expect(result.resolvedConfig.channels?.telegram?.botToken).toBe("resolved-telegram-token");
394+
expect(callGateway.mock.calls[0]?.[0].params).not.toHaveProperty("agentId");
395+
} finally {
396+
restoreDeps();
397+
}
398+
});
399+
334400
it("enforces unresolved checks only for allowed paths when provided", async () => {
335401
const restoreDeps = commandSecretGatewayTesting.setDepsForTest({
336402
analyzeCommandSecretAssignmentsFromSnapshot: () =>

‎src/cli/command-secret-gateway.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,7 @@ function collectConfiguredTargetRefPaths(params: {
290290
function classifyConfiguredTargetRefs(params: {
291291
config: OpenClawConfig;
292292
configuredTargetRefPaths: Set<string>;
293+
agentId?: string;
293294
forcedActivePaths?: ReadonlySet<string>;
294295
optionalActivePaths?: ReadonlySet<string>;
295296
}): {
@@ -311,6 +312,7 @@ function classifyConfiguredTargetRefs(params: {
311312
commandSecretGatewayDeps.collectConfigAssignments({
312313
config: structuredClone(params.config),
313314
context,
315+
agentId: params.agentId,
314316
});
315317

316318
const activePaths = new Set(context.assignments.map((assignment) => assignment.path));
@@ -463,6 +465,7 @@ async function resolveCommandSecretRefsWithoutGateway(params: {
463465
config: OpenClawConfig;
464466
commandName: string;
465467
targetIds: Set<string>;
468+
agentId?: string;
466469
preflightDiagnostics: string[];
467470
mode: CommandSecretResolutionMode;
468471
allowedPaths?: ReadonlySet<string>;
@@ -475,6 +478,7 @@ async function resolveCommandSecretRefsWithoutGateway(params: {
475478
config: params.config,
476479
commandName: params.commandName,
477480
targetIds: params.targetIds,
481+
agentId: params.agentId,
478482
preflightDiagnostics: params.preflightDiagnostics,
479483
mode: params.mode,
480484
allowedPaths: params.allowedPaths,
@@ -541,6 +545,7 @@ async function resolveCommandSecretRefsLocally(params: {
541545
config: OpenClawConfig;
542546
commandName: string;
543547
targetIds: Set<string>;
548+
agentId?: string;
544549
preflightDiagnostics: string[];
545550
mode: CommandSecretResolutionMode;
546551
allowedPaths?: ReadonlySet<string>;
@@ -564,6 +569,7 @@ async function resolveCommandSecretRefsLocally(params: {
564569
commandSecretGatewayDeps.collectConfigAssignments({
565570
config: structuredClone(params.config),
566571
context,
572+
agentId: params.agentId,
567573
});
568574
if (
569575
targetsRuntimeWebResolution({
@@ -828,6 +834,7 @@ export async function resolveCommandSecretRefsViaGateway(params: {
828834
config: OpenClawConfig;
829835
commandName: string;
830836
targetIds: Set<string>;
837+
agentId?: string;
831838
mode?: CommandSecretResolutionModeInput;
832839
allowedPaths?: ReadonlySet<string>;
833840
forcedActivePaths?: ReadonlySet<string>;
@@ -856,6 +863,7 @@ export async function resolveCommandSecretRefsViaGateway(params: {
856863
const preflight = classifyConfiguredTargetRefs({
857864
config: params.config,
858865
configuredTargetRefPaths,
866+
agentId: params.agentId,
859867
forcedActivePaths: params.forcedActivePaths,
860868
optionalActivePaths: params.optionalActivePaths,
861869
});
@@ -875,6 +883,7 @@ export async function resolveCommandSecretRefsViaGateway(params: {
875883
config: params.config,
876884
commandName: params.commandName,
877885
targetIds: params.targetIds,
886+
agentId: params.agentId,
878887
preflightDiagnostics: preflight.diagnostics,
879888
mode,
880889
allowedPaths: params.allowedPaths,
@@ -902,6 +911,7 @@ export async function resolveCommandSecretRefsViaGateway(params: {
902911
config: params.config,
903912
commandName: params.commandName,
904913
targetIds: params.targetIds,
914+
agentId: params.agentId,
905915
preflightDiagnostics: preflight.diagnostics,
906916
mode,
907917
allowedPaths: params.allowedPaths,
@@ -1039,6 +1049,7 @@ export async function resolveCommandSecretRefsViaGateway(params: {
10391049
config: params.config,
10401050
commandName: params.commandName,
10411051
targetIds: params.targetIds,
1052+
agentId: params.agentId,
10421053
preflightDiagnostics: [],
10431054
mode,
10441055
allowedPaths: new Set(analyzed.unresolved.map((entry) => entry.path)),

‎src/commands/channel-setup/channel-plugin-resolution.test.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,10 @@ describe("resolveInstallableChannelPlugin", () => {
8787
});
8888

8989
it("ignores untrusted workspace channel shadows during setup resolution", async () => {
90+
const config = {
91+
agents: { entries: { ops: {}, research: {} } },
92+
plugins: { enabled: true },
93+
};
9094
const workspaceEntry = createCatalogEntry({
9195
id: "telegram",
9296
pluginId: "evil-telegram-shadow",
@@ -114,9 +118,10 @@ describe("resolveInstallableChannelPlugin", () => {
114118
);
115119

116120
const result = await resolveInstallableChannelPlugin({
117-
cfg: { plugins: { enabled: true } },
121+
cfg: config,
118122
runtime: {} as never,
119123
rawChannel: "telegram",
124+
agentId: "ops",
120125
allowInstall: false,
121126
});
122127

@@ -129,6 +134,8 @@ describe("resolveInstallableChannelPlugin", () => {
129134
expect(snapshotRequest?.channel).toBe("telegram");
130135
expect(snapshotRequest?.pluginId).toBe("telegram");
131136
expect(snapshotRequest?.workspaceDir).toBe("/tmp/workspace");
137+
expect(mocks.resolveAgentWorkspaceDir).toHaveBeenCalledWith(config, "ops");
138+
expect(mocks.resolveDefaultAgentId).not.toHaveBeenCalled();
132139
});
133140

134141
it("keeps trusted workspace channel plugins eligible for setup resolution", async () => {

0 commit comments

Comments
 (0)