refactor: centralize target errors and cache lookups

This commit is contained in:
Peter Steinberger
2026-01-17 04:28:19 +00:00
parent 3efc5e54fa
commit 5fcc9b3244
20 changed files with 185 additions and 68 deletions

View File

@@ -1,6 +1,7 @@
import { chunkMarkdownText } from "../../../src/auto-reply/chunk.js";
import type { ChannelOutboundAdapter } from "../../../src/channels/plugins/types.js";
import { sendMessageMatrix, sendPollMatrix } from "./matrix/send.js";
import { missingTargetError } from "../../../src/infra/outbound/target-errors.js";
export const matrixOutbound: ChannelOutboundAdapter = {
deliveryMode: "direct",
@@ -11,7 +12,7 @@ export const matrixOutbound: ChannelOutboundAdapter = {
if (!trimmed) {
return {
ok: false,
error: new Error("Delivering to Matrix requires target <room|alias|user>"),
error: missingTargetError("Matrix", "<room|alias|user>"),
};
}
return { ok: true, to: trimmed };

View File

@@ -3,6 +3,7 @@ import type { ChannelOutboundAdapter } from "../../../src/channels/plugins/types
import { createMSTeamsPollStoreFs } from "./polls.js";
import { sendMessageMSTeams, sendPollMSTeams } from "./send.js";
import { missingTargetError } from "../../../src/infra/outbound/target-errors.js";
export const msteamsOutbound: ChannelOutboundAdapter = {
deliveryMode: "direct",
@@ -14,9 +15,7 @@ export const msteamsOutbound: ChannelOutboundAdapter = {
if (!trimmed) {
return {
ok: false,
error: new Error(
"Delivering to MS Teams requires target <conversationId|user:ID|conversation:ID>",
),
error: missingTargetError("MS Teams", "<conversationId|user:ID|conversation:ID>"),
};
}
return { ok: true, to: trimmed };

View File

@@ -21,6 +21,7 @@ import {
import { collectZaloStatusIssues } from "./status-issues.js";
import type { CoreConfig } from "./types.js";
import { DEFAULT_ACCOUNT_ID, normalizeAccountId } from "./shared/account-ids.js";
import { missingTargetError } from "../../../src/infra/outbound/target-errors.js";
const meta = {
id: "zalo",
@@ -185,7 +186,7 @@ export const zaloPlugin: ChannelPlugin<ResolvedZaloAccount> = {
return "ZALO_BOT_TOKEN can only be used for the default account.";
}
if (!input.useEnv && !input.token && !input.tokenFile) {
return "Zalo requires targetken or --token-file (or --use-env).";
return "Zalo requires token or --token-file (or --use-env).";
}
return null;
},
@@ -284,7 +285,7 @@ export const zaloPlugin: ChannelPlugin<ResolvedZaloAccount> = {
if (!trimmed) {
return {
ok: false,
error: new Error("Delivering to Zalo requires target <chatId>"),
error: missingTargetError("Zalo", "<chatId>"),
};
}
return { ok: true, to: trimmed };

View File

@@ -17,6 +17,7 @@ import { zalouserOnboardingAdapter } from "./onboarding.js";
import { sendMessageZalouser } from "./send.js";
import { checkZcaInstalled, parseJsonOutput, runZca, runZcaInteractive } from "./zca.js";
import {
import { missingTargetError } from "../../../src/infra/outbound/target-errors.js";
DEFAULT_ACCOUNT_ID,
type CoreConfig,
type ZalouserConfig,
@@ -378,7 +379,7 @@ export const zalouserPlugin: ChannelPlugin<ResolvedZalouserAccount> = {
if (!trimmed) {
return {
ok: false,
error: new Error("Delivering to Zalouser requires target <threadId>"),
error: missingTargetError("Zalouser", "<threadId>"),
};
}
return { ok: true, to: trimmed };

View File

@@ -35,6 +35,7 @@ import {
} from "./setup-helpers.js";
import { collectDiscordStatusIssues } from "./status-issues/discord.js";
import type { ChannelPlugin } from "./types.js";
import { missingTargetError } from "../../infra/outbound/target-errors.js";
const meta = getChatChannelMeta("discord");
@@ -253,7 +254,7 @@ export const discordPlugin: ChannelPlugin<ResolvedDiscordAccount> = {
return "DISCORD_BOT_TOKEN can only be used for the default account.";
}
if (!input.useEnv && !input.token) {
return "Discord requires targetken (or --use-env).";
return "Discord requires token (or --use-env).";
}
return null;
},
@@ -314,7 +315,7 @@ export const discordPlugin: ChannelPlugin<ResolvedDiscordAccount> = {
if (!trimmed) {
return {
ok: false,
error: new Error("Delivering to Discord requires target <channelId|user:ID|channel:ID>"),
error: missingTargetError("Discord", "<channelId|user:ID|channel:ID>"),
};
}
return { ok: true, to: trimmed };

View File

@@ -25,6 +25,7 @@ import {
migrateBaseNameToDefaultAccount,
} from "./setup-helpers.js";
import type { ChannelPlugin } from "./types.js";
import { missingTargetError } from "../../infra/outbound/target-errors.js";
const meta = getChatChannelMeta("imessage");
@@ -177,7 +178,7 @@ export const imessagePlugin: ChannelPlugin<ResolvedIMessageAccount> = {
if (!trimmed) {
return {
ok: false,
error: new Error("Delivering to iMessage requires target <handle|chat_id:ID>"),
error: missingTargetError("iMessage", "<handle|chat_id:ID>"),
};
}
return { ok: true, to: trimmed };

View File

@@ -1,5 +1,6 @@
import { sendMessageDiscord, sendPollDiscord } from "../../../discord/send.js";
import type { ChannelOutboundAdapter } from "../types.js";
import { missingTargetError } from "../../../infra/outbound/target-errors.js";
export const discordOutbound: ChannelOutboundAdapter = {
deliveryMode: "direct",
@@ -11,7 +12,7 @@ export const discordOutbound: ChannelOutboundAdapter = {
if (!trimmed) {
return {
ok: false,
error: new Error("Delivering to Discord requires target <channelId|user:ID|channel:ID>"),
error: missingTargetError("Discord", "<channelId|user:ID|channel:ID>"),
};
}
return { ok: true, to: trimmed };

View File

@@ -2,6 +2,7 @@ import { chunkText } from "../../../auto-reply/chunk.js";
import { sendMessageIMessage } from "../../../imessage/send.js";
import { resolveChannelMediaMaxBytes } from "../media-limits.js";
import type { ChannelOutboundAdapter } from "../types.js";
import { missingTargetError } from "../../../infra/outbound/target-errors.js";
export const imessageOutbound: ChannelOutboundAdapter = {
deliveryMode: "direct",
@@ -12,7 +13,7 @@ export const imessageOutbound: ChannelOutboundAdapter = {
if (!trimmed) {
return {
ok: false,
error: new Error("Delivering to iMessage requires target <handle|chat_id:ID>"),
error: missingTargetError("iMessage", "<handle|chat_id:ID>"),
};
}
return { ok: true, to: trimmed };

View File

@@ -2,6 +2,7 @@ import { chunkText } from "../../../auto-reply/chunk.js";
import { sendMessageSignal } from "../../../signal/send.js";
import { resolveChannelMediaMaxBytes } from "../media-limits.js";
import type { ChannelOutboundAdapter } from "../types.js";
import { missingTargetError } from "../../../infra/outbound/target-errors.js";
export const signalOutbound: ChannelOutboundAdapter = {
deliveryMode: "direct",
@@ -12,9 +13,7 @@ export const signalOutbound: ChannelOutboundAdapter = {
if (!trimmed) {
return {
ok: false,
error: new Error(
"Delivering to Signal requires target <E.164|group:ID|signal:group:ID|signal:+E.164>",
),
error: missingTargetError("Signal", "<E.164|group:ID|signal:group:ID|signal:+E.164>"),
};
}
return { ok: true, to: trimmed };

View File

@@ -1,5 +1,6 @@
import { sendMessageSlack } from "../../../slack/send.js";
import type { ChannelOutboundAdapter } from "../types.js";
import { missingTargetError } from "../../../infra/outbound/target-errors.js";
export const slackOutbound: ChannelOutboundAdapter = {
deliveryMode: "direct",
@@ -10,7 +11,7 @@ export const slackOutbound: ChannelOutboundAdapter = {
if (!trimmed) {
return {
ok: false,
error: new Error("Delivering to Slack requires target <channelId|user:ID|channel:ID>"),
error: missingTargetError("Slack", "<channelId|user:ID|channel:ID>"),
};
}
return { ok: true, to: trimmed };

View File

@@ -1,6 +1,7 @@
import { markdownToTelegramHtmlChunks } from "../../../telegram/format.js";
import { sendMessageTelegram } from "../../../telegram/send.js";
import type { ChannelOutboundAdapter } from "../types.js";
import { missingTargetError } from "../../../infra/outbound/target-errors.js";
function parseReplyToMessageId(replyToId?: string | null) {
if (!replyToId) return undefined;
@@ -27,7 +28,7 @@ export const telegramOutbound: ChannelOutboundAdapter = {
if (!trimmed) {
return {
ok: false,
error: new Error("Delivering to Telegram requires target <chatId>"),
error: missingTargetError("Telegram", "<chatId>"),
};
}
return { ok: true, to: trimmed };

View File

@@ -3,6 +3,7 @@ import { shouldLogVerbose } from "../../../globals.js";
import { sendMessageWhatsApp, sendPollWhatsApp } from "../../../web/outbound.js";
import { isWhatsAppGroupJid, normalizeWhatsAppTarget } from "../../../whatsapp/normalize.js";
import type { ChannelOutboundAdapter } from "../types.js";
import { missingTargetError } from "../../../infra/outbound/target-errors.js";
export const whatsappOutbound: ChannelOutboundAdapter = {
deliveryMode: "gateway",
@@ -26,8 +27,9 @@ export const whatsappOutbound: ChannelOutboundAdapter = {
}
return {
ok: false,
error: new Error(
"Delivering to WhatsApp requires target <E.164|group JID> or channels.whatsapp.allowFrom[0]",
error: missingTargetError(
"WhatsApp",
"<E.164|group JID> or channels.whatsapp.allowFrom[0]",
),
};
}
@@ -51,8 +53,9 @@ export const whatsappOutbound: ChannelOutboundAdapter = {
}
return {
ok: false,
error: new Error(
"Delivering to WhatsApp requires target <E.164|group JID> or channels.whatsapp.allowFrom[0]",
error: missingTargetError(
"WhatsApp",
"<E.164|group JID> or channels.whatsapp.allowFrom[0]",
),
};
},

View File

@@ -26,6 +26,7 @@ import {
migrateBaseNameToDefaultAccount,
} from "./setup-helpers.js";
import type { ChannelPlugin } from "./types.js";
import { missingTargetError } from "../../infra/outbound/target-errors.js";
const meta = getChatChannelMeta("signal");
@@ -201,8 +202,9 @@ export const signalPlugin: ChannelPlugin<ResolvedSignalAccount> = {
if (!trimmed) {
return {
ok: false,
error: new Error(
"Delivering to Signal requires target <E.164|group:ID|signal:group:ID|signal:+E.164>",
error: missingTargetError(
"Signal",
"<E.164|group:ID|signal:group:ID|signal:+E.164>",
),
};
}

View File

@@ -28,6 +28,7 @@ import {
migrateBaseNameToDefaultAccount,
} from "./setup-helpers.js";
import type { ChannelMessageActionName, ChannelPlugin } from "./types.js";
import { missingTargetError } from "../../infra/outbound/target-errors.js";
const meta = getChatChannelMeta("slack");
@@ -497,7 +498,7 @@ export const slackPlugin: ChannelPlugin<ResolvedSlackAccount> = {
if (!trimmed) {
return {
ok: false,
error: new Error("Delivering to Slack requires target <channelId|user:ID|channel:ID>"),
error: missingTargetError("Slack", "<channelId|user:ID|channel:ID>"),
};
}
return { ok: true, to: trimmed };

View File

@@ -35,6 +35,7 @@ import {
} from "./setup-helpers.js";
import { collectTelegramStatusIssues } from "./status-issues/telegram.js";
import type { ChannelPlugin } from "./types.js";
import { missingTargetError } from "../../infra/outbound/target-errors.js";
const meta = getChatChannelMeta("telegram");
@@ -215,7 +216,7 @@ export const telegramPlugin: ChannelPlugin<ResolvedTelegramAccount> = {
return "TELEGRAM_BOT_TOKEN can only be used for the default account.";
}
if (!input.useEnv && !input.token && !input.tokenFile) {
return "Telegram requires targetken or --token-file (or --use-env).";
return "Telegram requires token or --token-file (or --use-env).";
}
return null;
},
@@ -285,7 +286,7 @@ export const telegramPlugin: ChannelPlugin<ResolvedTelegramAccount> = {
if (!trimmed) {
return {
ok: false,
error: new Error("Delivering to Telegram requires target <chatId>"),
error: missingTargetError("Telegram", "<chatId>"),
};
}
return { ok: true, to: trimmed };

View File

@@ -35,6 +35,7 @@ import {
import { collectWhatsAppStatusIssues } from "./status-issues/whatsapp.js";
import type { ChannelMessageActionName, ChannelPlugin } from "./types.js";
import { resolveWhatsAppHeartbeatRecipients } from "./whatsapp-heartbeat.js";
import { missingTargetError } from "../../infra/outbound/target-errors.js";
const meta = getChatChannelMeta("whatsapp");
@@ -315,8 +316,9 @@ export const whatsappPlugin: ChannelPlugin<ResolvedWhatsAppAccount> = {
}
return {
ok: false,
error: new Error(
"Delivering to WhatsApp requires target <E.164|group JID> or channels.whatsapp.allowFrom[0]",
error: missingTargetError(
"WhatsApp",
"<E.164|group JID> or channels.whatsapp.allowFrom[0]",
),
};
}
@@ -340,9 +342,7 @@ export const whatsappPlugin: ChannelPlugin<ResolvedWhatsAppAccount> = {
}
return {
ok: false,
error: new Error(
"Delivering to WhatsApp requires target <E.164|group JID> or channels.whatsapp.allowFrom[0]",
),
error: missingTargetError("WhatsApp", "<E.164|group JID> or channels.whatsapp.allowFrom[0]"),
};
},
sendText: async ({ to, text, accountId, deps, gifPlayback }) => {

View File

@@ -150,6 +150,36 @@ function applyCrossContextMessageDecoration({
return applied.message;
}
async function maybeApplyCrossContextMarker(params: {
cfg: ClawdbotConfig;
channel: ChannelId;
action: ChannelMessageActionName;
target: string;
toolContext?: ChannelThreadingToolContext;
accountId?: string | null;
args: Record<string, unknown>;
message: string;
preferEmbeds: boolean;
}): Promise<string> {
if (!shouldApplyCrossContextMarker(params.action) || !params.toolContext) {
return params.message;
}
const decoration = await buildCrossContextDecoration({
cfg: params.cfg,
channel: params.channel,
target: params.target,
toolContext: params.toolContext,
accountId: params.accountId ?? undefined,
});
if (!decoration) return params.message;
return applyCrossContextMessageDecoration({
params: params.args,
message: params.message,
decoration,
preferEmbeds: params.preferEmbeds,
});
}
function readBooleanParam(params: Record<string, unknown>, key: string): boolean | undefined {
const raw = params[key];
if (typeof raw === "boolean") return raw;
@@ -339,24 +369,17 @@ async function handleSendAction(ctx: ResolvedActionContext): Promise<MessageActi
params.media = parsed.mediaUrls?.[0] || parsed.mediaUrl || undefined;
}
const decoration =
shouldApplyCrossContextMarker(action) && input.toolContext
? await buildCrossContextDecoration({
cfg,
channel,
target: to,
toolContext: input.toolContext,
accountId: accountId ?? undefined,
})
: null;
if (decoration) {
message = applyCrossContextMessageDecoration({
params,
message,
decoration,
preferEmbeds: true,
});
}
message = await maybeApplyCrossContextMarker({
cfg,
channel,
action,
target: to,
toolContext: input.toolContext,
accountId,
args: params,
message,
preferEmbeds: true,
});
const mediaUrl = readStringParam(params, "media", { trim: false });
const gifPlayback = readBooleanParam(params, "gifPlayback") ?? false;
@@ -415,25 +438,18 @@ async function handlePollAction(ctx: ResolvedActionContext): Promise<MessageActi
integer: true,
});
const maxSelections = allowMultiselect ? Math.max(2, options.length) : 1;
const decoration =
shouldApplyCrossContextMarker(action) && input.toolContext
? await buildCrossContextDecoration({
cfg,
channel,
target: to,
toolContext: input.toolContext,
accountId: accountId ?? undefined,
})
: null;
if (decoration) {
const base = typeof params.message === "string" ? params.message : "";
applyCrossContextMessageDecoration({
params,
message: base,
decoration,
preferEmbeds: true,
});
}
const base = typeof params.message === "string" ? params.message : "";
await maybeApplyCrossContextMarker({
cfg,
channel,
action,
target: to,
toolContext: input.toolContext,
accountId,
args: params,
message: base,
preferEmbeds: true,
});
const poll = await executePollAction({
ctx: {

View File

@@ -0,0 +1,8 @@
export function missingTargetMessage(provider: string, hint?: string): string {
const suffix = hint ? ` ${hint}` : "";
return `Delivering to ${provider} requires target${suffix}`;
}
export function missingTargetError(provider: string, hint?: string): Error {
return new Error(missingTargetMessage(provider, hint));
}

View File

@@ -0,0 +1,78 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { ChannelDirectoryEntry } from "../../channels/plugins/types.js";
import type { ClawdbotConfig } from "../../config/config.js";
import { resetDirectoryCache, resolveMessagingTarget } from "./target-resolver.js";
const mocks = vi.hoisted(() => ({
listGroups: vi.fn(),
listGroupsLive: vi.fn(),
getChannelPlugin: vi.fn(),
}));
vi.mock("../../channels/plugins/index.js", () => ({
getChannelPlugin: (...args: unknown[]) => mocks.getChannelPlugin(...args),
}));
describe("resolveMessagingTarget (directory fallback)", () => {
const cfg = {} as ClawdbotConfig;
beforeEach(() => {
mocks.listGroups.mockReset();
mocks.listGroupsLive.mockReset();
mocks.getChannelPlugin.mockReset();
resetDirectoryCache();
mocks.getChannelPlugin.mockReturnValue({
directory: {
listGroups: mocks.listGroups,
listGroupsLive: mocks.listGroupsLive,
},
});
});
it("uses live directory fallback and caches the result", async () => {
const entry: ChannelDirectoryEntry = { id: "123456789", name: "support" };
mocks.listGroups.mockResolvedValue([]);
mocks.listGroupsLive.mockResolvedValue([entry]);
const first = await resolveMessagingTarget({
cfg,
channel: "discord",
input: "support",
});
expect(first.ok).toBe(true);
if (first.ok) {
expect(first.target.source).toBe("directory");
expect(first.target.to).toBe("123456789");
}
expect(mocks.listGroups).toHaveBeenCalledTimes(1);
expect(mocks.listGroupsLive).toHaveBeenCalledTimes(1);
const second = await resolveMessagingTarget({
cfg,
channel: "discord",
input: "support",
});
expect(second.ok).toBe(true);
expect(mocks.listGroups).toHaveBeenCalledTimes(1);
expect(mocks.listGroupsLive).toHaveBeenCalledTimes(1);
});
it("skips directory lookup for direct ids", async () => {
const result = await resolveMessagingTarget({
cfg,
channel: "discord",
input: "123456789",
});
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.target.source).toBe("normalized");
expect(result.target.to).toBe("123456789");
}
expect(mocks.listGroups).not.toHaveBeenCalled();
expect(mocks.listGroupsLive).not.toHaveBeenCalled();
});
});

View File

@@ -227,6 +227,7 @@ async function getDirectoryEntries(params: {
source: "live",
});
directoryCache.set(liveKey, liveEntries, params.cfg);
directoryCache.set(cacheKey, liveEntries, params.cfg);
return liveEntries;
}