The Open Framework for Building Agents
fix(eve): telegram - preserve proactive private chat sessions (#377)
Andrew Barba6dc84fc33f59
diff --git a/.changeset/fix-telegram-proactive-private-chat.md b/.changeset/fix-telegram-proactive-private-chat.mdnew file mode 100644index 000000000..21a15f502--- /dev/null+++ b/.changeset/fix-telegram-proactive-private-chat.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Keep Telegram proactive private chat sessions keyed to their chat or topic after outbound sends, while group and supergroup proactive sends still anchor to the bot message id.diff --git a/docs/channels/telegram.mdx b/docs/channels/telegram.mdxindex d6a4d7dcc..036e2238c 100644--- a/docs/channels/telegram.mdx+++ b/docs/channels/telegram.mdx@@ -53,6 +53,8 @@ Human-in-the-loop (HITL) turns option requests into inline-keyboard buttons andStart a session without an inbound message through `receive(telegram, { message, target, auth })` from a schedule `run` handler, or `args.receive(telegram, ...)` from another channel. `target.chatId` is required. Add `messageThreadId` to land in a specific forum topic.+Private proactive chats stay keyed to the chat, or to the chat plus `messageThreadId` when you target a topic. Group and supergroup proactive sends anchor to the bot message id returned by Telegram, so replies to different bot messages can resume different sessions in the same chat. If Telegram does not return a recognized chat type for an outbound send, eve keeps the session unanchored instead of guessing.+### AttachmentsInbound photos and documents are supported. eve fetches them on demand via `getFile`, only when an upload policy allows the type:diff --git a/packages/eve/src/public/channels/telegram/api.test.ts b/packages/eve/src/public/channels/telegram/api.test.tsindex c27116cb7..6222d2f1f 100644--- a/packages/eve/src/public/channels/telegram/api.test.ts+++ b/packages/eve/src/public/channels/telegram/api.test.ts@@ -80,6 +80,50 @@ describe("sendTelegramMessage", () => {expect(posted).toMatchObject({ chatId: "-1001", id: "42" });});++ it("extracts recognized chat types from Telegram's response", async () => {+ for (const chatType of ["channel", "group", "private", "supergroup"] as const) {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ ok: true,+ result: { message_id: 42, chat: { id: -1001, type: chatType } },+ }),+ ),+ );++ const posted = await sendTelegramMessage({+ body: { text: "hello" },+ chatId: -1001,+ credentials: { botToken: "bot-token" },+ fetch: fetchMock,+ });++ expect(posted).toMatchObject({ chatType });+ }+ });++ it("ignores missing and unrecognized chat types from Telegram's response", async () => {+ for (const chat of [{ id: -1001 }, { id: -1001, type: "bot" }]) {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ ok: true,+ result: { message_id: 42, chat },+ }),+ ),+ );++ const posted = await sendTelegramMessage({+ body: { text: "hello" },+ chatId: -1001,+ credentials: { botToken: "bot-token" },+ fetch: fetchMock,+ });++ expect(posted.chatType).toBeUndefined();+ }+ });});describe("sendTelegramChatAction", () => {diff --git a/packages/eve/src/public/channels/telegram/api.ts b/packages/eve/src/public/channels/telegram/api.tsindex 531cb38ad..c9df17301 100644--- a/packages/eve/src/public/channels/telegram/api.ts+++ b/packages/eve/src/public/channels/telegram/api.ts@@ -7,6 +7,7 @@import { parseJsonObject, type JsonObject } from "#shared/json.js";import { isObject } from "#shared/guards.js";+import { parseTelegramChatType, type TelegramChatType } from "#public/channels/telegram/inbound.js";/** Telegram bot token, materialized directly or from an async secret provider. */export type TelegramBotToken = string | (() => string | Promise<string>);@@ -47,6 +48,8 @@ export interface TelegramMessageResult {readonly id: string;/** Telegram chat id associated with the message, when Telegram returned one. */readonly chatId?: string;+ /** Recognized Telegram chat type associated with the message, when returned. */+ readonly chatType?: TelegramChatType;/** Telegram's raw JSON response. */readonly raw: unknown;}@@ -284,6 +287,7 @@ function toTelegramMessageResult(body: unknown): TelegramMessageResult {return {chatId:typeof chat.id === "number" || typeof chat.id === "string" ? String(chat.id) : undefined,+ chatType: parseTelegramChatType(chat.type) ?? undefined,id:typeof result.message_id === "number" || typeof result.message_id === "string"? String(result.message_id)diff --git a/packages/eve/src/public/channels/telegram/inbound.ts b/packages/eve/src/public/channels/telegram/inbound.tsindex fc2c7aa10..0b22195a8 100644--- a/packages/eve/src/public/channels/telegram/inbound.ts+++ b/packages/eve/src/public/channels/telegram/inbound.ts@@ -192,7 +192,7 @@ function parseMessageReference(value: unknown): TelegramMessageReference | undeffunction parseTelegramChat(value: unknown): TelegramChat | null {if (!isObject(value)) return null;const id = numberLikeToString(value.id);- const type = parseChatType(value.type);+ const type = parseTelegramChatType(value.type);if (!id || !type) return null;return {id,@@ -276,7 +276,8 @@ function scorePhoto(photo: {return (photo.width ?? 0) * (photo.height ?? 0);}-function parseChatType(value: unknown): TelegramChatType | null {+/** Parses the Telegram chat types eve recognizes from inbound and send responses. */+export function parseTelegramChatType(value: unknown): TelegramChatType | null {if (value === "channel" || value === "group" || value === "private" || value === "supergroup") {return value;}diff --git a/packages/eve/src/public/channels/telegram/telegramChannel.test.ts b/packages/eve/src/public/channels/telegram/telegramChannel.test.tsindex 6448671f8..e39e986cb 100644--- a/packages/eve/src/public/channels/telegram/telegramChannel.test.ts+++ b/packages/eve/src/public/channels/telegram/telegramChannel.test.ts@@ -408,6 +408,142 @@ describe("telegramChannel() default event handlers", () => {expect(ctx.state.pendingFreeformReplies).toEqual({ "51": "call_1" });});+ it("hydrates unknown private message posts without re-keying the session", async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ ok: true,+ result: { message_id: 77, chat: { id: 42, type: "private" } },+ }),+ ),+ );+ vi.stubGlobal("fetch", fetchMock);+ const adapter = withState(+ getAdapter(telegramChannel({ credentials: { botToken: "bot-token" } })),+ { chatId: "42", chatType: null, conversationId: null },+ );+ const { accessor, writes } = captureAccessor("telegram:42::");+ const ctx = buildAdapterContext(adapter, accessor);++ await callEvent(+ adapter,+ makeEvent("message.completed", {+ finishReason: "stop",+ message: "hello",+ sequence: 0,+ stepIndex: 0,+ turnId: "t1",+ }),+ ctx,+ );++ expect(writes.filter(([key]) => key === "eve.continuationToken")).toEqual([]);+ expect(ctx.state.chatType).toBe("private");+ expect(ctx.state.conversationId).toBeNull();+ });++ it("keeps proactive private topic posts topic-wide without a message-id anchor", async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ ok: true,+ result: { message_id: 77, chat: { id: 42, type: "private" } },+ }),+ ),+ );+ vi.stubGlobal("fetch", fetchMock);+ const adapter = withState(+ getAdapter(telegramChannel({ credentials: { botToken: "bot-token" } })),+ { chatId: "42", chatType: null, conversationId: null, messageThreadId: 7 },+ );+ const { accessor, writes } = captureAccessor("telegram:42:7:");+ const ctx = buildAdapterContext(adapter, accessor);++ await callEvent(+ adapter,+ makeEvent("message.completed", {+ finishReason: "stop",+ message: "hello",+ sequence: 0,+ stepIndex: 0,+ turnId: "t1",+ }),+ ctx,+ );++ expect(writes.filter(([key]) => key === "eve.continuationToken")).toEqual([]);+ expect(ctx.state.chatType).toBe("private");+ expect(ctx.state.conversationId).toBeNull();+ });++ it("hydrates unknown group message posts and re-keys to the posted message id", async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ ok: true,+ result: { message_id: 77, chat: { id: -1001, type: "supergroup" } },+ }),+ ),+ );+ vi.stubGlobal("fetch", fetchMock);+ const adapter = withState(+ getAdapter(telegramChannel({ credentials: { botToken: "bot-token" } })),+ { chatId: "-1001", chatType: null, conversationId: null },+ );+ const { accessor, writes } = captureAccessor("telegram:-1001::");+ const ctx = buildAdapterContext(adapter, accessor);++ await callEvent(+ adapter,+ makeEvent("message.completed", {+ finishReason: "stop",+ message: "hello",+ sequence: 0,+ stepIndex: 0,+ turnId: "t1",+ }),+ ctx,+ );++ expect(writes).toContainEqual(["eve.continuationToken", "telegram:-1001::77"]);+ expect(ctx.state.chatType).toBe("supergroup");+ expect(ctx.state.conversationId).toBe("77");+ });++ it("preserves explicit conversation ids after Telegram identifies a private chat", async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ ok: true,+ result: { message_id: 77, chat: { id: 42, type: "private" } },+ }),+ ),+ );+ vi.stubGlobal("fetch", fetchMock);+ const adapter = withState(+ getAdapter(telegramChannel({ credentials: { botToken: "bot-token" } })),+ { chatId: "42", chatType: null, conversationId: "caller-selected" },+ );+ const { accessor, writes } = captureAccessor("telegram:42::caller-selected");+ const ctx = buildAdapterContext(adapter, accessor);++ await callEvent(+ adapter,+ makeEvent("message.completed", {+ finishReason: "stop",+ message: "hello",+ sequence: 0,+ stepIndex: 0,+ turnId: "t1",+ }),+ ctx,+ );++ expect(writes.filter(([key]) => key === "eve.continuationToken")).toEqual([]);+ expect(ctx.state.chatType).toBe("private");+ expect(ctx.state.conversationId).toBe("caller-selected");+ });+it("group message posts re-key the session to the posted message id", async () => {const fetchMock = vi.fn()@@ -440,7 +576,127 @@ describe("telegramChannel() default event handlers", () => {});describe("telegramChannel().receive", () => {- it("starts a proactive session and anchors initialMessage under Telegram's message id", async () => {+ it("keeps private initialMessage sessions chat-wide", async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ ok: true,+ result: { message_id: 88, chat: { id: 42, type: "private" } },+ }),+ ),+ );+ const channel = asCompiled<TelegramChannelState>(+ telegramChannel({+ api: { apiBaseUrl: "https://telegram.example", fetch: fetchMock },+ credentials: { botToken: "bot-token" },+ }),+ );+ const send = vi.fn().mockResolvedValue({ continuationToken: "ct", id: "s1" });++ await channel.receive!(+ {+ target: { chatId: 42, initialMessage: "Starting" },+ auth: null,+ message: "run",+ },+ { send },+ );++ expect(send).toHaveBeenCalledWith(+ "run",+ expect.objectContaining({+ continuationToken: "42::",+ state: expect.objectContaining({+ chatId: "42",+ chatType: "private",+ conversationId: null,+ }),+ }),+ );+ });++ it("keeps private topic initialMessage sessions topic-wide", async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ ok: true,+ result: { message_id: 88, chat: { id: 42, type: "private" } },+ }),+ ),+ );+ const channel = asCompiled<TelegramChannelState>(+ telegramChannel({+ api: { apiBaseUrl: "https://telegram.example", fetch: fetchMock },+ credentials: { botToken: "bot-token" },+ }),+ );+ const send = vi.fn().mockResolvedValue({ continuationToken: "ct", id: "s1" });++ await channel.receive!(+ {+ target: { chatId: 42, initialMessage: "Starting", messageThreadId: 7 },+ auth: null,+ message: "run",+ },+ { send },+ );++ expect(send).toHaveBeenCalledWith(+ "run",+ expect.objectContaining({+ continuationToken: "42:7:",+ state: expect.objectContaining({+ chatId: "42",+ chatType: "private",+ conversationId: null,+ messageThreadId: 7,+ }),+ }),+ );+ });++ it("anchors group initialMessage sessions under Telegram's message id", async () => {+ for (const chatType of ["group", "supergroup"] as const) {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ ok: true,+ result: { message_id: 88, chat: { id: -1001, type: chatType } },+ }),+ ),+ );+ const channel = asCompiled<TelegramChannelState>(+ telegramChannel({+ api: { apiBaseUrl: "https://telegram.example", fetch: fetchMock },+ credentials: { botToken: "bot-token" },+ }),+ );+ const send = vi.fn().mockResolvedValue({ continuationToken: "ct", id: "s1" });++ await channel.receive!(+ {+ target: { chatId: -1001, initialMessage: "Starting" },+ auth: null,+ message: "run",+ },+ { send },+ );++ expect(send).toHaveBeenCalledWith(+ "run",+ expect.objectContaining({+ continuationToken: "-1001::88",+ state: expect.objectContaining({+ chatId: "-1001",+ chatType,+ conversationId: "88",+ }),+ }),+ );+ }+ });++ it("leaves initialMessage sessions unanchored when Telegram omits the chat type", async () => {const fetchMock = vi.fn().mockResolvedValue(@@ -466,8 +722,51 @@ describe("telegramChannel().receive", () => {expect(send).toHaveBeenCalledWith("run",expect.objectContaining({- continuationToken: "42::88",- state: expect.objectContaining({ chatId: "42", conversationId: "88" }),+ continuationToken: "42::",+ state: expect.objectContaining({+ chatId: "42",+ chatType: null,+ conversationId: null,+ }),+ }),+ );+ });++ it("leaves initialMessage sessions unanchored for unsupported returned chat types", async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ ok: true,+ result: { message_id: 88, chat: { id: 42, type: "bot" } },+ }),+ ),+ );+ const channel = asCompiled<TelegramChannelState>(+ telegramChannel({+ api: { apiBaseUrl: "https://telegram.example", fetch: fetchMock },+ credentials: { botToken: "bot-token" },+ }),+ );+ const send = vi.fn().mockResolvedValue({ continuationToken: "ct", id: "s1" });++ await channel.receive!(+ {+ target: { chatId: 42, initialMessage: "Starting" },+ auth: null,+ message: "run",+ },+ { send },+ );++ expect(send).toHaveBeenCalledWith(+ "run",+ expect.objectContaining({+ continuationToken: "42::",+ state: expect.objectContaining({+ chatId: "42",+ chatType: null,+ conversationId: null,+ }),}),);});diff --git a/packages/eve/src/public/channels/telegram/telegramChannel.ts b/packages/eve/src/public/channels/telegram/telegramChannel.tsindex c0da4123d..fcc3c1e07 100644--- a/packages/eve/src/public/channels/telegram/telegramChannel.ts+++ b/packages/eve/src/public/channels/telegram/telegramChannel.ts@@ -292,33 +292,25 @@ export function telegramChannel(config: TelegramChannelConfig = {}): TelegramCha);}- let conversationId = requestedConversationId;+ const receiveState: TelegramChannelState = {+ ...initialTelegramState(config.botUsername),+ chatId,+ conversationId: requestedConversationId ?? null,+ messageThreadId: messageThreadId ?? null,+ };+if (initialMessage !== undefined) {const handle = buildTelegramHandle({config,- state: {- ...initialTelegramState(config.botUsername),- chatId,- messageThreadId: messageThreadId ?? null,- },+ state: receiveState,});- const posted = await handle.sendMessage(initialMessage);- conversationId = posted.id || undefined;+ await handle.sendMessage(initialMessage);}return send(input.message, {auth: input.auth,- continuationToken: telegramContinuationToken({- chatId,- conversationId,- messageThreadId,- }),- state: {- ...initialTelegramState(config.botUsername),- chatId,- conversationId: conversationId ?? null,- messageThreadId: messageThreadId ?? null,- },+ continuationToken: continuationTokenFromState(receiveState),+ state: receiveState,});},@@ -350,7 +342,11 @@ function buildTelegramHandle(input: {const credentials = input.config.credentials;function anchor(posted: TelegramMessageResult): void {- if (!posted.id || state.chatType === "private") return;+ const chatType = state.chatType ?? posted.chatType ?? null;+ if (state.chatType === null && posted.chatType !== undefined) {+ state.chatType = posted.chatType;+ }+ if (!posted.id || !shouldAnchorTelegramConversation(chatType)) return;state.conversationId = posted.id;if (state.chatId) {input.session?.setContinuationToken(@@ -443,6 +439,10 @@ function buildTelegramHandle(input: {};}+function shouldAnchorTelegramConversation(chatType: TelegramChatType | null): boolean {+ return chatType === "group" || chatType === "supergroup";+}+async function postTelegramMessage(message: string | TelegramMessageBody,sendOne: (body: TelegramMessageBody) => Promise<TelegramMessageResult>,