refactor: unify outbound delivery

This commit is contained in:
Peter Steinberger
2026-01-07 01:13:04 +00:00
parent 1ae5e9a26b
commit f5938f8114
9 changed files with 587 additions and 541 deletions

View File

@@ -0,0 +1,108 @@
import { describe, expect, it, vi } from "vitest";
import type { ClawdbotConfig } from "../../config/config.js";
import { deliverOutboundPayloads } from "./deliver.js";
describe("deliverOutboundPayloads", () => {
it("chunks telegram markdown and passes config token", async () => {
const sendTelegram = vi
.fn()
.mockResolvedValue({ messageId: "m1", chatId: "c1" });
const cfg: ClawdbotConfig = {
telegram: { botToken: "tok-1", textChunkLimit: 2 },
};
const prevTelegramToken = process.env.TELEGRAM_BOT_TOKEN;
process.env.TELEGRAM_BOT_TOKEN = "";
try {
const results = await deliverOutboundPayloads({
cfg,
provider: "telegram",
to: "123",
payloads: [{ text: "abcd" }],
deps: { sendTelegram },
});
expect(sendTelegram).toHaveBeenCalledTimes(2);
for (const call of sendTelegram.mock.calls) {
expect(call[2]).toEqual(
expect.objectContaining({ token: "tok-1", verbose: false }),
);
}
expect(results).toHaveLength(2);
expect(results[0]).toMatchObject({ provider: "telegram", chatId: "c1" });
} finally {
if (prevTelegramToken === undefined) {
delete process.env.TELEGRAM_BOT_TOKEN;
} else {
process.env.TELEGRAM_BOT_TOKEN = prevTelegramToken;
}
}
});
it("uses signal media maxBytes from config", async () => {
const sendSignal = vi
.fn()
.mockResolvedValue({ messageId: "s1", timestamp: 123 });
const cfg: ClawdbotConfig = { signal: { mediaMaxMb: 2 } };
const results = await deliverOutboundPayloads({
cfg,
provider: "signal",
to: "+1555",
payloads: [{ text: "hi", mediaUrl: "https://x.test/a.jpg" }],
deps: { sendSignal },
});
expect(sendSignal).toHaveBeenCalledWith(
"+1555",
"hi",
expect.objectContaining({
mediaUrl: "https://x.test/a.jpg",
maxBytes: 2 * 1024 * 1024,
}),
);
expect(results[0]).toMatchObject({ provider: "signal", messageId: "s1" });
});
it("chunks WhatsApp text and returns all results", async () => {
const sendWhatsApp = vi
.fn()
.mockResolvedValueOnce({ messageId: "w1", toJid: "jid" })
.mockResolvedValueOnce({ messageId: "w2", toJid: "jid" });
const cfg: ClawdbotConfig = {
whatsapp: { textChunkLimit: 2 },
};
const results = await deliverOutboundPayloads({
cfg,
provider: "whatsapp",
to: "+1555",
payloads: [{ text: "abcd" }],
deps: { sendWhatsApp },
});
expect(sendWhatsApp).toHaveBeenCalledTimes(2);
expect(results.map((r) => r.messageId)).toEqual(["w1", "w2"]);
});
it("uses iMessage media maxBytes from agent fallback", async () => {
const sendIMessage = vi
.fn()
.mockResolvedValue({ messageId: "i1" });
const cfg: ClawdbotConfig = { agent: { mediaMaxMb: 3 } };
await deliverOutboundPayloads({
cfg,
provider: "imessage",
to: "chat_id:42",
payloads: [{ text: "hello" }],
deps: { sendIMessage },
});
expect(sendIMessage).toHaveBeenCalledWith(
"chat_id:42",
"hello",
expect.objectContaining({ maxBytes: 3 * 1024 * 1024 }),
);
});
});

View File

@@ -0,0 +1,200 @@
import {
chunkMarkdownText,
chunkText,
resolveTextChunkLimit,
} from "../../auto-reply/chunk.js";
import type { ReplyPayload } from "../../auto-reply/types.js";
import type { ClawdbotConfig } from "../../config/config.js";
import { sendMessageDiscord } from "../../discord/send.js";
import { sendMessageIMessage } from "../../imessage/send.js";
import { sendMessageSignal } from "../../signal/send.js";
import { sendMessageSlack } from "../../slack/send.js";
import { sendMessageTelegram } from "../../telegram/send.js";
import { resolveTelegramToken } from "../../telegram/token.js";
import { sendMessageWhatsApp } from "../../web/outbound.js";
import type { OutboundProvider } from "./targets.js";
const MB = 1024 * 1024;
export type OutboundSendDeps = {
sendWhatsApp?: typeof sendMessageWhatsApp;
sendTelegram?: typeof sendMessageTelegram;
sendDiscord?: typeof sendMessageDiscord;
sendSlack?: typeof sendMessageSlack;
sendSignal?: typeof sendMessageSignal;
sendIMessage?: typeof sendMessageIMessage;
};
export type OutboundDeliveryResult =
| { provider: "whatsapp"; messageId: string; toJid: string }
| { provider: "telegram"; messageId: string; chatId: string }
| { provider: "discord"; messageId: string; channelId: string }
| { provider: "slack"; messageId: string; channelId: string }
| { provider: "signal"; messageId: string; timestamp?: number }
| { provider: "imessage"; messageId: string };
type Chunker = (text: string, limit: number) => string[];
function resolveChunker(provider: OutboundProvider): Chunker | null {
if (provider === "telegram") return chunkMarkdownText;
if (provider === "whatsapp") return chunkText;
if (provider === "signal") return chunkText;
if (provider === "imessage") return chunkText;
return null;
}
function resolveSignalMaxBytes(cfg: ClawdbotConfig): number | undefined {
if (cfg.signal?.mediaMaxMb) return cfg.signal.mediaMaxMb * MB;
if (cfg.agent?.mediaMaxMb) return cfg.agent.mediaMaxMb * MB;
return undefined;
}
function resolveIMessageMaxBytes(cfg: ClawdbotConfig): number | undefined {
if (cfg.imessage?.mediaMaxMb) return cfg.imessage.mediaMaxMb * MB;
if (cfg.agent?.mediaMaxMb) return cfg.agent.mediaMaxMb * MB;
return undefined;
}
function normalizeMediaUrls(payload: ReplyPayload): string[] {
return payload.mediaUrls ?? (payload.mediaUrl ? [payload.mediaUrl] : []);
}
export async function deliverOutboundPayloads(params: {
cfg: ClawdbotConfig;
provider: Exclude<OutboundProvider, "none">;
to: string;
payloads: ReplyPayload[];
deps?: OutboundSendDeps;
}): Promise<OutboundDeliveryResult[]> {
const { cfg, provider, to, payloads } = params;
const deps = {
sendWhatsApp: params.deps?.sendWhatsApp ?? sendMessageWhatsApp,
sendTelegram: params.deps?.sendTelegram ?? sendMessageTelegram,
sendDiscord: params.deps?.sendDiscord ?? sendMessageDiscord,
sendSlack: params.deps?.sendSlack ?? sendMessageSlack,
sendSignal: params.deps?.sendSignal ?? sendMessageSignal,
sendIMessage: params.deps?.sendIMessage ?? sendMessageIMessage,
};
const results: OutboundDeliveryResult[] = [];
const chunker = resolveChunker(provider);
const textLimit = chunker ? resolveTextChunkLimit(cfg, provider) : undefined;
const telegramToken =
provider === "telegram"
? resolveTelegramToken(cfg).token || undefined
: undefined;
const signalMaxBytes =
provider === "signal" ? resolveSignalMaxBytes(cfg) : undefined;
const imessageMaxBytes =
provider === "imessage" ? resolveIMessageMaxBytes(cfg) : undefined;
const sendTextChunks = async (text: string) => {
if (!chunker || textLimit === undefined) {
await sendText(text);
return;
}
for (const chunk of chunker(text, textLimit)) {
await sendText(chunk);
}
};
const sendText = async (text: string) => {
if (provider === "whatsapp") {
const res = await deps.sendWhatsApp(to, text, { verbose: false });
results.push({ provider: "whatsapp", ...res });
return;
}
if (provider === "telegram") {
const res = await deps.sendTelegram(to, text, {
verbose: false,
token: telegramToken,
});
results.push({ provider: "telegram", ...res });
return;
}
if (provider === "signal") {
const res = await deps.sendSignal(to, text, { maxBytes: signalMaxBytes });
results.push({ provider: "signal", ...res });
return;
}
if (provider === "imessage") {
const res = await deps.sendIMessage(to, text, {
maxBytes: imessageMaxBytes,
});
results.push({ provider: "imessage", ...res });
return;
}
if (provider === "slack") {
const res = await deps.sendSlack(to, text);
results.push({ provider: "slack", ...res });
return;
}
const res = await deps.sendDiscord(to, text, { verbose: false });
results.push({ provider: "discord", ...res });
};
const sendMedia = async (caption: string, mediaUrl: string) => {
if (provider === "whatsapp") {
const res = await deps.sendWhatsApp(to, caption, {
verbose: false,
mediaUrl,
});
results.push({ provider: "whatsapp", ...res });
return;
}
if (provider === "telegram") {
const res = await deps.sendTelegram(to, caption, {
verbose: false,
mediaUrl,
token: telegramToken,
});
results.push({ provider: "telegram", ...res });
return;
}
if (provider === "signal") {
const res = await deps.sendSignal(to, caption, {
mediaUrl,
maxBytes: signalMaxBytes,
});
results.push({ provider: "signal", ...res });
return;
}
if (provider === "imessage") {
const res = await deps.sendIMessage(to, caption, {
mediaUrl,
maxBytes: imessageMaxBytes,
});
results.push({ provider: "imessage", ...res });
return;
}
if (provider === "slack") {
const res = await deps.sendSlack(to, caption, { mediaUrl });
results.push({ provider: "slack", ...res });
return;
}
const res = await deps.sendDiscord(to, caption, {
verbose: false,
mediaUrl,
});
results.push({ provider: "discord", ...res });
};
for (const payload of payloads) {
const text = payload.text ?? "";
const mediaUrls = normalizeMediaUrls(payload);
if (!text && mediaUrls.length === 0) continue;
if (mediaUrls.length === 0) {
await sendTextChunks(text);
continue;
}
let first = true;
for (const url of mediaUrls) {
const caption = first ? text : "";
first = false;
await sendMedia(caption, url);
}
}
return results;
}

View File

@@ -0,0 +1,97 @@
import type { ClawdbotConfig } from "../../config/config.js";
import type { SessionEntry } from "../../config/sessions.js";
import { normalizeE164 } from "../../utils.js";
export type OutboundProvider =
| "whatsapp"
| "telegram"
| "discord"
| "slack"
| "signal"
| "imessage"
| "none";
export type HeartbeatTarget = OutboundProvider | "last";
export type OutboundTarget = {
provider: OutboundProvider;
to?: string;
reason?: string;
};
export function resolveHeartbeatDeliveryTarget(params: {
cfg: ClawdbotConfig;
entry?: SessionEntry;
}): OutboundTarget {
const { cfg, entry } = params;
const rawTarget = cfg.agent?.heartbeat?.target;
const target: HeartbeatTarget =
rawTarget === "whatsapp" ||
rawTarget === "telegram" ||
rawTarget === "discord" ||
rawTarget === "slack" ||
rawTarget === "signal" ||
rawTarget === "imessage" ||
rawTarget === "none" ||
rawTarget === "last"
? rawTarget
: "last";
if (target === "none") {
return { provider: "none", reason: "target-none" };
}
const explicitTo =
typeof cfg.agent?.heartbeat?.to === "string" &&
cfg.agent.heartbeat.to.trim()
? cfg.agent.heartbeat.to.trim()
: undefined;
const lastProvider =
entry?.lastProvider && entry.lastProvider !== "webchat"
? entry.lastProvider
: undefined;
const lastTo = typeof entry?.lastTo === "string" ? entry.lastTo.trim() : "";
const provider:
| "whatsapp"
| "telegram"
| "discord"
| "slack"
| "signal"
| "imessage"
| undefined =
target === "last"
? lastProvider
: target === "whatsapp" ||
target === "telegram" ||
target === "discord" ||
target === "slack" ||
target === "signal" ||
target === "imessage"
? target
: undefined;
const to =
explicitTo ||
(provider && lastProvider === provider ? lastTo : undefined) ||
(target === "last" ? lastTo : undefined);
if (!provider || !to) {
return { provider: "none", reason: "no-target" };
}
if (provider !== "whatsapp") {
return { provider, to };
}
const rawAllow = cfg.whatsapp?.allowFrom ?? [];
if (rawAllow.includes("*")) return { provider, to };
const allowFrom = rawAllow
.map((val) => normalizeE164(val))
.filter((val) => val.length > 1);
if (allowFrom.length === 0) return { provider, to };
const normalized = normalizeE164(to);
if (allowFrom.includes(normalized)) return { provider, to: normalized };
return { provider, to: allowFrom[0], reason: "allowFrom-fallback" };
}