Skip to content

Commit b5350bf

Browse files
committed
refactor(outbound): unify channel selection and action input normalization
1 parent 0f5f20e commit b5350bf

7 files changed

Lines changed: 297 additions & 83 deletions
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
import { beforeEach, describe, expect, it, vi } from "vitest";
2+
3+
const mocks = vi.hoisted(() => ({
4+
listChannelPlugins: vi.fn(),
5+
}));
6+
7+
vi.mock("../../channels/plugins/index.js", () => ({
8+
listChannelPlugins: mocks.listChannelPlugins,
9+
}));
10+
11+
import { resolveMessageChannelSelection } from "./channel-selection.js";
12+
13+
describe("resolveMessageChannelSelection", () => {
14+
beforeEach(() => {
15+
mocks.listChannelPlugins.mockReset();
16+
mocks.listChannelPlugins.mockReturnValue([]);
17+
});
18+
19+
it("keeps explicit known channels and marks source explicit", async () => {
20+
const selection = await resolveMessageChannelSelection({
21+
cfg: {} as never,
22+
channel: "telegram",
23+
});
24+
25+
expect(selection).toEqual({
26+
channel: "telegram",
27+
configured: [],
28+
source: "explicit",
29+
});
30+
});
31+
32+
it("falls back to tool context channel when explicit channel is unknown", async () => {
33+
const selection = await resolveMessageChannelSelection({
34+
cfg: {} as never,
35+
channel: "channel:C123",
36+
fallbackChannel: "slack",
37+
});
38+
39+
expect(selection).toEqual({
40+
channel: "slack",
41+
configured: [],
42+
source: "tool-context-fallback",
43+
});
44+
});
45+
46+
it("uses fallback channel when explicit channel is omitted", async () => {
47+
const selection = await resolveMessageChannelSelection({
48+
cfg: {} as never,
49+
fallbackChannel: "signal",
50+
});
51+
52+
expect(selection).toEqual({
53+
channel: "signal",
54+
configured: [],
55+
source: "tool-context-fallback",
56+
});
57+
});
58+
59+
it("selects single configured channel when no explicit/fallback channel exists", async () => {
60+
mocks.listChannelPlugins.mockReturnValue([
61+
{
62+
id: "discord",
63+
config: {
64+
listAccountIds: () => ["default"],
65+
resolveAccount: () => ({}),
66+
isConfigured: async () => true,
67+
},
68+
},
69+
]);
70+
71+
const selection = await resolveMessageChannelSelection({
72+
cfg: {} as never,
73+
});
74+
75+
expect(selection).toEqual({
76+
channel: "discord",
77+
configured: ["discord"],
78+
source: "single-configured",
79+
});
80+
});
81+
82+
it("throws unknown channel when explicit and fallback channels are both invalid", async () => {
83+
await expect(
84+
resolveMessageChannelSelection({
85+
cfg: {} as never,
86+
channel: "channel:C123",
87+
fallbackChannel: "not-a-channel",
88+
}),
89+
).rejects.toThrow("Unknown channel: channel:c123");
90+
});
91+
});

‎src/infra/outbound/channel-selection.ts‎

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,36 @@ import type { OpenClawConfig } from "../../config/config.js";
44
import {
55
listDeliverableMessageChannels,
66
type DeliverableMessageChannel,
7+
isDeliverableMessageChannel,
78
normalizeMessageChannel,
89
} from "../../utils/message-channel.js";
910

1011
export type MessageChannelId = DeliverableMessageChannel;
12+
export type MessageChannelSelectionSource =
13+
| "explicit"
14+
| "tool-context-fallback"
15+
| "single-configured";
1116

1217
const getMessageChannels = () => listDeliverableMessageChannels();
1318

1419
function isKnownChannel(value: string): boolean {
1520
return getMessageChannels().includes(value as MessageChannelId);
1621
}
1722

23+
function resolveKnownChannel(value?: string | null): MessageChannelId | undefined {
24+
const normalized = normalizeMessageChannel(value);
25+
if (!normalized) {
26+
return undefined;
27+
}
28+
if (!isDeliverableMessageChannel(normalized)) {
29+
return undefined;
30+
}
31+
if (!isKnownChannel(normalized)) {
32+
return undefined;
33+
}
34+
return normalized as MessageChannelId;
35+
}
36+
1837
function isAccountEnabled(account: unknown): boolean {
1938
if (!account || typeof account !== "object") {
2039
return true;
@@ -67,21 +86,44 @@ export async function listConfiguredMessageChannels(
6786
export async function resolveMessageChannelSelection(params: {
6887
cfg: OpenClawConfig;
6988
channel?: string | null;
70-
}): Promise<{ channel: MessageChannelId; configured: MessageChannelId[] }> {
89+
fallbackChannel?: string | null;
90+
}): Promise<{
91+
channel: MessageChannelId;
92+
configured: MessageChannelId[];
93+
source: MessageChannelSelectionSource;
94+
}> {
7195
const normalized = normalizeMessageChannel(params.channel);
7296
if (normalized) {
7397
if (!isKnownChannel(normalized)) {
98+
const fallback = resolveKnownChannel(params.fallbackChannel);
99+
if (fallback) {
100+
return {
101+
channel: fallback,
102+
configured: await listConfiguredMessageChannels(params.cfg),
103+
source: "tool-context-fallback",
104+
};
105+
}
74106
throw new Error(`Unknown channel: ${String(normalized)}`);
75107
}
76108
return {
77109
channel: normalized as MessageChannelId,
78110
configured: await listConfiguredMessageChannels(params.cfg),
111+
source: "explicit",
112+
};
113+
}
114+
115+
const fallback = resolveKnownChannel(params.fallbackChannel);
116+
if (fallback) {
117+
return {
118+
channel: fallback,
119+
configured: await listConfiguredMessageChannels(params.cfg),
120+
source: "tool-context-fallback",
79121
};
80122
}
81123

82124
const configured = await listConfiguredMessageChannels(params.cfg);
83125
if (configured.length === 1) {
84-
return { channel: configured[0], configured };
126+
return { channel: configured[0], configured, source: "single-configured" };
85127
}
86128
if (configured.length === 0) {
87129
throw new Error("Channel is required (no configured channels detected).");
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import { describe, expect, it } from "vitest";
2+
import { normalizeMessageActionInput } from "./message-action-normalization.js";
3+
4+
describe("normalizeMessageActionInput", () => {
5+
it("prefers explicit target and clears legacy target fields", () => {
6+
const normalized = normalizeMessageActionInput({
7+
action: "send",
8+
args: {
9+
target: "channel:C1",
10+
to: "legacy",
11+
channelId: "legacy-channel",
12+
},
13+
});
14+
15+
expect(normalized.target).toBe("channel:C1");
16+
expect(normalized.to).toBe("channel:C1");
17+
expect("channelId" in normalized).toBe(false);
18+
});
19+
20+
it("maps legacy target fields into canonical target", () => {
21+
const normalized = normalizeMessageActionInput({
22+
action: "send",
23+
args: {
24+
to: "channel:C1",
25+
},
26+
});
27+
28+
expect(normalized.target).toBe("channel:C1");
29+
expect(normalized.to).toBe("channel:C1");
30+
});
31+
32+
it("infers target from tool context when required", () => {
33+
const normalized = normalizeMessageActionInput({
34+
action: "send",
35+
args: {},
36+
toolContext: {
37+
currentChannelId: "channel:C1",
38+
},
39+
});
40+
41+
expect(normalized.target).toBe("channel:C1");
42+
expect(normalized.to).toBe("channel:C1");
43+
});
44+
45+
it("infers channel from tool context provider", () => {
46+
const normalized = normalizeMessageActionInput({
47+
action: "send",
48+
args: {
49+
target: "channel:C1",
50+
},
51+
toolContext: {
52+
currentChannelId: "C1",
53+
currentChannelProvider: "slack",
54+
},
55+
});
56+
57+
expect(normalized.channel).toBe("slack");
58+
});
59+
60+
it("throws when required target remains unresolved", () => {
61+
expect(() =>
62+
normalizeMessageActionInput({
63+
action: "send",
64+
args: {},
65+
}),
66+
).toThrow(/requires a target/);
67+
});
68+
});
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import type {
2+
ChannelMessageActionName,
3+
ChannelThreadingToolContext,
4+
} from "../../channels/plugins/types.js";
5+
import {
6+
isDeliverableMessageChannel,
7+
normalizeMessageChannel,
8+
} from "../../utils/message-channel.js";
9+
import { applyTargetToParams } from "./channel-target.js";
10+
import { actionHasTarget, actionRequiresTarget } from "./message-action-spec.js";
11+
12+
export function normalizeMessageActionInput(params: {
13+
action: ChannelMessageActionName;
14+
args: Record<string, unknown>;
15+
toolContext?: ChannelThreadingToolContext;
16+
}): Record<string, unknown> {
17+
const normalizedArgs = { ...params.args };
18+
const { action, toolContext } = params;
19+
20+
const explicitTarget =
21+
typeof normalizedArgs.target === "string" ? normalizedArgs.target.trim() : "";
22+
const hasLegacyTarget =
23+
(typeof normalizedArgs.to === "string" && normalizedArgs.to.trim().length > 0) ||
24+
(typeof normalizedArgs.channelId === "string" && normalizedArgs.channelId.trim().length > 0);
25+
26+
if (explicitTarget && hasLegacyTarget) {
27+
delete normalizedArgs.to;
28+
delete normalizedArgs.channelId;
29+
}
30+
31+
if (
32+
!explicitTarget &&
33+
!hasLegacyTarget &&
34+
actionRequiresTarget(action) &&
35+
!actionHasTarget(action, normalizedArgs)
36+
) {
37+
const inferredTarget = toolContext?.currentChannelId?.trim();
38+
if (inferredTarget) {
39+
normalizedArgs.target = inferredTarget;
40+
}
41+
}
42+
43+
if (!explicitTarget && actionRequiresTarget(action) && hasLegacyTarget) {
44+
const legacyTo = typeof normalizedArgs.to === "string" ? normalizedArgs.to.trim() : "";
45+
const legacyChannelId =
46+
typeof normalizedArgs.channelId === "string" ? normalizedArgs.channelId.trim() : "";
47+
const legacyTarget = legacyTo || legacyChannelId;
48+
if (legacyTarget) {
49+
normalizedArgs.target = legacyTarget;
50+
delete normalizedArgs.to;
51+
delete normalizedArgs.channelId;
52+
}
53+
}
54+
55+
const explicitChannel =
56+
typeof normalizedArgs.channel === "string" ? normalizedArgs.channel.trim() : "";
57+
if (!explicitChannel) {
58+
const inferredChannel = normalizeMessageChannel(toolContext?.currentChannelProvider);
59+
if (inferredChannel && isDeliverableMessageChannel(inferredChannel)) {
60+
normalizedArgs.channel = inferredChannel;
61+
}
62+
}
63+
64+
applyTargetToParams({ action, args: normalizedArgs });
65+
if (actionRequiresTarget(action) && !actionHasTarget(action, normalizedArgs)) {
66+
throw new Error(`Action ${action} requires a target.`);
67+
}
68+
69+
return normalizedArgs;
70+
}

0 commit comments

Comments
 (0)