feat(telegram): wire replyToMode config, add forum topic support, fix messaging tool duplicates
Changes: - Default replyToMode from "off" to "first" for better threading UX - Add messageThreadId and replyToMessageId params for forum topic support - Add messaging tool duplicate detection to suppress redundant block replies - Add sendMessage action to telegram tool schema - Add @grammyjs/types devDependency for proper TypeScript typing - Remove @ts-nocheck and fix all type errors in send.ts - Add comprehensive docs/telegram.md documentation - Add PR-326-REVIEW.md with John Carmack-level code review Test coverage: - normalizeTextForComparison: 5 cases - isMessagingToolDuplicate: 7 cases - sendMessageTelegram thread params: 5 cases - handleTelegramAction sendMessage: 4 cases - Forum topic isolation: 4 cases 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
committed by
Peter Steinberger
parent
6cd32ec7f6
commit
33e2d53be3
@@ -5,6 +5,8 @@ import {
|
||||
buildBootstrapContextFiles,
|
||||
formatAssistantErrorText,
|
||||
isContextOverflowError,
|
||||
isMessagingToolDuplicate,
|
||||
normalizeTextForComparison,
|
||||
sanitizeGoogleTurnOrdering,
|
||||
validateGeminiTurns,
|
||||
} from "./pi-embedded-helpers.js";
|
||||
@@ -247,3 +249,86 @@ describe("sanitizeGoogleTurnOrdering", () => {
|
||||
expect(out).toBe(input);
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeTextForComparison", () => {
|
||||
it("lowercases text", () => {
|
||||
expect(normalizeTextForComparison("Hello World")).toBe("hello world");
|
||||
});
|
||||
|
||||
it("trims whitespace", () => {
|
||||
expect(normalizeTextForComparison(" hello ")).toBe("hello");
|
||||
});
|
||||
|
||||
it("collapses multiple spaces", () => {
|
||||
expect(normalizeTextForComparison("hello world")).toBe("hello world");
|
||||
});
|
||||
|
||||
it("strips emoji", () => {
|
||||
expect(normalizeTextForComparison("Hello 👋 World 🌍")).toBe("hello world");
|
||||
});
|
||||
|
||||
it("handles mixed normalization", () => {
|
||||
expect(normalizeTextForComparison(" Hello 👋 WORLD 🌍 ")).toBe(
|
||||
"hello world",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isMessagingToolDuplicate", () => {
|
||||
it("returns false for empty sentTexts", () => {
|
||||
expect(isMessagingToolDuplicate("hello world", [])).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false for short texts", () => {
|
||||
expect(isMessagingToolDuplicate("short", ["short"])).toBe(false);
|
||||
});
|
||||
|
||||
it("detects exact duplicates", () => {
|
||||
expect(
|
||||
isMessagingToolDuplicate("Hello, this is a test message!", [
|
||||
"Hello, this is a test message!",
|
||||
]),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("detects duplicates with different casing", () => {
|
||||
expect(
|
||||
isMessagingToolDuplicate("HELLO, THIS IS A TEST MESSAGE!", [
|
||||
"hello, this is a test message!",
|
||||
]),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("detects duplicates with emoji variations", () => {
|
||||
expect(
|
||||
isMessagingToolDuplicate("Hello! 👋 This is a test message!", [
|
||||
"Hello! This is a test message!",
|
||||
]),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("detects substring duplicates (LLM elaboration)", () => {
|
||||
expect(
|
||||
isMessagingToolDuplicate(
|
||||
'I sent the message: "Hello, this is a test message!"',
|
||||
["Hello, this is a test message!"],
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("detects when sent text contains block reply (reverse substring)", () => {
|
||||
expect(
|
||||
isMessagingToolDuplicate("Hello, this is a test message!", [
|
||||
'I sent the message: "Hello, this is a test message!"',
|
||||
]),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false for non-matching texts", () => {
|
||||
expect(
|
||||
isMessagingToolDuplicate("This is completely different content.", [
|
||||
"Hello, this is a test message!",
|
||||
]),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -346,3 +346,50 @@ export function validateGeminiTurns(messages: AgentMessage[]): AgentMessage[] {
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// ── Messaging tool duplicate detection ──────────────────────────────────────
|
||||
// When the agent uses a messaging tool (telegram, discord, slack, sessions_send)
|
||||
// to send a message, we track the text so we can suppress duplicate block replies.
|
||||
// The LLM sometimes elaborates or wraps the same content, so we use substring matching.
|
||||
|
||||
const MIN_DUPLICATE_TEXT_LENGTH = 10;
|
||||
|
||||
/**
|
||||
* Normalize text for duplicate comparison.
|
||||
* - Trims whitespace
|
||||
* - Lowercases
|
||||
* - Strips emoji (Emoji_Presentation and Extended_Pictographic)
|
||||
* - Collapses multiple spaces to single space
|
||||
*/
|
||||
export function normalizeTextForComparison(text: string): string {
|
||||
return text
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/\p{Emoji_Presentation}|\p{Extended_Pictographic}/gu, "")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a text is a duplicate of any previously sent messaging tool text.
|
||||
* Uses substring matching to handle LLM elaboration (e.g., wrapping in quotes,
|
||||
* adding context, or slight rephrasing that includes the original).
|
||||
*/
|
||||
export function isMessagingToolDuplicate(
|
||||
text: string,
|
||||
sentTexts: string[],
|
||||
): boolean {
|
||||
if (sentTexts.length === 0) return false;
|
||||
const normalized = normalizeTextForComparison(text);
|
||||
if (!normalized || normalized.length < MIN_DUPLICATE_TEXT_LENGTH)
|
||||
return false;
|
||||
return sentTexts.some((sent) => {
|
||||
const normalizedSent = normalizeTextForComparison(sent);
|
||||
if (!normalizedSent || normalizedSent.length < MIN_DUPLICATE_TEXT_LENGTH)
|
||||
return false;
|
||||
// Substring match: either text contains the other
|
||||
return (
|
||||
normalized.includes(normalizedSent) || normalizedSent.includes(normalized)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -223,6 +223,9 @@ export type EmbeddedPiRunResult = {
|
||||
isError?: boolean;
|
||||
}>;
|
||||
meta: EmbeddedPiRunMeta;
|
||||
// True if a messaging tool (telegram, whatsapp, discord, slack, sessions_send)
|
||||
// successfully sent a message. Used to suppress agent's confirmation text.
|
||||
didSendViaMessagingTool?: boolean;
|
||||
};
|
||||
|
||||
export type EmbeddedPiCompactResult = {
|
||||
@@ -1250,6 +1253,7 @@ export async function runEmbeddedPiAgent(params: {
|
||||
toolMetas,
|
||||
unsubscribe,
|
||||
waitForCompactionRetry,
|
||||
didSendViaMessagingTool,
|
||||
} = subscription;
|
||||
|
||||
const queueHandle: EmbeddedPiQueueHandle = {
|
||||
@@ -1531,6 +1535,7 @@ export async function runEmbeddedPiAgent(params: {
|
||||
agentMeta,
|
||||
aborted,
|
||||
},
|
||||
didSendViaMessagingTool: didSendViaMessagingTool(),
|
||||
};
|
||||
} finally {
|
||||
restoreSkillEnv?.();
|
||||
|
||||
@@ -8,6 +8,7 @@ import { createSubsystemLogger } from "../logging.js";
|
||||
import { splitMediaFromOutput } from "../media/parse.js";
|
||||
import type { BlockReplyChunking } from "./pi-embedded-block-chunker.js";
|
||||
import { EmbeddedBlockChunker } from "./pi-embedded-block-chunker.js";
|
||||
import { isMessagingToolDuplicate } from "./pi-embedded-helpers.js";
|
||||
import {
|
||||
extractAssistantText,
|
||||
extractAssistantThinking,
|
||||
@@ -137,6 +138,21 @@ export function subscribeEmbeddedPiSession(params: {
|
||||
let compactionRetryPromise: Promise<void> | null = null;
|
||||
let lastReasoningSent: string | undefined;
|
||||
|
||||
// ── Messaging tool duplicate detection ──────────────────────────────────────
|
||||
// Track texts sent via messaging tools to suppress duplicate block replies.
|
||||
// Only committed (successful) texts are checked - pending texts are tracked
|
||||
// to support commit logic but not used for suppression (avoiding lost messages on tool failure).
|
||||
// These tools can send messages via sendMessage/threadReply actions (or sessions_send with message).
|
||||
const MESSAGING_TOOLS = new Set([
|
||||
"telegram",
|
||||
"whatsapp",
|
||||
"discord",
|
||||
"slack",
|
||||
"sessions_send",
|
||||
]);
|
||||
const messagingToolSentTexts: string[] = [];
|
||||
const pendingMessagingTexts = new Map<string, string>();
|
||||
|
||||
const ensureCompactionPromise = () => {
|
||||
if (!compactionRetryPromise) {
|
||||
compactionRetryPromise = new Promise((resolve) => {
|
||||
@@ -221,6 +237,16 @@ export function subscribeEmbeddedPiSession(params: {
|
||||
const chunk = strippedText.trimEnd();
|
||||
if (!chunk) return;
|
||||
if (chunk === lastBlockReplyText) return;
|
||||
|
||||
// Only check committed (successful) messaging tool texts - checking pending texts
|
||||
// is risky because if the tool fails after suppression, the user gets no response
|
||||
if (isMessagingToolDuplicate(chunk, messagingToolSentTexts)) {
|
||||
log.debug(
|
||||
`Skipping block reply - already sent via messaging tool: ${chunk.slice(0, 50)}...`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
lastBlockReplyText = chunk;
|
||||
assistantTexts.push(chunk);
|
||||
if (!params.onBlockReply) return;
|
||||
@@ -288,6 +314,8 @@ export function subscribeEmbeddedPiSession(params: {
|
||||
toolMetas.length = 0;
|
||||
toolMetaById.clear();
|
||||
toolSummaryById.clear();
|
||||
messagingToolSentTexts.length = 0;
|
||||
pendingMessagingTexts.clear();
|
||||
deltaBuffer = "";
|
||||
blockBuffer = "";
|
||||
blockChunker?.reset();
|
||||
@@ -355,6 +383,32 @@ export function subscribeEmbeddedPiSession(params: {
|
||||
toolSummaryById.add(toolCallId);
|
||||
emitToolSummary(toolName, meta);
|
||||
}
|
||||
|
||||
// Track messaging tool sends (pending until confirmed in tool_execution_end)
|
||||
if (MESSAGING_TOOLS.has(toolName)) {
|
||||
const argsRecord =
|
||||
args && typeof args === "object"
|
||||
? (args as Record<string, unknown>)
|
||||
: {};
|
||||
const action =
|
||||
typeof argsRecord.action === "string" ? argsRecord.action : "";
|
||||
// Track send actions: sendMessage/threadReply for Discord/Slack, or sessions_send (no action field)
|
||||
if (
|
||||
action === "sendMessage" ||
|
||||
action === "threadReply" ||
|
||||
toolName === "sessions_send"
|
||||
) {
|
||||
// Field names vary by tool: Discord/Slack use "content", sessions_send uses "message"
|
||||
const text =
|
||||
(argsRecord.content as string) ?? (argsRecord.message as string);
|
||||
if (text && typeof text === "string") {
|
||||
pendingMessagingTexts.set(toolCallId, text);
|
||||
log.debug(
|
||||
`Tracking pending messaging text: tool=${toolName} action=${action} len=${text.length}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (evt.type === "tool_execution_update") {
|
||||
@@ -404,6 +458,18 @@ export function subscribeEmbeddedPiSession(params: {
|
||||
toolMetaById.delete(toolCallId);
|
||||
toolSummaryById.delete(toolCallId);
|
||||
|
||||
// Commit messaging tool text on success, discard on error
|
||||
const pendingText = pendingMessagingTexts.get(toolCallId);
|
||||
if (pendingText) {
|
||||
pendingMessagingTexts.delete(toolCallId);
|
||||
if (!isError) {
|
||||
messagingToolSentTexts.push(pendingText);
|
||||
log.debug(
|
||||
`Committed messaging text: tool=${toolName} len=${pendingText.length}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
emitAgentEvent({
|
||||
runId: params.runId,
|
||||
stream: "tool",
|
||||
@@ -591,14 +657,21 @@ export function subscribeEmbeddedPiSession(params: {
|
||||
blockChunker.drain({ force: true, emit: emitBlockChunk });
|
||||
blockChunker.reset();
|
||||
} else if (text !== lastBlockReplyText) {
|
||||
lastBlockReplyText = text;
|
||||
const { text: cleanedText, mediaUrls } =
|
||||
splitMediaFromOutput(text);
|
||||
if (cleanedText || (mediaUrls && mediaUrls.length > 0)) {
|
||||
void params.onBlockReply({
|
||||
text: cleanedText,
|
||||
mediaUrls: mediaUrls?.length ? mediaUrls : undefined,
|
||||
});
|
||||
// Check for duplicates before emitting (same logic as emitBlockChunk)
|
||||
if (isMessagingToolDuplicate(text, messagingToolSentTexts)) {
|
||||
log.debug(
|
||||
`Skipping message_end block reply - already sent via messaging tool: ${text.slice(0, 50)}...`,
|
||||
);
|
||||
} else {
|
||||
lastBlockReplyText = text;
|
||||
const { text: cleanedText, mediaUrls } =
|
||||
splitMediaFromOutput(text);
|
||||
if (cleanedText || (mediaUrls && mediaUrls.length > 0)) {
|
||||
void params.onBlockReply({
|
||||
text: cleanedText,
|
||||
mediaUrls: mediaUrls?.length ? mediaUrls : undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -705,6 +778,10 @@ export function subscribeEmbeddedPiSession(params: {
|
||||
toolMetas,
|
||||
unsubscribe,
|
||||
isCompacting: () => compactionInFlight || pendingCompactionRetry > 0,
|
||||
// Returns true if any messaging tool successfully sent a message.
|
||||
// Used to suppress agent's confirmation text (e.g., "Respondi no Telegram!")
|
||||
// which is generated AFTER the tool sends the actual answer.
|
||||
didSendViaMessagingTool: () => messagingToolSentTexts.length > 0,
|
||||
waitForCompactionRetry: () => {
|
||||
if (compactionInFlight || pendingCompactionRetry > 0) {
|
||||
ensureCompactionPromise();
|
||||
|
||||
@@ -4,15 +4,21 @@ import type { ClawdbotConfig } from "../../config/config.js";
|
||||
import { handleTelegramAction } from "./telegram-actions.js";
|
||||
|
||||
const reactMessageTelegram = vi.fn(async () => ({ ok: true }));
|
||||
const sendMessageTelegram = vi.fn(async () => ({
|
||||
messageId: "789",
|
||||
chatId: "123",
|
||||
}));
|
||||
const originalToken = process.env.TELEGRAM_BOT_TOKEN;
|
||||
|
||||
vi.mock("../../telegram/send.js", () => ({
|
||||
reactMessageTelegram: (...args: unknown[]) => reactMessageTelegram(...args),
|
||||
sendMessageTelegram: (...args: unknown[]) => sendMessageTelegram(...args),
|
||||
}));
|
||||
|
||||
describe("handleTelegramAction", () => {
|
||||
beforeEach(() => {
|
||||
reactMessageTelegram.mockClear();
|
||||
sendMessageTelegram.mockClear();
|
||||
process.env.TELEGRAM_BOT_TOKEN = "tok";
|
||||
});
|
||||
|
||||
@@ -92,4 +98,74 @@ describe("handleTelegramAction", () => {
|
||||
),
|
||||
).rejects.toThrow(/Telegram reactions are disabled/);
|
||||
});
|
||||
|
||||
it("sends a text message", async () => {
|
||||
const cfg = { telegram: { botToken: "tok" } } as ClawdbotConfig;
|
||||
const result = await handleTelegramAction(
|
||||
{
|
||||
action: "sendMessage",
|
||||
to: "@testchannel",
|
||||
content: "Hello, Telegram!",
|
||||
},
|
||||
cfg,
|
||||
);
|
||||
expect(sendMessageTelegram).toHaveBeenCalledWith(
|
||||
"@testchannel",
|
||||
"Hello, Telegram!",
|
||||
{ token: "tok", mediaUrl: undefined },
|
||||
);
|
||||
expect(result.content).toContainEqual({
|
||||
type: "text",
|
||||
text: expect.stringContaining('"ok": true'),
|
||||
});
|
||||
});
|
||||
|
||||
it("sends a message with media", async () => {
|
||||
const cfg = { telegram: { botToken: "tok" } } as ClawdbotConfig;
|
||||
await handleTelegramAction(
|
||||
{
|
||||
action: "sendMessage",
|
||||
to: "123456",
|
||||
content: "Check this image!",
|
||||
mediaUrl: "https://example.com/image.jpg",
|
||||
},
|
||||
cfg,
|
||||
);
|
||||
expect(sendMessageTelegram).toHaveBeenCalledWith(
|
||||
"123456",
|
||||
"Check this image!",
|
||||
{ token: "tok", mediaUrl: "https://example.com/image.jpg" },
|
||||
);
|
||||
});
|
||||
|
||||
it("respects sendMessage gating", async () => {
|
||||
const cfg = {
|
||||
telegram: { botToken: "tok", actions: { sendMessage: false } },
|
||||
} as ClawdbotConfig;
|
||||
await expect(
|
||||
handleTelegramAction(
|
||||
{
|
||||
action: "sendMessage",
|
||||
to: "@testchannel",
|
||||
content: "Hello!",
|
||||
},
|
||||
cfg,
|
||||
),
|
||||
).rejects.toThrow(/Telegram sendMessage is disabled/);
|
||||
});
|
||||
|
||||
it("throws on missing bot token for sendMessage", async () => {
|
||||
delete process.env.TELEGRAM_BOT_TOKEN;
|
||||
const cfg = {} as ClawdbotConfig;
|
||||
await expect(
|
||||
handleTelegramAction(
|
||||
{
|
||||
action: "sendMessage",
|
||||
to: "@testchannel",
|
||||
content: "Hello!",
|
||||
},
|
||||
cfg,
|
||||
),
|
||||
).rejects.toThrow(/Telegram bot token missing/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import type { AgentToolResult } from "@mariozechner/pi-agent-core";
|
||||
|
||||
import type { ClawdbotConfig } from "../../config/config.js";
|
||||
import { reactMessageTelegram } from "../../telegram/send.js";
|
||||
import {
|
||||
reactMessageTelegram,
|
||||
sendMessageTelegram,
|
||||
} from "../../telegram/send.js";
|
||||
import { resolveTelegramToken } from "../../telegram/token.js";
|
||||
import {
|
||||
createActionGate,
|
||||
@@ -49,5 +52,38 @@ export async function handleTelegramAction(
|
||||
return jsonResult({ ok: true, removed: true });
|
||||
}
|
||||
|
||||
if (action === "sendMessage") {
|
||||
if (!isActionEnabled("sendMessage")) {
|
||||
throw new Error("Telegram sendMessage is disabled.");
|
||||
}
|
||||
const to = readStringParam(params, "to", { required: true });
|
||||
const content = readStringParam(params, "content", { required: true });
|
||||
const mediaUrl = readStringParam(params, "mediaUrl");
|
||||
// Optional threading parameters for forum topics and reply chains
|
||||
const replyToMessageId = readNumberParam(params, "replyToMessageId", {
|
||||
integer: true,
|
||||
});
|
||||
const messageThreadId = readNumberParam(params, "messageThreadId", {
|
||||
integer: true,
|
||||
});
|
||||
const token = resolveTelegramToken(cfg).token;
|
||||
if (!token) {
|
||||
throw new Error(
|
||||
"Telegram bot token missing. Set TELEGRAM_BOT_TOKEN or telegram.botToken.",
|
||||
);
|
||||
}
|
||||
const result = await sendMessageTelegram(to, content, {
|
||||
token,
|
||||
mediaUrl: mediaUrl || undefined,
|
||||
replyToMessageId: replyToMessageId ?? undefined,
|
||||
messageThreadId: messageThreadId ?? undefined,
|
||||
});
|
||||
return jsonResult({
|
||||
ok: true,
|
||||
messageId: result.messageId,
|
||||
chatId: result.chatId,
|
||||
});
|
||||
}
|
||||
|
||||
throw new Error(`Unsupported Telegram action: ${action}`);
|
||||
}
|
||||
|
||||
@@ -13,4 +13,22 @@ export const TelegramToolSchema = Type.Union([
|
||||
},
|
||||
includeRemove: true,
|
||||
}),
|
||||
Type.Object({
|
||||
action: Type.Literal("sendMessage"),
|
||||
to: Type.String({ description: "Chat ID, @username, or t.me/username" }),
|
||||
content: Type.String({ description: "Message text to send" }),
|
||||
mediaUrl: Type.Optional(
|
||||
Type.String({ description: "URL of image/video/audio to attach" }),
|
||||
),
|
||||
replyToMessageId: Type.Optional(
|
||||
Type.Union([Type.String(), Type.Number()], {
|
||||
description: "Message ID to reply to (for threading)",
|
||||
}),
|
||||
),
|
||||
messageThreadId: Type.Optional(
|
||||
Type.Union([Type.String(), Type.Number()], {
|
||||
description: "Forum topic thread ID (for forum supergroups)",
|
||||
}),
|
||||
),
|
||||
}),
|
||||
]);
|
||||
|
||||
@@ -7,7 +7,7 @@ export function createTelegramTool(): AnyAgentTool {
|
||||
return {
|
||||
label: "Telegram",
|
||||
name: "telegram",
|
||||
description: "Manage Telegram reactions.",
|
||||
description: "Send messages and manage reactions on Telegram.",
|
||||
parameters: TelegramToolSchema,
|
||||
execute: async (_toolCallId, args) => {
|
||||
const params = args as Record<string, unknown>;
|
||||
|
||||
Reference in New Issue
Block a user