Discord: honor accountId across channel actions (refs #1489)

This commit is contained in:
Sergii Kozak
2026-01-23 00:50:50 -08:00
parent dc89bc4004
commit 716f901504
8 changed files with 322 additions and 146 deletions

View File

@@ -5,6 +5,10 @@ vi.mock("../../gateway/call.js", () => ({
callGateway: (opts: unknown) => callGatewayMock(opts), callGateway: (opts: unknown) => callGatewayMock(opts),
})); }));
vi.mock("../agent-scope.js", () => ({
resolveSessionAgentId: () => "agent-123",
}));
import { createCronTool } from "./cron-tool.js"; import { createCronTool } from "./cron-tool.js";
describe("cron tool", () => { describe("cron tool", () => {
@@ -85,6 +89,23 @@ describe("cron tool", () => {
}); });
}); });
it("does not default agentId when job.agentId is null", async () => {
const tool = createCronTool({ agentSessionKey: "main" });
await tool.execute("call-null", {
action: "add",
job: {
name: "wake-up",
schedule: { atMs: 123 },
agentId: null,
},
});
const call = callGatewayMock.mock.calls[0]?.[0] as {
params?: { agentId?: unknown };
};
expect(call?.params?.agentId).toBeNull();
});
it("adds recent context for systemEvent reminders when contextMessages > 0", async () => { it("adds recent context for systemEvent reminders when contextMessages > 0", async () => {
callGatewayMock callGatewayMock
.mockResolvedValueOnce({ .mockResolvedValueOnce({

View File

@@ -164,7 +164,7 @@ export function createCronTool(opts?: CronToolOptions): AnyAgentTool {
const agentId = opts?.agentSessionKey const agentId = opts?.agentSessionKey
? resolveSessionAgentId({ sessionKey: opts.agentSessionKey, config: cfg }) ? resolveSessionAgentId({ sessionKey: opts.agentSessionKey, config: cfg })
: undefined; : undefined;
if (agentId && !(job as { agentId?: unknown }).agentId) { if (agentId && !("agentId" in (job as { agentId?: unknown }))) {
(job as { agentId?: string }).agentId = agentId; (job as { agentId?: string }).agentId = agentId;
} }
} }

View File

@@ -39,6 +39,9 @@ export async function handleDiscordGuildAction(
params: Record<string, unknown>, params: Record<string, unknown>,
isActionEnabled: ActionGate<DiscordActionConfig>, isActionEnabled: ActionGate<DiscordActionConfig>,
): Promise<AgentToolResult<unknown>> { ): Promise<AgentToolResult<unknown>> {
const accountId = readStringParam(params, "accountId");
const accountOpts = accountId ? { accountId } : {};
switch (action) { switch (action) {
case "memberInfo": { case "memberInfo": {
if (!isActionEnabled("memberInfo")) { if (!isActionEnabled("memberInfo")) {
@@ -50,7 +53,7 @@ export async function handleDiscordGuildAction(
const userId = readStringParam(params, "userId", { const userId = readStringParam(params, "userId", {
required: true, required: true,
}); });
const member = await fetchMemberInfoDiscord(guildId, userId); const member = await fetchMemberInfoDiscord(guildId, userId, accountOpts);
return jsonResult({ ok: true, member }); return jsonResult({ ok: true, member });
} }
case "roleInfo": { case "roleInfo": {
@@ -60,7 +63,7 @@ export async function handleDiscordGuildAction(
const guildId = readStringParam(params, "guildId", { const guildId = readStringParam(params, "guildId", {
required: true, required: true,
}); });
const roles = await fetchRoleInfoDiscord(guildId); const roles = await fetchRoleInfoDiscord(guildId, accountOpts);
return jsonResult({ ok: true, roles }); return jsonResult({ ok: true, roles });
} }
case "emojiList": { case "emojiList": {
@@ -70,7 +73,7 @@ export async function handleDiscordGuildAction(
const guildId = readStringParam(params, "guildId", { const guildId = readStringParam(params, "guildId", {
required: true, required: true,
}); });
const emojis = await listGuildEmojisDiscord(guildId); const emojis = await listGuildEmojisDiscord(guildId, accountOpts);
return jsonResult({ ok: true, emojis }); return jsonResult({ ok: true, emojis });
} }
case "emojiUpload": { case "emojiUpload": {
@@ -85,12 +88,15 @@ export async function handleDiscordGuildAction(
required: true, required: true,
}); });
const roleIds = readStringArrayParam(params, "roleIds"); const roleIds = readStringArrayParam(params, "roleIds");
const emoji = await uploadEmojiDiscord({ const emoji = await uploadEmojiDiscord(
guildId, {
name, guildId,
mediaUrl, name,
roleIds: roleIds?.length ? roleIds : undefined, mediaUrl,
}); roleIds: roleIds?.length ? roleIds : undefined,
},
accountOpts,
);
return jsonResult({ ok: true, emoji }); return jsonResult({ ok: true, emoji });
} }
case "stickerUpload": { case "stickerUpload": {
@@ -108,13 +114,16 @@ export async function handleDiscordGuildAction(
const mediaUrl = readStringParam(params, "mediaUrl", { const mediaUrl = readStringParam(params, "mediaUrl", {
required: true, required: true,
}); });
const sticker = await uploadStickerDiscord({ const sticker = await uploadStickerDiscord(
guildId, {
name, guildId,
description, name,
tags, description,
mediaUrl, tags,
}); mediaUrl,
},
accountOpts,
);
return jsonResult({ ok: true, sticker }); return jsonResult({ ok: true, sticker });
} }
case "roleAdd": { case "roleAdd": {
@@ -128,7 +137,7 @@ export async function handleDiscordGuildAction(
required: true, required: true,
}); });
const roleId = readStringParam(params, "roleId", { required: true }); const roleId = readStringParam(params, "roleId", { required: true });
await addRoleDiscord({ guildId, userId, roleId }); await addRoleDiscord({ guildId, userId, roleId }, accountOpts);
return jsonResult({ ok: true }); return jsonResult({ ok: true });
} }
case "roleRemove": { case "roleRemove": {
@@ -142,7 +151,7 @@ export async function handleDiscordGuildAction(
required: true, required: true,
}); });
const roleId = readStringParam(params, "roleId", { required: true }); const roleId = readStringParam(params, "roleId", { required: true });
await removeRoleDiscord({ guildId, userId, roleId }); await removeRoleDiscord({ guildId, userId, roleId }, accountOpts);
return jsonResult({ ok: true }); return jsonResult({ ok: true });
} }
case "channelInfo": { case "channelInfo": {
@@ -152,7 +161,7 @@ export async function handleDiscordGuildAction(
const channelId = readStringParam(params, "channelId", { const channelId = readStringParam(params, "channelId", {
required: true, required: true,
}); });
const channel = await fetchChannelInfoDiscord(channelId); const channel = await fetchChannelInfoDiscord(channelId, accountOpts);
return jsonResult({ ok: true, channel }); return jsonResult({ ok: true, channel });
} }
case "channelList": { case "channelList": {
@@ -162,7 +171,7 @@ export async function handleDiscordGuildAction(
const guildId = readStringParam(params, "guildId", { const guildId = readStringParam(params, "guildId", {
required: true, required: true,
}); });
const channels = await listGuildChannelsDiscord(guildId); const channels = await listGuildChannelsDiscord(guildId, accountOpts);
return jsonResult({ ok: true, channels }); return jsonResult({ ok: true, channels });
} }
case "voiceStatus": { case "voiceStatus": {
@@ -175,7 +184,7 @@ export async function handleDiscordGuildAction(
const userId = readStringParam(params, "userId", { const userId = readStringParam(params, "userId", {
required: true, required: true,
}); });
const voice = await fetchVoiceStatusDiscord(guildId, userId); const voice = await fetchVoiceStatusDiscord(guildId, userId, accountOpts);
return jsonResult({ ok: true, voice }); return jsonResult({ ok: true, voice });
} }
case "eventList": { case "eventList": {
@@ -185,7 +194,7 @@ export async function handleDiscordGuildAction(
const guildId = readStringParam(params, "guildId", { const guildId = readStringParam(params, "guildId", {
required: true, required: true,
}); });
const events = await listScheduledEventsDiscord(guildId); const events = await listScheduledEventsDiscord(guildId, accountOpts);
return jsonResult({ ok: true, events }); return jsonResult({ ok: true, events });
} }
case "eventCreate": { case "eventCreate": {
@@ -215,7 +224,7 @@ export async function handleDiscordGuildAction(
entity_metadata: entityType === 3 && location ? { location } : undefined, entity_metadata: entityType === 3 && location ? { location } : undefined,
privacy_level: 2, privacy_level: 2,
}; };
const event = await createScheduledEventDiscord(guildId, payload); const event = await createScheduledEventDiscord(guildId, payload, accountOpts);
return jsonResult({ ok: true, event }); return jsonResult({ ok: true, event });
} }
case "channelCreate": { case "channelCreate": {
@@ -229,15 +238,18 @@ export async function handleDiscordGuildAction(
const topic = readStringParam(params, "topic"); const topic = readStringParam(params, "topic");
const position = readNumberParam(params, "position", { integer: true }); const position = readNumberParam(params, "position", { integer: true });
const nsfw = params.nsfw as boolean | undefined; const nsfw = params.nsfw as boolean | undefined;
const channel = await createChannelDiscord({ const channel = await createChannelDiscord(
guildId, {
name, guildId,
type: type ?? undefined, name,
parentId: parentId ?? undefined, type: type ?? undefined,
topic: topic ?? undefined, parentId: parentId ?? undefined,
position: position ?? undefined, topic: topic ?? undefined,
nsfw, position: position ?? undefined,
}); nsfw,
},
accountOpts,
);
return jsonResult({ ok: true, channel }); return jsonResult({ ok: true, channel });
} }
case "channelEdit": { case "channelEdit": {
@@ -255,15 +267,18 @@ export async function handleDiscordGuildAction(
const rateLimitPerUser = readNumberParam(params, "rateLimitPerUser", { const rateLimitPerUser = readNumberParam(params, "rateLimitPerUser", {
integer: true, integer: true,
}); });
const channel = await editChannelDiscord({ const channel = await editChannelDiscord(
channelId, {
name: name ?? undefined, channelId,
topic: topic ?? undefined, name: name ?? undefined,
position: position ?? undefined, topic: topic ?? undefined,
parentId, position: position ?? undefined,
nsfw, parentId,
rateLimitPerUser: rateLimitPerUser ?? undefined, nsfw,
}); rateLimitPerUser: rateLimitPerUser ?? undefined,
},
accountOpts,
);
return jsonResult({ ok: true, channel }); return jsonResult({ ok: true, channel });
} }
case "channelDelete": { case "channelDelete": {
@@ -273,7 +288,7 @@ export async function handleDiscordGuildAction(
const channelId = readStringParam(params, "channelId", { const channelId = readStringParam(params, "channelId", {
required: true, required: true,
}); });
const result = await deleteChannelDiscord(channelId); const result = await deleteChannelDiscord(channelId, accountOpts);
return jsonResult(result); return jsonResult(result);
} }
case "channelMove": { case "channelMove": {
@@ -286,12 +301,15 @@ export async function handleDiscordGuildAction(
}); });
const parentId = readParentIdParam(params); const parentId = readParentIdParam(params);
const position = readNumberParam(params, "position", { integer: true }); const position = readNumberParam(params, "position", { integer: true });
await moveChannelDiscord({ await moveChannelDiscord(
guildId, {
channelId, guildId,
parentId, channelId,
position: position ?? undefined, parentId,
}); position: position ?? undefined,
},
accountOpts,
);
return jsonResult({ ok: true }); return jsonResult({ ok: true });
} }
case "categoryCreate": { case "categoryCreate": {
@@ -301,12 +319,15 @@ export async function handleDiscordGuildAction(
const guildId = readStringParam(params, "guildId", { required: true }); const guildId = readStringParam(params, "guildId", { required: true });
const name = readStringParam(params, "name", { required: true }); const name = readStringParam(params, "name", { required: true });
const position = readNumberParam(params, "position", { integer: true }); const position = readNumberParam(params, "position", { integer: true });
const channel = await createChannelDiscord({ const channel = await createChannelDiscord(
guildId, {
name, guildId,
type: 4, name,
position: position ?? undefined, type: 4,
}); position: position ?? undefined,
},
accountOpts,
);
return jsonResult({ ok: true, category: channel }); return jsonResult({ ok: true, category: channel });
} }
case "categoryEdit": { case "categoryEdit": {
@@ -318,11 +339,14 @@ export async function handleDiscordGuildAction(
}); });
const name = readStringParam(params, "name"); const name = readStringParam(params, "name");
const position = readNumberParam(params, "position", { integer: true }); const position = readNumberParam(params, "position", { integer: true });
const channel = await editChannelDiscord({ const channel = await editChannelDiscord(
channelId: categoryId, {
name: name ?? undefined, channelId: categoryId,
position: position ?? undefined, name: name ?? undefined,
}); position: position ?? undefined,
},
accountOpts,
);
return jsonResult({ ok: true, category: channel }); return jsonResult({ ok: true, category: channel });
} }
case "categoryDelete": { case "categoryDelete": {
@@ -332,7 +356,7 @@ export async function handleDiscordGuildAction(
const categoryId = readStringParam(params, "categoryId", { const categoryId = readStringParam(params, "categoryId", {
required: true, required: true,
}); });
const result = await deleteChannelDiscord(categoryId); const result = await deleteChannelDiscord(categoryId, accountOpts);
return jsonResult(result); return jsonResult(result);
} }
case "channelPermissionSet": { case "channelPermissionSet": {
@@ -349,13 +373,16 @@ export async function handleDiscordGuildAction(
const targetType = targetTypeRaw === "member" ? 1 : 0; const targetType = targetTypeRaw === "member" ? 1 : 0;
const allow = readStringParam(params, "allow"); const allow = readStringParam(params, "allow");
const deny = readStringParam(params, "deny"); const deny = readStringParam(params, "deny");
await setChannelPermissionDiscord({ await setChannelPermissionDiscord(
channelId, {
targetId, channelId,
targetType, targetId,
allow: allow ?? undefined, targetType,
deny: deny ?? undefined, allow: allow ?? undefined,
}); deny: deny ?? undefined,
},
accountOpts,
);
return jsonResult({ ok: true }); return jsonResult({ ok: true });
} }
case "channelPermissionRemove": { case "channelPermissionRemove": {
@@ -366,7 +393,7 @@ export async function handleDiscordGuildAction(
required: true, required: true,
}); });
const targetId = readStringParam(params, "targetId", { required: true }); const targetId = readStringParam(params, "targetId", { required: true });
await removeChannelPermissionDiscord(channelId, targetId); await removeChannelPermissionDiscord(channelId, targetId, accountOpts);
return jsonResult({ ok: true }); return jsonResult({ ok: true });
} }
default: default:

View File

@@ -65,6 +65,8 @@ export async function handleDiscordMessagingAction(
(message as { timestamp?: unknown }).timestamp, (message as { timestamp?: unknown }).timestamp,
); );
}; };
const accountId = readStringParam(params, "accountId");
const accountOpts = accountId ? { accountId } : {};
switch (action) { switch (action) {
case "react": { case "react": {
if (!isActionEnabled("reactions")) { if (!isActionEnabled("reactions")) {
@@ -78,14 +80,14 @@ export async function handleDiscordMessagingAction(
removeErrorMessage: "Emoji is required to remove a Discord reaction.", removeErrorMessage: "Emoji is required to remove a Discord reaction.",
}); });
if (remove) { if (remove) {
await removeReactionDiscord(channelId, messageId, emoji); await removeReactionDiscord(channelId, messageId, emoji, accountOpts);
return jsonResult({ ok: true, removed: emoji }); return jsonResult({ ok: true, removed: emoji });
} }
if (isEmpty) { if (isEmpty) {
const removed = await removeOwnReactionsDiscord(channelId, messageId); const removed = await removeOwnReactionsDiscord(channelId, messageId, accountOpts);
return jsonResult({ ok: true, removed: removed.removed }); return jsonResult({ ok: true, removed: removed.removed });
} }
await reactMessageDiscord(channelId, messageId, emoji); await reactMessageDiscord(channelId, messageId, emoji, accountOpts);
return jsonResult({ ok: true, added: emoji }); return jsonResult({ ok: true, added: emoji });
} }
case "reactions": { case "reactions": {
@@ -100,6 +102,7 @@ export async function handleDiscordMessagingAction(
const limit = const limit =
typeof limitRaw === "number" && Number.isFinite(limitRaw) ? limitRaw : undefined; typeof limitRaw === "number" && Number.isFinite(limitRaw) ? limitRaw : undefined;
const reactions = await fetchReactionsDiscord(channelId, messageId, { const reactions = await fetchReactionsDiscord(channelId, messageId, {
...accountOpts,
limit, limit,
}); });
return jsonResult({ ok: true, reactions }); return jsonResult({ ok: true, reactions });
@@ -114,8 +117,10 @@ export async function handleDiscordMessagingAction(
required: true, required: true,
label: "stickerIds", label: "stickerIds",
}); });
const accountId = readStringParam(params, "accountId"); await sendStickerDiscord(to, stickerIds, {
await sendStickerDiscord(to, stickerIds, { content, accountId: accountId ?? undefined }); content,
accountId: accountId ?? undefined,
});
return jsonResult({ ok: true }); return jsonResult({ ok: true });
} }
case "poll": { case "poll": {
@@ -138,7 +143,6 @@ export async function handleDiscordMessagingAction(
const durationHours = const durationHours =
typeof durationRaw === "number" && Number.isFinite(durationRaw) ? durationRaw : undefined; typeof durationRaw === "number" && Number.isFinite(durationRaw) ? durationRaw : undefined;
const maxSelections = allowMultiselect ? Math.max(2, answers.length) : 1; const maxSelections = allowMultiselect ? Math.max(2, answers.length) : 1;
const accountId = readStringParam(params, "accountId");
await sendPollDiscord( await sendPollDiscord(
to, to,
{ question, options: answers, maxSelections, durationHours }, { question, options: answers, maxSelections, durationHours },
@@ -151,7 +155,7 @@ export async function handleDiscordMessagingAction(
throw new Error("Discord permissions are disabled."); throw new Error("Discord permissions are disabled.");
} }
const channelId = resolveChannelId(); const channelId = resolveChannelId();
const permissions = await fetchChannelPermissionsDiscord(channelId); const permissions = await fetchChannelPermissionsDiscord(channelId, accountOpts);
return jsonResult({ ok: true, permissions }); return jsonResult({ ok: true, permissions });
} }
case "fetchMessage": { case "fetchMessage": {
@@ -173,7 +177,7 @@ export async function handleDiscordMessagingAction(
"Discord message fetch requires guildId, channelId, and messageId (or a valid messageLink).", "Discord message fetch requires guildId, channelId, and messageId (or a valid messageLink).",
); );
} }
const message = await fetchMessageDiscord(channelId, messageId); const message = await fetchMessageDiscord(channelId, messageId, accountOpts);
return jsonResult({ return jsonResult({
ok: true, ok: true,
message: normalizeMessage(message), message: normalizeMessage(message),
@@ -187,15 +191,19 @@ export async function handleDiscordMessagingAction(
throw new Error("Discord message reads are disabled."); throw new Error("Discord message reads are disabled.");
} }
const channelId = resolveChannelId(); const channelId = resolveChannelId();
const messages = await readMessagesDiscord(channelId, { const messages = await readMessagesDiscord(
limit: channelId,
typeof params.limit === "number" && Number.isFinite(params.limit) {
? params.limit limit:
: undefined, typeof params.limit === "number" && Number.isFinite(params.limit)
before: readStringParam(params, "before"), ? params.limit
after: readStringParam(params, "after"), : undefined,
around: readStringParam(params, "around"), before: readStringParam(params, "before"),
}); after: readStringParam(params, "after"),
around: readStringParam(params, "around"),
},
accountOpts,
);
return jsonResult({ return jsonResult({
ok: true, ok: true,
messages: messages.map((message) => normalizeMessage(message)), messages: messages.map((message) => normalizeMessage(message)),
@@ -213,8 +221,6 @@ export async function handleDiscordMessagingAction(
const replyTo = readStringParam(params, "replyTo"); const replyTo = readStringParam(params, "replyTo");
const embeds = const embeds =
Array.isArray(params.embeds) && params.embeds.length > 0 ? params.embeds : undefined; Array.isArray(params.embeds) && params.embeds.length > 0 ? params.embeds : undefined;
const accountId = readStringParam(params, "accountId");
const result = await sendMessageDiscord(to, content, { const result = await sendMessageDiscord(to, content, {
accountId: accountId ?? undefined, accountId: accountId ?? undefined,
mediaUrl, mediaUrl,
@@ -234,9 +240,14 @@ export async function handleDiscordMessagingAction(
const content = readStringParam(params, "content", { const content = readStringParam(params, "content", {
required: true, required: true,
}); });
const message = await editMessageDiscord(channelId, messageId, { const message = await editMessageDiscord(
content, channelId,
}); messageId,
{
content,
},
accountOpts,
);
return jsonResult({ ok: true, message }); return jsonResult({ ok: true, message });
} }
case "deleteMessage": { case "deleteMessage": {
@@ -247,7 +258,7 @@ export async function handleDiscordMessagingAction(
const messageId = readStringParam(params, "messageId", { const messageId = readStringParam(params, "messageId", {
required: true, required: true,
}); });
await deleteMessageDiscord(channelId, messageId); await deleteMessageDiscord(channelId, messageId, accountOpts);
return jsonResult({ ok: true }); return jsonResult({ ok: true });
} }
case "threadCreate": { case "threadCreate": {
@@ -262,11 +273,15 @@ export async function handleDiscordMessagingAction(
typeof autoArchiveMinutesRaw === "number" && Number.isFinite(autoArchiveMinutesRaw) typeof autoArchiveMinutesRaw === "number" && Number.isFinite(autoArchiveMinutesRaw)
? autoArchiveMinutesRaw ? autoArchiveMinutesRaw
: undefined; : undefined;
const thread = await createThreadDiscord(channelId, { const thread = await createThreadDiscord(
name, channelId,
messageId, {
autoArchiveMinutes, name,
}); messageId,
autoArchiveMinutes,
},
accountOpts,
);
return jsonResult({ ok: true, thread }); return jsonResult({ ok: true, thread });
} }
case "threadList": { case "threadList": {
@@ -284,13 +299,16 @@ export async function handleDiscordMessagingAction(
typeof params.limit === "number" && Number.isFinite(params.limit) typeof params.limit === "number" && Number.isFinite(params.limit)
? params.limit ? params.limit
: undefined; : undefined;
const threads = await listThreadsDiscord({ const threads = await listThreadsDiscord(
guildId, {
channelId, guildId,
includeArchived, channelId,
before, includeArchived,
limit, before,
}); limit,
},
accountOpts,
);
return jsonResult({ ok: true, threads }); return jsonResult({ ok: true, threads });
} }
case "threadReply": { case "threadReply": {
@@ -303,7 +321,6 @@ export async function handleDiscordMessagingAction(
}); });
const mediaUrl = readStringParam(params, "mediaUrl"); const mediaUrl = readStringParam(params, "mediaUrl");
const replyTo = readStringParam(params, "replyTo"); const replyTo = readStringParam(params, "replyTo");
const accountId = readStringParam(params, "accountId");
const result = await sendMessageDiscord(`channel:${channelId}`, content, { const result = await sendMessageDiscord(`channel:${channelId}`, content, {
accountId: accountId ?? undefined, accountId: accountId ?? undefined,
mediaUrl, mediaUrl,
@@ -319,7 +336,7 @@ export async function handleDiscordMessagingAction(
const messageId = readStringParam(params, "messageId", { const messageId = readStringParam(params, "messageId", {
required: true, required: true,
}); });
await pinMessageDiscord(channelId, messageId); await pinMessageDiscord(channelId, messageId, accountOpts);
return jsonResult({ ok: true }); return jsonResult({ ok: true });
} }
case "unpinMessage": { case "unpinMessage": {
@@ -330,7 +347,7 @@ export async function handleDiscordMessagingAction(
const messageId = readStringParam(params, "messageId", { const messageId = readStringParam(params, "messageId", {
required: true, required: true,
}); });
await unpinMessageDiscord(channelId, messageId); await unpinMessageDiscord(channelId, messageId, accountOpts);
return jsonResult({ ok: true }); return jsonResult({ ok: true });
} }
case "listPins": { case "listPins": {
@@ -338,7 +355,7 @@ export async function handleDiscordMessagingAction(
throw new Error("Discord pins are disabled."); throw new Error("Discord pins are disabled.");
} }
const channelId = resolveChannelId(); const channelId = resolveChannelId();
const pins = await listPinsDiscord(channelId); const pins = await listPinsDiscord(channelId, accountOpts);
return jsonResult({ ok: true, pins: pins.map((pin) => normalizeMessage(pin)) }); return jsonResult({ ok: true, pins: pins.map((pin) => normalizeMessage(pin)) });
} }
case "searchMessages": { case "searchMessages": {
@@ -361,13 +378,16 @@ export async function handleDiscordMessagingAction(
: undefined; : undefined;
const channelIdList = [...(channelIds ?? []), ...(channelId ? [channelId] : [])]; const channelIdList = [...(channelIds ?? []), ...(channelId ? [channelId] : [])];
const authorIdList = [...(authorIds ?? []), ...(authorId ? [authorId] : [])]; const authorIdList = [...(authorIds ?? []), ...(authorId ? [authorId] : [])];
const results = await searchMessagesDiscord({ const results = await searchMessagesDiscord(
guildId, {
content, guildId,
channelIds: channelIdList.length ? channelIdList : undefined, content,
authorIds: authorIdList.length ? authorIdList : undefined, channelIds: channelIdList.length ? channelIdList : undefined,
limit, authorIds: authorIdList.length ? authorIdList : undefined,
}); limit,
},
accountOpts,
);
if (!results || typeof results !== "object") { if (!results || typeof results !== "object") {
return jsonResult({ ok: true, results }); return jsonResult({ ok: true, results });
} }

View File

@@ -8,6 +8,9 @@ export async function handleDiscordModerationAction(
params: Record<string, unknown>, params: Record<string, unknown>,
isActionEnabled: ActionGate<DiscordActionConfig>, isActionEnabled: ActionGate<DiscordActionConfig>,
): Promise<AgentToolResult<unknown>> { ): Promise<AgentToolResult<unknown>> {
const accountId = readStringParam(params, "accountId");
const accountOpts = accountId ? { accountId } : {};
switch (action) { switch (action) {
case "timeout": { case "timeout": {
if (!isActionEnabled("moderation", false)) { if (!isActionEnabled("moderation", false)) {
@@ -25,13 +28,16 @@ export async function handleDiscordModerationAction(
: undefined; : undefined;
const until = readStringParam(params, "until"); const until = readStringParam(params, "until");
const reason = readStringParam(params, "reason"); const reason = readStringParam(params, "reason");
const member = await timeoutMemberDiscord({ const member = await timeoutMemberDiscord(
guildId, {
userId, guildId,
durationMinutes, userId,
until, durationMinutes,
reason, until,
}); reason,
},
accountOpts,
);
return jsonResult({ ok: true, member }); return jsonResult({ ok: true, member });
} }
case "kick": { case "kick": {
@@ -45,7 +51,7 @@ export async function handleDiscordModerationAction(
required: true, required: true,
}); });
const reason = readStringParam(params, "reason"); const reason = readStringParam(params, "reason");
await kickMemberDiscord({ guildId, userId, reason }); await kickMemberDiscord({ guildId, userId, reason }, accountOpts);
return jsonResult({ ok: true }); return jsonResult({ ok: true });
} }
case "ban": { case "ban": {
@@ -63,12 +69,15 @@ export async function handleDiscordModerationAction(
typeof params.deleteMessageDays === "number" && Number.isFinite(params.deleteMessageDays) typeof params.deleteMessageDays === "number" && Number.isFinite(params.deleteMessageDays)
? params.deleteMessageDays ? params.deleteMessageDays
: undefined; : undefined;
await banMemberDiscord({ await banMemberDiscord(
guildId, {
userId, guildId,
reason, userId,
deleteMessageDays, reason,
}); deleteMessageDays,
},
accountOpts,
);
return jsonResult({ ok: true }); return jsonResult({ ok: true });
} }
default: default:

View File

@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest";
import type { ClawdbotConfig } from "../../../config/config.js"; import type { ClawdbotConfig } from "../../../config/config.js";
type SendMessageDiscord = typeof import("../../../discord/send.js").sendMessageDiscord; type SendMessageDiscord = typeof import("../../../discord/send.js").sendMessageDiscord;
type SendPollDiscord = typeof import("../../../discord/send.js").sendPollDiscord; type SendPollDiscord = typeof import("../../../discord/send.js").sendPollDiscord;
type ReactMessageDiscord = typeof import("../../../discord/send.js").reactMessageDiscord;
const sendMessageDiscord = vi.fn<Parameters<SendMessageDiscord>, ReturnType<SendMessageDiscord>>( const sendMessageDiscord = vi.fn<Parameters<SendMessageDiscord>, ReturnType<SendMessageDiscord>>(
async () => ({ ok: true }) as Awaited<ReturnType<SendMessageDiscord>>, async () => ({ ok: true }) as Awaited<ReturnType<SendMessageDiscord>>,
@@ -10,6 +11,9 @@ const sendMessageDiscord = vi.fn<Parameters<SendMessageDiscord>, ReturnType<Send
const sendPollDiscord = vi.fn<Parameters<SendPollDiscord>, ReturnType<SendPollDiscord>>( const sendPollDiscord = vi.fn<Parameters<SendPollDiscord>, ReturnType<SendPollDiscord>>(
async () => ({ ok: true }) as Awaited<ReturnType<SendPollDiscord>>, async () => ({ ok: true }) as Awaited<ReturnType<SendPollDiscord>>,
); );
const reactMessageDiscord = vi.fn<Parameters<ReactMessageDiscord>, ReturnType<ReactMessageDiscord>>(
async () => ({ ok: true }) as Awaited<ReturnType<ReactMessageDiscord>>,
);
vi.mock("../../../discord/send.js", async () => { vi.mock("../../../discord/send.js", async () => {
const actual = await vi.importActual<typeof import("../../../discord/send.js")>( const actual = await vi.importActual<typeof import("../../../discord/send.js")>(
@@ -19,6 +23,7 @@ vi.mock("../../../discord/send.js", async () => {
...actual, ...actual,
sendMessageDiscord: (...args: Parameters<SendMessageDiscord>) => sendMessageDiscord(...args), sendMessageDiscord: (...args: Parameters<SendMessageDiscord>) => sendMessageDiscord(...args),
sendPollDiscord: (...args: Parameters<SendPollDiscord>) => sendPollDiscord(...args), sendPollDiscord: (...args: Parameters<SendPollDiscord>) => sendPollDiscord(...args),
reactMessageDiscord: (...args: Parameters<ReactMessageDiscord>) => reactMessageDiscord(...args),
}; };
}); });
@@ -104,4 +109,29 @@ describe("handleDiscordMessageAction", () => {
}), }),
); );
}); });
it("forwards accountId for reaction actions", async () => {
reactMessageDiscord.mockClear();
const handleDiscordMessageAction = await loadHandleDiscordMessageAction();
await handleDiscordMessageAction({
action: "react",
params: {
channelId: "123",
messageId: "m1",
emoji: "👍",
},
cfg: {} as ClawdbotConfig,
accountId: "ops",
});
expect(reactMessageDiscord).toHaveBeenCalledWith(
"123",
"m1",
"👍",
expect.objectContaining({
accountId: "ops",
}),
);
});
}); });

View File

@@ -7,7 +7,7 @@ import {
import { handleDiscordAction } from "../../../../agents/tools/discord-actions.js"; import { handleDiscordAction } from "../../../../agents/tools/discord-actions.js";
import type { ChannelMessageActionContext } from "../../types.js"; import type { ChannelMessageActionContext } from "../../types.js";
type Ctx = Pick<ChannelMessageActionContext, "action" | "params" | "cfg">; type Ctx = Pick<ChannelMessageActionContext, "action" | "params" | "cfg" | "accountId">;
export async function tryHandleDiscordMessageActionGuildAdmin(params: { export async function tryHandleDiscordMessageActionGuildAdmin(params: {
ctx: Ctx; ctx: Ctx;
@@ -16,27 +16,38 @@ export async function tryHandleDiscordMessageActionGuildAdmin(params: {
}): Promise<AgentToolResult<unknown> | undefined> { }): Promise<AgentToolResult<unknown> | undefined> {
const { ctx, resolveChannelId, readParentIdParam } = params; const { ctx, resolveChannelId, readParentIdParam } = params;
const { action, params: actionParams, cfg } = ctx; const { action, params: actionParams, cfg } = ctx;
const accountId = ctx.accountId ?? readStringParam(actionParams, "accountId");
const accountIdParam = accountId ?? undefined;
if (action === "member-info") { if (action === "member-info") {
const userId = readStringParam(actionParams, "userId", { required: true }); const userId = readStringParam(actionParams, "userId", { required: true });
const guildId = readStringParam(actionParams, "guildId", { const guildId = readStringParam(actionParams, "guildId", {
required: true, required: true,
}); });
return await handleDiscordAction({ action: "memberInfo", guildId, userId }, cfg); return await handleDiscordAction(
{ action: "memberInfo", accountId: accountIdParam, guildId, userId },
cfg,
);
} }
if (action === "role-info") { if (action === "role-info") {
const guildId = readStringParam(actionParams, "guildId", { const guildId = readStringParam(actionParams, "guildId", {
required: true, required: true,
}); });
return await handleDiscordAction({ action: "roleInfo", guildId }, cfg); return await handleDiscordAction(
{ action: "roleInfo", accountId: accountIdParam, guildId },
cfg,
);
} }
if (action === "emoji-list") { if (action === "emoji-list") {
const guildId = readStringParam(actionParams, "guildId", { const guildId = readStringParam(actionParams, "guildId", {
required: true, required: true,
}); });
return await handleDiscordAction({ action: "emojiList", guildId }, cfg); return await handleDiscordAction(
{ action: "emojiList", accountId: accountIdParam, guildId },
cfg,
);
} }
if (action === "emoji-upload") { if (action === "emoji-upload") {
@@ -50,7 +61,7 @@ export async function tryHandleDiscordMessageActionGuildAdmin(params: {
}); });
const roleIds = readStringArrayParam(actionParams, "roleIds"); const roleIds = readStringArrayParam(actionParams, "roleIds");
return await handleDiscordAction( return await handleDiscordAction(
{ action: "emojiUpload", guildId, name, mediaUrl, roleIds }, { action: "emojiUpload", accountId: accountIdParam, guildId, name, mediaUrl, roleIds },
cfg, cfg,
); );
} }
@@ -73,7 +84,15 @@ export async function tryHandleDiscordMessageActionGuildAdmin(params: {
trim: false, trim: false,
}); });
return await handleDiscordAction( return await handleDiscordAction(
{ action: "stickerUpload", guildId, name, description, tags, mediaUrl }, {
action: "stickerUpload",
accountId: accountIdParam,
guildId,
name,
description,
tags,
mediaUrl,
},
cfg, cfg,
); );
} }
@@ -87,6 +106,7 @@ export async function tryHandleDiscordMessageActionGuildAdmin(params: {
return await handleDiscordAction( return await handleDiscordAction(
{ {
action: action === "role-add" ? "roleAdd" : "roleRemove", action: action === "role-add" ? "roleAdd" : "roleRemove",
accountId: accountIdParam,
guildId, guildId,
userId, userId,
roleId, roleId,
@@ -99,14 +119,20 @@ export async function tryHandleDiscordMessageActionGuildAdmin(params: {
const channelId = readStringParam(actionParams, "channelId", { const channelId = readStringParam(actionParams, "channelId", {
required: true, required: true,
}); });
return await handleDiscordAction({ action: "channelInfo", channelId }, cfg); return await handleDiscordAction(
{ action: "channelInfo", accountId: accountIdParam, channelId },
cfg,
);
} }
if (action === "channel-list") { if (action === "channel-list") {
const guildId = readStringParam(actionParams, "guildId", { const guildId = readStringParam(actionParams, "guildId", {
required: true, required: true,
}); });
return await handleDiscordAction({ action: "channelList", guildId }, cfg); return await handleDiscordAction(
{ action: "channelList", accountId: accountIdParam, guildId },
cfg,
);
} }
if (action === "channel-create") { if (action === "channel-create") {
@@ -124,6 +150,7 @@ export async function tryHandleDiscordMessageActionGuildAdmin(params: {
return await handleDiscordAction( return await handleDiscordAction(
{ {
action: "channelCreate", action: "channelCreate",
accountId: accountIdParam,
guildId, guildId,
name, name,
type: type ?? undefined, type: type ?? undefined,
@@ -153,6 +180,7 @@ export async function tryHandleDiscordMessageActionGuildAdmin(params: {
return await handleDiscordAction( return await handleDiscordAction(
{ {
action: "channelEdit", action: "channelEdit",
accountId: accountIdParam,
channelId, channelId,
name: name ?? undefined, name: name ?? undefined,
topic: topic ?? undefined, topic: topic ?? undefined,
@@ -169,7 +197,10 @@ export async function tryHandleDiscordMessageActionGuildAdmin(params: {
const channelId = readStringParam(actionParams, "channelId", { const channelId = readStringParam(actionParams, "channelId", {
required: true, required: true,
}); });
return await handleDiscordAction({ action: "channelDelete", channelId }, cfg); return await handleDiscordAction(
{ action: "channelDelete", accountId: accountIdParam, channelId },
cfg,
);
} }
if (action === "channel-move") { if (action === "channel-move") {
@@ -186,6 +217,7 @@ export async function tryHandleDiscordMessageActionGuildAdmin(params: {
return await handleDiscordAction( return await handleDiscordAction(
{ {
action: "channelMove", action: "channelMove",
accountId: accountIdParam,
guildId, guildId,
channelId, channelId,
parentId: parentId === undefined ? undefined : parentId, parentId: parentId === undefined ? undefined : parentId,
@@ -206,6 +238,7 @@ export async function tryHandleDiscordMessageActionGuildAdmin(params: {
return await handleDiscordAction( return await handleDiscordAction(
{ {
action: "categoryCreate", action: "categoryCreate",
accountId: accountIdParam,
guildId, guildId,
name, name,
position: position ?? undefined, position: position ?? undefined,
@@ -225,6 +258,7 @@ export async function tryHandleDiscordMessageActionGuildAdmin(params: {
return await handleDiscordAction( return await handleDiscordAction(
{ {
action: "categoryEdit", action: "categoryEdit",
accountId: accountIdParam,
categoryId, categoryId,
name: name ?? undefined, name: name ?? undefined,
position: position ?? undefined, position: position ?? undefined,
@@ -237,7 +271,10 @@ export async function tryHandleDiscordMessageActionGuildAdmin(params: {
const categoryId = readStringParam(actionParams, "categoryId", { const categoryId = readStringParam(actionParams, "categoryId", {
required: true, required: true,
}); });
return await handleDiscordAction({ action: "categoryDelete", categoryId }, cfg); return await handleDiscordAction(
{ action: "categoryDelete", accountId: accountIdParam, categoryId },
cfg,
);
} }
if (action === "voice-status") { if (action === "voice-status") {
@@ -245,14 +282,20 @@ export async function tryHandleDiscordMessageActionGuildAdmin(params: {
required: true, required: true,
}); });
const userId = readStringParam(actionParams, "userId", { required: true }); const userId = readStringParam(actionParams, "userId", { required: true });
return await handleDiscordAction({ action: "voiceStatus", guildId, userId }, cfg); return await handleDiscordAction(
{ action: "voiceStatus", accountId: accountIdParam, guildId, userId },
cfg,
);
} }
if (action === "event-list") { if (action === "event-list") {
const guildId = readStringParam(actionParams, "guildId", { const guildId = readStringParam(actionParams, "guildId", {
required: true, required: true,
}); });
return await handleDiscordAction({ action: "eventList", guildId }, cfg); return await handleDiscordAction(
{ action: "eventList", accountId: accountIdParam, guildId },
cfg,
);
} }
if (action === "event-create") { if (action === "event-create") {
@@ -271,6 +314,7 @@ export async function tryHandleDiscordMessageActionGuildAdmin(params: {
return await handleDiscordAction( return await handleDiscordAction(
{ {
action: "eventCreate", action: "eventCreate",
accountId: accountIdParam,
guildId, guildId,
name, name,
startTime, startTime,
@@ -301,6 +345,7 @@ export async function tryHandleDiscordMessageActionGuildAdmin(params: {
return await handleDiscordAction( return await handleDiscordAction(
{ {
action: discordAction, action: discordAction,
accountId: accountIdParam,
guildId, guildId,
userId, userId,
durationMinutes, durationMinutes,
@@ -325,6 +370,7 @@ export async function tryHandleDiscordMessageActionGuildAdmin(params: {
return await handleDiscordAction( return await handleDiscordAction(
{ {
action: "threadList", action: "threadList",
accountId: accountIdParam,
guildId, guildId,
channelId, channelId,
includeArchived, includeArchived,
@@ -344,6 +390,7 @@ export async function tryHandleDiscordMessageActionGuildAdmin(params: {
return await handleDiscordAction( return await handleDiscordAction(
{ {
action: "threadReply", action: "threadReply",
accountId: accountIdParam,
channelId: resolveChannelId(), channelId: resolveChannelId(),
content, content,
mediaUrl: mediaUrl ?? undefined, mediaUrl: mediaUrl ?? undefined,
@@ -361,6 +408,7 @@ export async function tryHandleDiscordMessageActionGuildAdmin(params: {
return await handleDiscordAction( return await handleDiscordAction(
{ {
action: "searchMessages", action: "searchMessages",
accountId: accountIdParam,
guildId, guildId,
content: query, content: query,
channelId: readStringParam(actionParams, "channelId"), channelId: readStringParam(actionParams, "channelId"),

View File

@@ -22,6 +22,7 @@ export async function handleDiscordMessageAction(
): Promise<AgentToolResult<unknown>> { ): Promise<AgentToolResult<unknown>> {
const { action, params, cfg } = ctx; const { action, params, cfg } = ctx;
const accountId = ctx.accountId ?? readStringParam(params, "accountId"); const accountId = ctx.accountId ?? readStringParam(params, "accountId");
const accountIdParam = accountId ?? undefined;
const resolveChannelId = () => const resolveChannelId = () =>
resolveDiscordChannelId( resolveDiscordChannelId(
@@ -40,7 +41,7 @@ export async function handleDiscordMessageAction(
return await handleDiscordAction( return await handleDiscordAction(
{ {
action: "sendMessage", action: "sendMessage",
accountId: accountId ?? undefined, accountId: accountIdParam,
to, to,
content, content,
mediaUrl: mediaUrl ?? undefined, mediaUrl: mediaUrl ?? undefined,
@@ -64,7 +65,7 @@ export async function handleDiscordMessageAction(
return await handleDiscordAction( return await handleDiscordAction(
{ {
action: "poll", action: "poll",
accountId: accountId ?? undefined, accountId: accountIdParam,
to, to,
question, question,
answers, answers,
@@ -83,6 +84,7 @@ export async function handleDiscordMessageAction(
return await handleDiscordAction( return await handleDiscordAction(
{ {
action: "react", action: "react",
accountId: accountIdParam,
channelId: resolveChannelId(), channelId: resolveChannelId(),
messageId, messageId,
emoji, emoji,
@@ -96,7 +98,13 @@ export async function handleDiscordMessageAction(
const messageId = readStringParam(params, "messageId", { required: true }); const messageId = readStringParam(params, "messageId", { required: true });
const limit = readNumberParam(params, "limit", { integer: true }); const limit = readNumberParam(params, "limit", { integer: true });
return await handleDiscordAction( return await handleDiscordAction(
{ action: "reactions", channelId: resolveChannelId(), messageId, limit }, {
action: "reactions",
accountId: accountIdParam,
channelId: resolveChannelId(),
messageId,
limit,
},
cfg, cfg,
); );
} }
@@ -106,6 +114,7 @@ export async function handleDiscordMessageAction(
return await handleDiscordAction( return await handleDiscordAction(
{ {
action: "readMessages", action: "readMessages",
accountId: accountIdParam,
channelId: resolveChannelId(), channelId: resolveChannelId(),
limit, limit,
before: readStringParam(params, "before"), before: readStringParam(params, "before"),
@@ -122,6 +131,7 @@ export async function handleDiscordMessageAction(
return await handleDiscordAction( return await handleDiscordAction(
{ {
action: "editMessage", action: "editMessage",
accountId: accountIdParam,
channelId: resolveChannelId(), channelId: resolveChannelId(),
messageId, messageId,
content, content,
@@ -133,7 +143,12 @@ export async function handleDiscordMessageAction(
if (action === "delete") { if (action === "delete") {
const messageId = readStringParam(params, "messageId", { required: true }); const messageId = readStringParam(params, "messageId", { required: true });
return await handleDiscordAction( return await handleDiscordAction(
{ action: "deleteMessage", channelId: resolveChannelId(), messageId }, {
action: "deleteMessage",
accountId: accountIdParam,
channelId: resolveChannelId(),
messageId,
},
cfg, cfg,
); );
} }
@@ -144,6 +159,7 @@ export async function handleDiscordMessageAction(
return await handleDiscordAction( return await handleDiscordAction(
{ {
action: action === "pin" ? "pinMessage" : action === "unpin" ? "unpinMessage" : "listPins", action: action === "pin" ? "pinMessage" : action === "unpin" ? "unpinMessage" : "listPins",
accountId: accountIdParam,
channelId: resolveChannelId(), channelId: resolveChannelId(),
messageId, messageId,
}, },
@@ -152,7 +168,10 @@ export async function handleDiscordMessageAction(
} }
if (action === "permissions") { if (action === "permissions") {
return await handleDiscordAction({ action: "permissions", channelId: resolveChannelId() }, cfg); return await handleDiscordAction(
{ action: "permissions", accountId: accountIdParam, channelId: resolveChannelId() },
cfg,
);
} }
if (action === "thread-create") { if (action === "thread-create") {
@@ -164,6 +183,7 @@ export async function handleDiscordMessageAction(
return await handleDiscordAction( return await handleDiscordAction(
{ {
action: "threadCreate", action: "threadCreate",
accountId: accountIdParam,
channelId: resolveChannelId(), channelId: resolveChannelId(),
name, name,
messageId, messageId,
@@ -182,6 +202,7 @@ export async function handleDiscordMessageAction(
return await handleDiscordAction( return await handleDiscordAction(
{ {
action: "sticker", action: "sticker",
accountId: accountIdParam,
to: readStringParam(params, "to", { required: true }), to: readStringParam(params, "to", { required: true }),
stickerIds, stickerIds,
content: readStringParam(params, "message"), content: readStringParam(params, "message"),