Skip to content

Commit a14ad01

Browse files
committed
Plugin SDK: centralize message tool discovery and context
1 parent 4e912bf commit a14ad01

13 files changed

Lines changed: 737 additions & 297 deletions

‎src/agents/channel-tools.ts‎

Lines changed: 42 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,14 @@ import { defaultRuntime } from "../runtime.js";
1515
export function listChannelSupportedActions(params: {
1616
cfg?: OpenClawConfig;
1717
channel?: string;
18+
currentChannelId?: string | null;
19+
currentThreadTs?: string | null;
20+
currentMessageId?: string | number | null;
21+
accountId?: string | null;
22+
sessionKey?: string | null;
23+
sessionId?: string | null;
24+
agentId?: string | null;
25+
requesterSenderId?: string | null;
1826
}): ChannelMessageActionName[] {
1927
if (!params.channel) {
2028
return [];
@@ -24,22 +32,52 @@ export function listChannelSupportedActions(params: {
2432
return [];
2533
}
2634
const cfg = params.cfg ?? ({} as OpenClawConfig);
27-
return runPluginListActions(plugin, cfg);
35+
return runPluginListActions(plugin, {
36+
cfg,
37+
currentChannelId: params.currentChannelId,
38+
currentChannelProvider: params.channel,
39+
currentThreadTs: params.currentThreadTs,
40+
currentMessageId: params.currentMessageId,
41+
accountId: params.accountId,
42+
sessionKey: params.sessionKey,
43+
sessionId: params.sessionId,
44+
agentId: params.agentId,
45+
requesterSenderId: params.requesterSenderId,
46+
});
2847
}
2948

3049
/**
3150
* Get the list of all supported message actions across all configured channels.
3251
*/
3352
export function listAllChannelSupportedActions(params: {
3453
cfg?: OpenClawConfig;
54+
currentChannelId?: string | null;
55+
currentThreadTs?: string | null;
56+
currentMessageId?: string | number | null;
57+
accountId?: string | null;
58+
sessionKey?: string | null;
59+
sessionId?: string | null;
60+
agentId?: string | null;
61+
requesterSenderId?: string | null;
3562
}): ChannelMessageActionName[] {
3663
const actions = new Set<ChannelMessageActionName>();
3764
for (const plugin of listChannelPlugins()) {
3865
if (!plugin.actions?.listActions) {
3966
continue;
4067
}
4168
const cfg = params.cfg ?? ({} as OpenClawConfig);
42-
const channelActions = runPluginListActions(plugin, cfg);
69+
const channelActions = runPluginListActions(plugin, {
70+
cfg,
71+
currentChannelId: params.currentChannelId,
72+
currentChannelProvider: plugin.id,
73+
currentThreadTs: params.currentThreadTs,
74+
currentMessageId: params.currentMessageId,
75+
accountId: params.accountId,
76+
sessionKey: params.sessionKey,
77+
sessionId: params.sessionId,
78+
agentId: params.agentId,
79+
requesterSenderId: params.requesterSenderId,
80+
});
4381
for (const action of channelActions) {
4482
actions.add(action);
4583
}
@@ -86,13 +124,13 @@ const loggedListActionErrors = new Set<string>();
86124

87125
function runPluginListActions(
88126
plugin: ChannelPlugin,
89-
cfg: OpenClawConfig,
127+
context: Parameters<NonNullable<NonNullable<ChannelPlugin["actions"]>["listActions"]>>[0],
90128
): ChannelMessageActionName[] {
91129
if (!plugin.actions?.listActions) {
92130
return [];
93131
}
94132
try {
95-
const listed = plugin.actions.listActions({ cfg });
133+
const listed = plugin.actions.listActions(context);
96134
return Array.isArray(listed) ? listed : [];
97135
} catch (err) {
98136
logListActionsError(plugin.id, err);

‎src/agents/openclaw-tools.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,7 @@ export function createOpenClawTools(
135135
: createMessageTool({
136136
agentAccountId: options?.agentAccountId,
137137
agentSessionKey: options?.agentSessionKey,
138+
sessionId: options?.sessionId,
138139
config: options?.config,
139140
currentChannelId: options?.currentChannelId,
140141
currentChannelProvider: options?.agentChannel,

‎src/agents/pi-embedded-runner/compact.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -649,11 +649,19 @@ export async function compactEmbeddedPiSessionDirect(
649649
return undefined;
650650
})()
651651
: undefined;
652+
const { defaultAgentId, sessionAgentId } = resolveSessionAgentIds({
653+
sessionKey: params.sessionKey,
654+
config: params.config,
655+
});
652656
// Resolve channel-specific message actions for system prompt
653657
const channelActions = runtimeChannel
654658
? listChannelSupportedActions({
655659
cfg: params.config,
656660
channel: runtimeChannel,
661+
accountId: params.agentAccountId,
662+
sessionKey: params.sessionKey,
663+
sessionId: params.sessionId,
664+
agentId: sessionAgentId,
657665
})
658666
: undefined;
659667
const messageToolHints = runtimeChannel
@@ -680,10 +688,6 @@ export async function compactEmbeddedPiSessionDirect(
680688
const userTimezone = resolveUserTimezone(params.config?.agents?.defaults?.userTimezone);
681689
const userTimeFormat = resolveUserTimeFormat(params.config?.agents?.defaults?.timeFormat);
682690
const userTime = formatUserTime(new Date(), userTimezone, userTimeFormat);
683-
const { defaultAgentId, sessionAgentId } = resolveSessionAgentIds({
684-
sessionKey: params.sessionKey,
685-
config: params.config,
686-
});
687691
const isDefaultAgent = sessionAgentId === defaultAgentId;
688692
const promptMode =
689693
isSubagentSessionKey(params.sessionKey) || isCronSessionKey(params.sessionKey)

‎src/agents/pi-embedded-runner/run/attempt.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1623,6 +1623,13 @@ export async function runEmbeddedAttempt(
16231623
? listChannelSupportedActions({
16241624
cfg: params.config,
16251625
channel: runtimeChannel,
1626+
currentChannelId: params.currentChannelId,
1627+
currentThreadTs: params.currentThreadTs,
1628+
currentMessageId: params.currentMessageId,
1629+
accountId: params.agentAccountId,
1630+
sessionKey: params.sessionKey,
1631+
sessionId: params.sessionId,
1632+
agentId: sessionAgentId,
16261633
})
16271634
: undefined;
16281635
const messageToolHints = runtimeChannel

‎src/agents/tools/message-tool.test.ts‎

Lines changed: 171 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,20 @@
11
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
22
import type { ChannelMessageCapability } from "../../channels/plugins/message-capabilities.js";
3+
import {
4+
createDiscordMessageToolComponentsSchema,
5+
createMessageToolButtonsSchema,
6+
createSlackMessageToolBlocksSchema,
7+
createTelegramPollExtraToolSchemas,
8+
} from "../../channels/plugins/message-tool-schema.js";
39
import type { ChannelMessageActionName, ChannelPlugin } from "../../channels/plugins/types.js";
410
import type { MessageActionRunResult } from "../../infra/outbound/message-action-runner.js";
5-
import { setActivePluginRegistry } from "../../plugins/runtime.js";
6-
import { createTestRegistry } from "../../test-utils/channel-plugins.js";
7-
import { createMessageTool } from "./message-tool.js";
11+
type CreateMessageTool = typeof import("./message-tool.js").createMessageTool;
12+
type SetActivePluginRegistry = typeof import("../../plugins/runtime.js").setActivePluginRegistry;
13+
type CreateTestRegistry = typeof import("../../test-utils/channel-plugins.js").createTestRegistry;
14+
15+
let createMessageTool: CreateMessageTool;
16+
let setActivePluginRegistry: SetActivePluginRegistry;
17+
let createTestRegistry: CreateTestRegistry;
818

919
const mocks = vi.hoisted(() => ({
1020
runMessageAction: vi.fn(),
@@ -50,21 +60,25 @@ function mockSendResult(overrides: { channel?: string; to?: string } = {}) {
5060
} satisfies MessageActionRunResult);
5161
}
5262

53-
function getToolProperties(tool: ReturnType<typeof createMessageTool>) {
63+
function getToolProperties(tool: ReturnType<CreateMessageTool>) {
5464
return (tool.parameters as { properties?: Record<string, unknown> }).properties ?? {};
5565
}
5666

5767
function getActionEnum(properties: Record<string, unknown>) {
5868
return (properties.action as { enum?: string[] } | undefined)?.enum ?? [];
5969
}
6070

61-
beforeEach(() => {
71+
beforeEach(async () => {
72+
vi.resetModules();
6273
mocks.runMessageAction.mockReset();
6374
mocks.loadConfig.mockReset().mockReturnValue({});
6475
mocks.resolveCommandSecretRefsViaGateway.mockReset().mockImplementation(async ({ config }) => ({
6576
resolvedConfig: config,
6677
diagnostics: [],
6778
}));
79+
({ setActivePluginRegistry } = await import("../../plugins/runtime.js"));
80+
({ createTestRegistry } = await import("../../test-utils/channel-plugins.js"));
81+
({ createMessageTool } = await import("./message-tool.js"));
6882
});
6983

7084
function createChannelPlugin(params: {
@@ -75,6 +89,7 @@ function createChannelPlugin(params: {
7589
actions?: ChannelMessageActionName[];
7690
listActions?: NonNullable<NonNullable<ChannelPlugin["actions"]>["listActions"]>;
7791
capabilities?: readonly ChannelMessageCapability[];
92+
toolSchema?: NonNullable<NonNullable<ChannelPlugin["actions"]>["getToolSchema"]>;
7893
messaging?: ChannelPlugin["messaging"];
7994
}): ChannelPlugin {
8095
const actionCapabilities = params.capabilities;
@@ -102,6 +117,7 @@ function createChannelPlugin(params: {
102117
...(actionCapabilities
103118
? { getCapabilities: (_params: { cfg: unknown }) => actionCapabilities }
104119
: {}),
120+
...(params.toolSchema ? { getToolSchema: params.toolSchema } : {}),
105121
},
106122
};
107123
}
@@ -219,6 +235,17 @@ describe("message tool schema scoping", () => {
219235
blurb: "Telegram test plugin.",
220236
actions: ["send", "react", "poll"],
221237
capabilities: ["interactive", "buttons"],
238+
toolSchema: () => [
239+
{
240+
properties: {
241+
buttons: createMessageToolButtonsSchema(),
242+
},
243+
},
244+
{
245+
properties: createTelegramPollExtraToolSchemas(),
246+
visibility: "all-configured",
247+
},
248+
],
222249
});
223250

224251
const discordPlugin = createChannelPlugin({
@@ -228,6 +255,11 @@ describe("message tool schema scoping", () => {
228255
blurb: "Discord test plugin.",
229256
actions: ["send", "poll", "poll-vote"],
230257
capabilities: ["interactive", "components"],
258+
toolSchema: () => ({
259+
properties: {
260+
components: createDiscordMessageToolComponentsSchema(),
261+
},
262+
}),
231263
});
232264

233265
const slackPlugin = createChannelPlugin({
@@ -237,6 +269,11 @@ describe("message tool schema scoping", () => {
237269
blurb: "Slack test plugin.",
238270
actions: ["send", "react"],
239271
capabilities: ["interactive", "blocks"],
272+
toolSchema: () => ({
273+
properties: {
274+
blocks: createSlackMessageToolBlocksSchema(),
275+
},
276+
}),
240277
});
241278

242279
afterEach(() => {
@@ -365,6 +402,25 @@ describe("message tool schema scoping", () => {
365402
return telegramCfg?.actions?.poll === false ? ["send", "react"] : ["send", "react", "poll"];
366403
},
367404
capabilities: ["interactive", "buttons"],
405+
toolSchema: ({ cfg }) => {
406+
const telegramCfg = (cfg as { channels?: { telegram?: { actions?: { poll?: boolean } } } })
407+
.channels?.telegram;
408+
return [
409+
{
410+
properties: {
411+
buttons: createMessageToolButtonsSchema(),
412+
},
413+
},
414+
...(telegramCfg?.actions?.poll === false
415+
? []
416+
: [
417+
{
418+
properties: createTelegramPollExtraToolSchemas(),
419+
visibility: "all-configured" as const,
420+
},
421+
]),
422+
];
423+
},
368424
});
369425

370426
setActivePluginRegistry(
@@ -393,6 +449,95 @@ describe("message tool schema scoping", () => {
393449
expect(properties.pollAnonymous).toBeUndefined();
394450
expect(properties.pollPublic).toBeUndefined();
395451
});
452+
453+
it("uses discovery account scope for capability-gated shared fields", () => {
454+
const scopedInteractivePlugin = createChannelPlugin({
455+
id: "telegram",
456+
label: "Telegram",
457+
docsPath: "/channels/telegram",
458+
blurb: "Telegram test plugin.",
459+
actions: ["send"],
460+
toolSchema: () => null,
461+
});
462+
scopedInteractivePlugin.actions = {
463+
...scopedInteractivePlugin.actions,
464+
getCapabilities: ({ accountId }) => (accountId === "ops" ? ["interactive"] : []),
465+
};
466+
467+
setActivePluginRegistry(
468+
createTestRegistry([
469+
{ pluginId: "telegram", source: "test", plugin: scopedInteractivePlugin },
470+
]),
471+
);
472+
473+
const scopedTool = createMessageTool({
474+
config: {} as never,
475+
currentChannelProvider: "telegram",
476+
agentAccountId: "ops",
477+
});
478+
const unscopedTool = createMessageTool({
479+
config: {} as never,
480+
currentChannelProvider: "telegram",
481+
});
482+
483+
expect(getToolProperties(scopedTool).interactive).toBeDefined();
484+
expect(getToolProperties(unscopedTool).interactive).toBeUndefined();
485+
});
486+
487+
it("routes full discovery context into plugin action discovery", () => {
488+
const seenContexts: Record<string, unknown>[] = [];
489+
const contextPlugin = createChannelPlugin({
490+
id: "discord",
491+
label: "Discord",
492+
docsPath: "/channels/discord",
493+
blurb: "Discord context plugin.",
494+
listActions: (ctx) => {
495+
seenContexts.push({ phase: "listActions", ...ctx });
496+
return ["send", "react"];
497+
},
498+
toolSchema: (ctx) => {
499+
seenContexts.push({ phase: "getToolSchema", ...ctx });
500+
return null;
501+
},
502+
});
503+
contextPlugin.actions = {
504+
...contextPlugin.actions,
505+
getCapabilities: (ctx) => {
506+
seenContexts.push({ phase: "getCapabilities", ...ctx });
507+
return ["interactive"];
508+
},
509+
};
510+
511+
setActivePluginRegistry(
512+
createTestRegistry([{ pluginId: "discord", source: "test", plugin: contextPlugin }]),
513+
);
514+
515+
createMessageTool({
516+
config: {} as never,
517+
currentChannelProvider: "discord",
518+
currentChannelId: "channel:123",
519+
currentThreadTs: "thread-456",
520+
currentMessageId: "msg-789",
521+
agentAccountId: "ops",
522+
agentSessionKey: "agent:alpha:main",
523+
sessionId: "session-123",
524+
requesterSenderId: "user-42",
525+
});
526+
527+
expect(seenContexts).toContainEqual(
528+
expect.objectContaining({
529+
currentChannelProvider: "discord",
530+
currentChannelId: "channel:123",
531+
currentThreadTs: "thread-456",
532+
currentMessageId: "msg-789",
533+
accountId: "ops",
534+
sessionKey: "agent:alpha:main",
535+
sessionId: "session-123",
536+
agentId: "alpha",
537+
requesterSenderId: "user-42",
538+
}),
539+
);
540+
});
396541
});
397542

398543
describe("message tool description", () => {
@@ -405,7 +550,27 @@ describe("message tool description", () => {
405550
label: "BlueBubbles",
406551
docsPath: "/channels/bluebubbles",
407552
blurb: "BlueBubbles test plugin.",
408-
actions: ["react", "renameGroup", "addParticipant", "removeParticipant", "leaveGroup"],
553+
listActions: ({ currentChannelId }) => {
554+
const all: ChannelMessageActionName[] = [
555+
"react",
556+
"renameGroup",
557+
"addParticipant",
558+
"removeParticipant",
559+
"leaveGroup",
560+
];
561+
const lowered = currentChannelId?.toLowerCase() ?? "";
562+
const isDmTarget =
563+
lowered.includes("chat_guid:imessage;-;") || lowered.includes("chat_guid:sms;-;");
564+
return isDmTarget
565+
? all.filter(
566+
(action) =>
567+
action !== "renameGroup" &&
568+
action !== "addParticipant" &&
569+
action !== "removeParticipant" &&
570+
action !== "leaveGroup",
571+
)
572+
: all;
573+
},
409574
messaging: {
410575
normalizeTarget: (raw) => {
411576
const trimmed = raw.trim().replace(/^bluebubbles:/i, "");

0 commit comments

Comments
 (0)