Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): support HITL authorization on Telegram channel (#2501)

Ben Pankowcfa90d6478a1
diff --git a/.changeset/telegram-private-authorization.md b/.changeset/telegram-private-authorization.md
new file mode 100644
index 000000000..46b53e56a
--- /dev/null
+++ b/.changeset/telegram-private-authorization.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Telegram now supports HITL authorization challenges.
diff --git a/packages/eve/src/public/channels/telegram/api.test.ts b/packages/eve/src/public/channels/telegram/api.test.ts
index 6222d2f1f..de62dd26b 100644
--- a/packages/eve/src/public/channels/telegram/api.test.ts
+++ b/packages/eve/src/public/channels/telegram/api.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vitest";
import {
callTelegramApi,
+ editTelegramMessageText,
sendTelegramChatAction,
sendTelegramMessage,
splitTelegramMessageText,
@@ -81,6 +82,25 @@ describe("sendTelegramMessage", () => {
expect(posted).toMatchObject({ chatId: "-1001", id: "42" });
});
+ it("includes Telegram's error description when delivery fails", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ description: "Bad Request: bot is not an administrator" }), {
+ status: 400,
+ }),
+ );
+
+ await expect(
+ sendTelegramMessage({
+ body: { text: "hello" },
+ chatId: -1001,
+ credentials: { botToken: "bot-token" },
+ fetch: fetchMock,
+ }),
+ ).rejects.toThrow(
+ "Telegram sendMessage failed with HTTP 400: Bad Request: bot is not an administrator",
+ );
+ });
+
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(
@@ -126,6 +146,27 @@ describe("sendTelegramMessage", () => {
});
});
+describe("editTelegramMessageText", () => {
+ it("sends the replacement text and removes reply markup when omitted", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ ok: true })));
+
+ await editTelegramMessageText({
+ chatId: "C1",
+ credentials: { botToken: "bot-token" },
+ fetch: fetchMock,
+ messageId: "42",
+ text: "Notion connected.",
+ });
+
+ const init = fetchMock.mock.calls[0]![1] as RequestInit;
+ expect(JSON.parse(String(init.body))).toEqual({
+ chat_id: "C1",
+ message_id: 42,
+ text: "Notion connected.",
+ });
+ });
+});
+
describe("sendTelegramChatAction", () => {
it("passes message_thread_id when supplied", async () => {
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ ok: true })));
diff --git a/packages/eve/src/public/channels/telegram/api.ts b/packages/eve/src/public/channels/telegram/api.ts
index c9df17301..4f7dcf837 100644
--- a/packages/eve/src/public/channels/telegram/api.ts
+++ b/packages/eve/src/public/channels/telegram/api.ts
@@ -58,8 +58,17 @@ export interface TelegramMessageResult {
* Body for Telegram's `sendMessage`. Only `text` is required; the remaining
* snake_case fields are forwarded to Telegram unchanged.
*/
+export interface TelegramEphemeralMessageParameters {
+ /** Callback query that grants this ephemeral response's 15-second delivery window. */
+ readonly callback_query_id?: string;
+ /** Telegram user id that may view this group or supergroup response. */
+ readonly receiver_user_id: number | string;
+}
+
export interface TelegramMessageBody {
readonly disable_notification?: boolean;
+ /** Delivers this group or supergroup response only to one member. */
+ readonly ephemeral_message_parameters?: TelegramEphemeralMessageParameters;
readonly link_preview_options?: Readonly<Record<string, unknown>>;
readonly message_thread_id?: number;
readonly protect_content?: boolean;
@@ -141,7 +150,9 @@ export async function sendTelegramMessage(
method: "sendMessage",
});
if (!response.ok) {
- throw new Error(`Telegram sendMessage failed with HTTP ${response.status}.`);
+ throw new Error(
+ `Telegram sendMessage failed with HTTP ${response.status}: ${formatTelegramErrorBody(response.body)}`,
+ );
}
return toTelegramMessageResult(response.body);
}
@@ -191,6 +202,29 @@ export async function answerTelegramCallbackQuery(
});
}
+/** Edits the text and optional reply markup for one Telegram message. */
+export async function editTelegramMessageText(
+ input: TelegramApiOptions & {
+ readonly chatId: number | string;
+ readonly messageId: number | string;
+ readonly replyMarkup?: Readonly<Record<string, unknown>>;
+ readonly text: string;
+ },
+): Promise<TelegramApiResponse> {
+ return callTelegramApi({
+ apiBaseUrl: input.apiBaseUrl,
+ body: parseJsonObject({
+ chat_id: input.chatId,
+ message_id: Number(input.messageId),
+ reply_markup: input.replyMarkup,
+ text: input.text,
+ }),
+ botToken: input.credentials?.botToken,
+ fetch: input.fetch,
+ method: "editMessageText",
+ });
+}
+
/** Edits only the reply markup for one Telegram message. */
export async function editTelegramMessageReplyMarkup(
input: TelegramApiOptions & {
@@ -296,6 +330,20 @@ function toTelegramMessageResult(body: unknown): TelegramMessageResult {
};
}
+function formatTelegramErrorBody(body: unknown): string {
+ if (typeof body === "string") return body;
+ if (body !== null && typeof body === "object") {
+ const description = (body as { description?: unknown }).description;
+ if (typeof description === "string" && description.length > 0) return description;
+ }
+ try {
+ const text = JSON.stringify(body);
+ return text === undefined || text.length === 0 ? "empty response body" : text;
+ } catch {
+ return "unserializable response body";
+ }
+}
+
async function parseResponseBody(response: Response): Promise<unknown> {
const text = await response.text();
if (!text) return null;
diff --git a/packages/eve/src/public/channels/telegram/authorization-callback.ts b/packages/eve/src/public/channels/telegram/authorization-callback.ts
new file mode 100644
index 000000000..dd9b9cd23
--- /dev/null
+++ b/packages/eve/src/public/channels/telegram/authorization-callback.ts
@@ -0,0 +1,95 @@
+import type { ChannelResolveSession } from "#channel/channel-operations.js";
+import type { Session } from "#channel/session.js";
+import { createLogger } from "#internal/logging.js";
+import type { AuthorizationRequiredStreamEvent } from "#protocol/message.js";
+import {
+ TELEGRAM_AUTHORIZATION_CALLBACK_PREFIX,
+ renderTelegramAuthorizationPrompt,
+} from "#public/channels/telegram/authorization.js";
+import type { TelegramCallbackQuery } from "#public/channels/telegram/inbound.js";
+import type {
+ TelegramChannelState,
+ TelegramContext,
+} from "#public/channels/telegram/telegramChannel.js";
+
+const log = createLogger("telegram.authorization-callback");
+
+export async function dispatchTelegramAuthorizationCallback(input: {
+ readonly continuationToken: string;
+ readonly query: TelegramCallbackQuery;
+ readonly resolveSession: ChannelResolveSession;
+ readonly state: TelegramChannelState;
+ readonly telegram: TelegramContext;
+}): Promise<void> {
+ const expectedUserId = input.query.data?.slice(TELEGRAM_AUTHORIZATION_CALLBACK_PREFIX.length);
+ if (expectedUserId !== input.query.from.id) {
+ await input.telegram.telegram.answerCallbackQuery({
+ callbackQueryId: input.query.id,
+ showAlert: true,
+ text: "Only the requester can authorize this connection.",
+ });
+ return;
+ }
+ if (!input.query.message || !input.state.chatId) return;
+
+ try {
+ const session = await input.resolveSession(input.continuationToken);
+ if (session === undefined) {
+ await inactiveAuthorization(input.telegram.telegram, input.query.id);
+ return;
+ }
+ const authorization = await findPendingAuthorization(session);
+ if (authorization === undefined) {
+ await inactiveAuthorization(input.telegram.telegram, input.query.id);
+ return;
+ }
+
+ await input.telegram.telegram.postEphemeral(
+ input.query.from.id,
+ renderTelegramAuthorizationPrompt(authorization.data),
+ { callbackQueryId: input.query.id },
+ );
+ await input.telegram.telegram.answerCallbackQuery({
+ callbackQueryId: input.query.id,
+ text: "Sign-in prompt sent privately.",
+ });
+ } catch (error) {
+ log.error("Telegram authorization callback delivery failed", { error });
+ }
+}
+
+async function inactiveAuthorization(
+ telegram: TelegramContext["telegram"],
+ callbackQueryId: string,
+) {
+ await telegram.answerCallbackQuery({
+ callbackQueryId,
+ showAlert: true,
+ text: "This authorization request is no longer active.",
+ });
+}
+
+async function findPendingAuthorization(
+ session: Session,
+): Promise<AuthorizationRequiredStreamEvent | undefined> {
+ const tailIndex = await session.getStreamTailIndex();
+ if (tailIndex < 0) return undefined;
+ const events = await session.getEventStream({ startIndex: 0 });
+ const reader = events.getReader();
+ let authorization: AuthorizationRequiredStreamEvent | undefined;
+ try {
+ for (let index = 0; index <= tailIndex; index += 1) {
+ const next = await reader.read();
+ if (next.done) break;
+ if (
+ next.value.type === "authorization.required" &&
+ next.value.data.candidateId === undefined
+ ) {
+ authorization = next.value;
+ }
+ }
+ } finally {
+ await reader.cancel().catch(() => {});
+ }
+ return authorization;
+}
diff --git a/packages/eve/src/public/channels/telegram/authorization.ts b/packages/eve/src/public/channels/telegram/authorization.ts
new file mode 100644
index 000000000..94c05aad4
--- /dev/null
+++ b/packages/eve/src/public/channels/telegram/authorization.ts
@@ -0,0 +1,67 @@
+import type { AuthorizationOutcome, AuthorizationRequiredStreamEvent } from "#protocol/message.js";
+
+export const TELEGRAM_AUTHORIZATION_CALLBACK_PREFIX = "eve_auth:";
+
+export function renderTelegramAuthorizationPrompt(
+ authorization: AuthorizationRequiredStreamEvent["data"],
+): { readonly reply_markup?: Readonly<Record<string, unknown>>; readonly text: string } {
+ const displayName = formatTelegramAuthorizationDisplayName(
+ authorization.name,
+ authorization.authorization?.displayName,
+ );
+ const url = authorization.authorization?.url;
+ return {
+ reply_markup:
+ url === undefined
+ ? undefined
+ : { inline_keyboard: [[{ text: `Sign in with ${displayName}`, url }]] },
+ text: [
+ `Authorization required for ${displayName}.`,
+ authorization.authorization?.instructions,
+ authorization.authorization?.userCode === undefined
+ ? undefined
+ : `Code: ${authorization.authorization.userCode}`,
+ ]
+ .filter((part): part is string => part !== undefined && part.length > 0)
+ .join("\n\n"),
+ };
+}
+
+export function renderTelegramAuthorizationStatus(input: {
+ readonly displayName: string;
+ readonly requesterUserId?: string | null;
+}): { readonly reply_markup?: Readonly<Record<string, unknown>>; readonly text: string } {
+ const callbackData =
+ input.requesterUserId === undefined || input.requesterUserId === null
+ ? undefined
+ : `${TELEGRAM_AUTHORIZATION_CALLBACK_PREFIX}${input.requesterUserId}`;
+ return {
+ reply_markup:
+ callbackData === undefined
+ ? undefined
+ : {
+ inline_keyboard: [[{ callback_data: callbackData, text: "Authorize" }]],
+ },
+ text: `Authorization required for ${input.displayName}. The requester must sign in to resume.`,
+ };
+}
+
+export function formatTelegramAuthorizationDisplayName(
+ name: string,
+ displayName: string | undefined,
+): string {
+ if (displayName !== undefined) return displayName;
+ if (name.length === 0) return name;
+ return name.charAt(0).toUpperCase() + name.slice(1);
+}
+
+export function renderTelegramAuthorizationCompleted(input: {
+ readonly displayName: string;
+ readonly outcome: AuthorizationOutcome;
+ readonly reason?: string;
+}): string {
+ if (input.outcome === "authorized") return `${input.displayName} connected.`;
+ const reason = input.reason === undefined ? "" : ` (${input.reason})`;
+ const outcome = input.outcome === "timed-out" ? "timed out" : input.outcome;
+ return `${input.displayName} authorization ${outcome}${reason}.`;
+}
diff --git a/packages/eve/src/public/channels/telegram/defaults.ts b/packages/eve/src/public/channels/telegram/defaults.ts
index 2540ec314..d7af7b8d2 100644
--- a/packages/eve/src/public/channels/telegram/defaults.ts
+++ b/packages/eve/src/public/channels/telegram/defaults.ts
@@ -1,6 +1,12 @@
import type { SessionAuthContext } from "#channel/types.js";
-import { extractErrorId, formatErrorHint } from "#internal/logging.js";
+import { createLogger, extractErrorId, formatErrorHint } from "#internal/logging.js";
+import {
+ formatTelegramAuthorizationDisplayName,
+ renderTelegramAuthorizationCompleted,
+ renderTelegramAuthorizationPrompt,
+ renderTelegramAuthorizationStatus,
+} from "#public/channels/telegram/authorization.js";
import {
registerTelegramFreeformPrompt,
renderTelegramInputRequest,
@@ -12,6 +18,8 @@ import type {
TelegramInboundResult,
} from "#public/channels/telegram/telegramChannel.js";
+const log = createLogger("telegram.defaults");
+
/** Default auth projection for Telegram webhook actors. */
export function defaultTelegramAuth(message: TelegramMessage): SessionAuthContext | null {
const user = message.from;
@@ -70,10 +78,74 @@ export const defaultEvents: TelegramChannelEvents = {
await channel.telegram.startTyping();
},
+ async "authorization.required"(event, channel, _ctx) {
+ if (event.candidateId !== undefined) return;
+
+ const displayName = formatTelegramAuthorizationDisplayName(
+ event.name,
+ event.authorization?.displayName,
+ );
+ const isPrivate = channel.telegram.chatType === "private";
+ const pending = channel.state.pendingAuthMessageIds ?? {};
+
+ if (isPrivate) {
+ try {
+ const posted = await channel.telegram.post(renderTelegramAuthorizationPrompt(event));
+ if (posted.id) {
+ channel.state.pendingAuthMessageIds = { ...pending, [event.name]: posted.id };
+ }
+ } catch (error) {
+ log.error("Telegram authorization prompt delivery failed", { error, name: event.name });
+ }
+ return;
+ }
+
+ if (pending[event.name] === undefined) {
+ try {
+ const posted = await channel.telegram.post(
+ renderTelegramAuthorizationStatus({
+ displayName,
+ requesterUserId: channel.state.triggeringUserId,
+ }),
+ );
+ if (posted.id) {
+ channel.state.pendingAuthMessageIds = { ...pending, [event.name]: posted.id };
+ }
+ } catch (error) {
+ log.error("Telegram authorization status delivery failed", { error, name: event.name });
+ }
+ }
+ },
+
async "authorization.completed"(event, channel, _ctx) {
- if (event.outcome === "authorized") {
+ if (event.outcome === "authorized" && event.candidateId === undefined) {
await channel.telegram.startTyping();
}
+ if (event.candidateId !== undefined) return;
+
+ const pending = channel.state.pendingAuthMessageIds ?? {};
+ const messageId = pending[event.name];
+ if (messageId === undefined) return;
+ const displayName = formatTelegramAuthorizationDisplayName(
+ event.name,
+ event.authorization?.displayName,
+ );
+ try {
+ await channel.telegram.editMessageText({
+ messageId,
+ replyMarkup: { inline_keyboard: [] },
+ text: renderTelegramAuthorizationCompleted({
+ displayName,
+ outcome: event.outcome,
+ reason: event.reason,
+ }),
+ });
+ } catch (error) {
+ log.error("Telegram authorization status edit failed", { error, name: event.name });
+ }
+ const next = { ...pending };
+ delete next[event.name];
+ channel.state.pendingAuthMessageIds = next;
},
async "actions.requested"(_event, channel, _ctx) {
diff --git a/packages/eve/src/public/channels/telegram/index.ts b/packages/eve/src/public/channels/telegram/index.ts
index 90c65463b..843c34b3e 100644
--- a/packages/eve/src/public/channels/telegram/index.ts
+++ b/packages/eve/src/public/channels/telegram/index.ts
@@ -33,6 +33,7 @@ export {
answerTelegramCallbackQuery,
downloadTelegramFile,
editTelegramMessageReplyMarkup,
+ editTelegramMessageText,
getTelegramFile,
resolveTelegramBotToken,
sendTelegramChatAction,
@@ -44,6 +45,7 @@ export {
type TelegramApiResponse,
type TelegramBotToken,
type TelegramCredentials,
+ type TelegramEphemeralMessageParameters,
type TelegramFetch,
type TelegramMessageBody,
type TelegramMessageResult,
diff --git a/packages/eve/src/public/channels/telegram/state.ts b/packages/eve/src/public/channels/telegram/state.ts
new file mode 100644
index 000000000..dfe29db50
--- /dev/null
+++ b/packages/eve/src/public/channels/telegram/state.ts
@@ -0,0 +1,66 @@
+import { telegramContinuationToken } from "#public/channels/telegram/api.js";
+import type { TelegramCallbackQuery, TelegramMessage } from "#public/channels/telegram/inbound.js";
+import type { TelegramChannelState } from "#public/channels/telegram/telegramChannel.js";
+
+export function stateFromTelegramMessage(
+ message: TelegramMessage,
+ botUsername: string | undefined,
+): TelegramChannelState {
+ const privateChat = message.chat.type === "private";
+ return {
+ ...initialTelegramState(botUsername),
+ chatId: message.chat.id,
+ chatType: message.chat.type,
+ conversationId: privateChat ? null : conversationIdForMessage(message),
+ messageThreadId: message.messageThreadId ?? null,
+ triggeringUserId: message.from?.id ?? null,
+ };
+}
+
+export function stateFromTelegramCallbackQuery(
+ query: TelegramCallbackQuery,
+ botUsername: string | undefined,
+): TelegramChannelState {
+ const message = query.message;
+ if (!message) {
+ return { ...initialTelegramState(botUsername), triggeringUserId: query.from.id };
+ }
+ const privateChat = message.chat.type === "private";
+ return {
+ ...initialTelegramState(botUsername),
+ chatId: message.chat.id,
+ chatType: message.chat.type,
+ conversationId: privateChat ? null : message.messageId,
+ messageThreadId: message.messageThreadId ?? null,
+ triggeringUserId: query.from.id,
+ };
+}
+
+export function telegramContinuationTokenFromState(state: TelegramChannelState): string {
+ return telegramContinuationToken({
+ chatId: state.chatId ?? "",
+ conversationId: state.chatType === "private" ? undefined : (state.conversationId ?? undefined),
+ messageThreadId: state.messageThreadId ?? undefined,
+ });
+}
+
+export function initialTelegramState(botUsername: string | undefined): TelegramChannelState {
+ return {
+ botUsername: botUsername ?? null,
+ chatId: null,
+ chatType: null,
+ conversationId: null,
+ hitlCallbacks: {},
+ messageThreadId: null,
+ nextHitlCallbackId: 0,
+ pendingAuthMessageIds: {},
+ pendingFreeformReplies: {},
+ triggeringUserId: null,
+ };
+}
+
+function conversationIdForMessage(message: TelegramMessage): string {
+ return message.replyToMessage?.from?.isBot === true
+ ? message.replyToMessage.messageId
+ : message.messageId;
+}
diff --git a/packages/eve/src/public/channels/telegram/telegramChannel.test.ts b/packages/eve/src/public/channels/telegram/telegramChannel.test.ts
index 2afcf3ffb..06606f872 100644
--- a/packages/eve/src/public/channels/telegram/telegramChannel.test.ts
+++ b/packages/eve/src/public/channels/telegram/telegramChannel.test.ts
@@ -78,6 +78,7 @@ function fakeTelegramFetch(): typeof fetch {
async function firePost(
channel: unknown,
body: unknown,
+ options: { readonly resolveSession?: () => Promise<any> } = {},
): Promise<{
readonly response: Response;
readonly send: ReturnType<typeof vi.fn>;
@@ -94,6 +95,7 @@ async function firePost(
const response = await post.handler(signedRequest(JSON.stringify(body)), {
attachSession: vi.fn() as any,
...mockChannelContext(send),
+ resolveSession: options.resolveSession ?? (async () => undefined),
to: vi.fn() as any,
params: {},
requestIp: null,
@@ -265,6 +267,69 @@ describe("telegramChannel() inbound route", () => {
);
});
+ it("sends authorization privately after the requester taps its group callback", async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValue(new Response(JSON.stringify({ ok: true, result: true })));
+ const channel = telegramChannel({
+ api: { fetch: fetchMock },
+ credentials: { botToken: "bot-token", webhookSecretToken: SECRET },
+ });
+ const session = {
+ async getEventStream() {
+ return new ReadableStream({
+ start(controller) {
+ controller.enqueue({
+ type: "authorization.required",
+ data: {
+ authorization: { url: "https://connect.example.com/a/sca_1", userCode: "ABC-123" },
+ name: "notion",
+ sequence: 0,
+ stepIndex: 0,
+ turnId: "t1",
+ },
+ });
+ controller.close();
+ },
+ });
+ },
+ async getStreamTailIndex() {
+ return 0;
+ },
+ };
+
+ await firePost(
+ channel,
+ {
+ callback_query: {
+ id: "cb-auth",
+ from: { id: "U1", is_bot: false },
+ data: "eve_auth:U1",
+ message: {
+ message_id: 55,
+ chat: { id: -1001, type: "supergroup" },
+ },
+ },
+ },
+ { resolveSession: async () => session },
+ );
+
+ expect(JSON.parse(String((fetchMock.mock.calls[0]![1] as RequestInit).body))).toEqual({
+ chat_id: "-1001",
+ ephemeral_message_parameters: { callback_query_id: "cb-auth", receiver_user_id: "U1" },
+ reply_markup: {
+ inline_keyboard: [
+ [{ text: "Sign in with Notion", url: "https://connect.example.com/a/sca_1" }],
+ ],
+ },
+ text: "Authorization required for Notion.\n\nCode: ABC-123",
+ });
+ expect(JSON.parse(String((fetchMock.mock.calls[1]![1] as RequestInit).body))).toEqual({
+ callback_query_id: "cb-auth",
+ text: "Sign-in prompt sent privately.",
+ });
+ });
+
it("marks replies to bot messages as possible freeform HITL answers", async () => {
const channel = telegramChannel({
api: { fetch: fakeTelegramFetch() },
@@ -369,6 +434,140 @@ describe("telegramChannel() deliver hook", () => {
});
describe("telegramChannel() default event handlers", () => {
+ it("renders authorization privately in a direct chat and replaces it on completion", async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ ok: true,
+ result: { message_id: 71, chat: { id: 42, type: "private" } },
+ }),
+ ),
+ )
+ .mockResolvedValueOnce(new Response(JSON.stringify({ ok: true, result: true })))
+ .mockResolvedValueOnce(new Response(JSON.stringify({ ok: true, result: true })));
+ vi.stubGlobal("fetch", fetchMock);
+ const adapter = withState(
+ getAdapter(telegramChannel({ credentials: { botToken: "bot-token" } })),
+ { chatId: "42", chatType: "private" },
+ );
+ const ctx = buildAdapterContext(adapter, { get: () => undefined, set: () => {} } as any);
+
+ await callEvent(
+ adapter,
+ makeEvent("authorization.required", {
+ authorization: {
+ displayName: "Notion Workspace",
+ instructions: "Choose a workspace.",
+ url: "https://connect.example.com/a/sca_1",
+ userCode: "ABC-123",
+ },
+ name: "notion",
+ sequence: 0,
+ stepIndex: 0,
+ turnId: "t1",
+ }),
+ ctx,
+ );
+
+ expect(JSON.parse(String((fetchMock.mock.calls[0]![1] as RequestInit).body))).toEqual({
+ chat_id: "42",
+ reply_markup: {
+ inline_keyboard: [
+ [{ text: "Sign in with Notion Workspace", url: "https://connect.example.com/a/sca_1" }],
+ ],
+ },
+ text: "Authorization required for Notion Workspace.\n\nChoose a workspace.\n\nCode: ABC-123",
+ });
+ expect(ctx.state.pendingAuthMessageIds).toEqual({ notion: "71" });
+
+ await callEvent(
+ adapter,
+ makeEvent("authorization.completed", {
+ authorization: { displayName: "Notion Workspace" },
+ name: "notion",
+ outcome: "authorized",
+ sequence: 1,
+ stepIndex: 0,
+ turnId: "t1",
+ }),
+ ctx,
+ );
+
+ expect(JSON.parse(String((fetchMock.mock.calls[2]![1] as RequestInit).body))).toEqual({
+ chat_id: "42",
+ message_id: 71,
+ reply_markup: { inline_keyboard: [] },
+ text: "Notion Workspace connected.",
+ });
+ expect(ctx.state.pendingAuthMessageIds).toEqual({});
+ });
+
+ it("keeps the group status link-free and sends the challenge ephemerally", async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ ok: true,
+ result: { message_id: 72, chat: { id: -100, type: "group" } },
+ }),
+ ),
+ )
+ .mockResolvedValueOnce(new Response(JSON.stringify({ ok: true, result: true })))
+ .mockResolvedValueOnce(new Response(JSON.stringify({ ok: true, result: true })));
+ vi.stubGlobal("fetch", fetchMock);
+ const adapter = withState(
+ getAdapter(telegramChannel({ credentials: { botToken: "bot-token" } })),
+ { chatId: "-100", chatType: "group", triggeringUserId: "U1" },
+ );
+ const ctx = buildAdapterContext(adapter, { get: () => undefined, set: () => {} } as any);
+
+ await callEvent(
+ adapter,
+ makeEvent("authorization.required", {
+ authorization: { url: "https://connect.example.com/a/sca_1", userCode: "ABC-123" },
+ name: "notion",
+ sequence: 0,
+ stepIndex: 0,
+ turnId: "t1",
+ }),
+ ctx,
+ );
+
+ const publicBody = JSON.parse(String((fetchMock.mock.calls[0]![1] as RequestInit).body));
+ expect(publicBody).toEqual({
+ chat_id: "-100",
+ reply_markup: {
+ inline_keyboard: [[{ callback_data: "eve_auth:U1", text: "Authorize" }]],
+ },
+ text: "Authorization required for Notion. The requester must sign in to resume.",
+ });
+ expect(JSON.stringify(publicBody)).not.toContain("connect.example.com");
+
+ await callEvent(
+ adapter,
+ makeEvent("authorization.completed", {
+ name: "notion",
+ outcome: "declined",
+ reason: "access_denied",
+ sequence: 1,
+ stepIndex: 0,
+ turnId: "t1",
+ }),
+ ctx,
+ );
+
+ expect(JSON.parse(String((fetchMock.mock.calls[1]![1] as RequestInit).body))).toEqual({
+ chat_id: "-100",
+ message_id: 72,
+ reply_markup: { inline_keyboard: [] },
+ text: "Notion authorization declined (access_denied).",
+ });
+ expect(ctx.state.pendingAuthMessageIds).toEqual({});
+ });
+
it("restarts the typing indicator after authorization succeeds", async () => {
const fetchMock = vi.fn().mockResolvedValue(
new Response(JSON.stringify({ ok: true, result: true }), {
diff --git a/packages/eve/src/public/channels/telegram/telegramChannel.ts b/packages/eve/src/public/channels/telegram/telegramChannel.ts
index f18f51e16..42c1f82fa 100644
--- a/packages/eve/src/public/channels/telegram/telegramChannel.ts
+++ b/packages/eve/src/public/channels/telegram/telegramChannel.ts
@@ -1,6 +1,6 @@
import type { TelegramInstrumentationMetadata } from "#public/channels/telegram/index.js";
import { defaultDeliverResult, type ChannelAdapterContext } from "#channel/adapter.js";
-import type { ChannelFrom } from "#channel/channel-operations.js";
+import type { ChannelFrom, ChannelResolveSession } from "#channel/channel-operations.js";
import type { SessionHandle } from "#channel/session.js";
import type { DeliverPayload, SessionAuthContext, TurnPolicy } from "#channel/types.js";
import type { SessionContext } from "#public/definitions/callback-context.js";
@@ -12,6 +12,7 @@ import {
answerTelegramCallbackQuery,
callTelegramApi,
editTelegramMessageReplyMarkup,
+ editTelegramMessageText,
sendTelegramChatAction,
sendTelegramMessage,
splitTelegramMessageText,
@@ -22,6 +23,8 @@ import {
type TelegramMessageBody,
type TelegramMessageResult,
} from "#public/channels/telegram/api.js";
+import { TELEGRAM_AUTHORIZATION_CALLBACK_PREFIX } from "#public/channels/telegram/authorization.js";
+import { dispatchTelegramAuthorizationCallback } from "#public/channels/telegram/authorization-callback.js";
import {
buildTelegramTurnMessage,
collectTelegramFileParts,
@@ -52,6 +55,12 @@ import {
type UploadPolicy,
type UploadPolicyInput,
} from "#public/channels/upload-policy.js";
+import {
+ initialTelegramState,
+ stateFromTelegramCallbackQuery,
+ stateFromTelegramMessage,
+ telegramContinuationTokenFromState,
+} from "#public/channels/telegram/state.js";
import {
verifyTelegramRequest,
type TelegramWebhookSecretToken,
@@ -93,6 +102,8 @@ export interface TelegramChannelState extends TelegramHitlState {
messageThreadId: number | null;
/** Telegram user id that triggered the current session/turn. */
triggeringUserId?: string | null;
+ /** Public authorization status messages, keyed by connection name. */
+ pendingAuthMessageIds?: Record<string, string>;
}
/** Telegram channel credentials. `webhookVerifier` is a custom inbound webhook verifier for forwarded webhooks. */
@@ -189,6 +200,12 @@ export interface TelegramHandle {
request(method: string, body?: JsonObject): Promise<TelegramApiResponse>;
post(message: string | TelegramMessageBody): Promise<TelegramMessageResult>;
+ /** Posts a group or supergroup message visible only to `userId`. */
+ postEphemeral(
+ userId: number | string,
+ message: string | TelegramMessageBody,
+ options?: { readonly callbackQueryId?: string },
+ ): Promise<TelegramMessageResult>;
sendMessage(message: string | TelegramMessageBody): Promise<TelegramMessageResult>;
startTyping(action?: string): Promise<void>;
answerCallbackQuery(input: {
@@ -200,6 +217,11 @@ export interface TelegramHandle {
readonly messageId: number | string;
readonly replyMarkup?: Readonly<Record<string, unknown>>;
}): Promise<TelegramApiResponse>;
+ editMessageText(input: {
+ readonly messageId: number | string;
+ readonly replyMarkup?: Readonly<Record<string, unknown>>;
+ readonly text: string;
+ }): Promise<TelegramApiResponse>;
}
/** Concrete return type of {@link telegramChannel}. */
@@ -238,7 +260,7 @@ export function telegramChannel(config: TelegramChannelConfig = {}): TelegramCha
routes: [
POST<TelegramChannelState>(
config.route ?? "/eve/v1/telegram",
- async (req, { from, waitUntil }) => {
+ async (req, { from, resolveSession, waitUntil }) => {
const body = await verifyInbound(req, config.credentials);
if (body === null) return new Response("unauthorized", { status: 401 });
@@ -271,6 +293,7 @@ export function telegramChannel(config: TelegramChannelConfig = {}): TelegramCha
config,
query: update.callbackQuery,
from,
+ resolveSession,
}),
);
return new Response("ok");
@@ -311,7 +334,7 @@ export function telegramChannel(config: TelegramChannelConfig = {}): TelegramCha
await handle.sendMessage(initialMessage);
}
- return from(continuationTokenFromState(receiveState)).send(input.message, {
+ return from(telegramContinuationTokenFromState(receiveState)).send(input.message, {
auth: input.auth,
state: receiveState,
});
@@ -363,9 +386,15 @@ function buildTelegramHandle(input: {
}
async function sendOne(body: TelegramMessageBody): Promise<TelegramMessageResult> {
+ const posted = await sendMessage(body);
+ anchor(posted);
+ return posted;
+ }
+
+ async function sendMessage(body: TelegramMessageBody): Promise<TelegramMessageResult> {
const chatId = state.chatId ?? "";
if (!chatId) throw new Error("telegramChannel: missing chat id for outbound message.");
- const posted = await sendTelegramMessage({
+ return sendTelegramMessage({
apiBaseUrl: api?.apiBaseUrl,
body: {
...body,
@@ -376,8 +405,6 @@ function buildTelegramHandle(input: {
fileBaseUrl: api?.fileBaseUrl,
chatId,
});
- anchor(posted);
- return posted;
}
return {
@@ -408,9 +435,37 @@ function buildTelegramHandle(input: {
replyMarkup: args.replyMarkup,
});
},
+ editMessageText(args) {
+ const chatId = state.chatId ?? "";
+ if (!chatId) throw new Error("telegramChannel: missing chat id for text edit.");
+ return editTelegramMessageText({
+ apiBaseUrl: api?.apiBaseUrl,
+ chatId,
+ credentials,
+ fetch: api?.fetch,
+ messageId: args.messageId,
+ replyMarkup: args.replyMarkup,
+ text: args.text,
+ });
+ },
post(message) {
return postTelegramMessage(message, sendOne);
},
+ postEphemeral(userId, message, options) {
+ const body = typeof message === "string" ? { text: message } : message;
+ return postTelegramMessage(
+ {
+ ...body,
+ ephemeral_message_parameters: {
+ ...(options?.callbackQueryId === undefined
+ ? {}
+ : { callback_query_id: options.callbackQueryId }),
+ receiver_user_id: userId,
+ },
+ },
+ sendMessage,
+ );
+ },
request(method, body) {
return callTelegramApi({
apiBaseUrl: api?.apiBaseUrl,
@@ -455,7 +510,16 @@ async function postTelegramMessage(
let first: TelegramMessageResult | undefined;
for (const [index, text] of chunks.entries()) {
- const posted = await sendOne(index === 0 ? { ...body, text } : { text });
+ const posted = await sendOne(
+ index === 0
+ ? { ...body, text }
+ : {
+ ...(body.ephemeral_message_parameters === undefined
+ ? {}
+ : { ephemeral_message_parameters: body.ephemeral_message_parameters }),
+ text,
+ },
+ );
if (first === undefined) first = posted;
}
@@ -486,7 +550,7 @@ async function dispatchMessage(input: {
}): Promise<void> {
if (input.message.from?.isBot === true) return;
- const state = stateFromMessage(input.message, input.config);
+ const state = stateFromTelegramMessage(input.message, input.config.botUsername);
const telegram: TelegramContext = {
telegram: buildTelegramHandle({ config: input.config, state }),
};
@@ -527,7 +591,7 @@ async function dispatchMessage(input: {
: undefined;
try {
- const source = input.from(continuationTokenFromState(state));
+ const source = input.from(telegramContinuationTokenFromState(state));
if (replyInputResponses === undefined) {
await source.send(turnMessage, {
auth: result.auth,
@@ -550,12 +614,24 @@ async function dispatchCallbackQuery(input: {
readonly config: TelegramChannelConfig;
readonly query: TelegramCallbackQuery;
readonly from: ChannelFrom<TelegramChannelState>;
+ readonly resolveSession: ChannelResolveSession;
}): Promise<void> {
- const state = stateFromCallbackQuery(input.query, input.config);
+ const state = stateFromTelegramCallbackQuery(input.query, input.config.botUsername);
const telegram: TelegramContext = {
telegram: buildTelegramHandle({ config: input.config, state }),
};
+ if (input.query.data?.startsWith(TELEGRAM_AUTHORIZATION_CALLBACK_PREFIX) === true) {
+ await dispatchTelegramAuthorizationCallback({
+ continuationToken: telegramContinuationTokenFromState(state),
+ query: input.query,
+ resolveSession: input.resolveSession,
+ state,
+ telegram,
+ });
+ return;
+ }
+
if (input.query.data?.startsWith(TELEGRAM_HITL_CALLBACK_PREFIX) === true) {
try {
await telegram.telegram.answerCallbackQuery({
@@ -568,7 +644,7 @@ async function dispatchCallbackQuery(input: {
if (!input.query.message || !state.chatId) return;
try {
- const source = input.from(continuationTokenFromState(state));
+ const source = input.from(telegramContinuationTokenFromState(state));
await source.respond([telegramCallbackInputResponse(input.query.data)], {
auth: null,
});
@@ -616,73 +692,6 @@ function attachTelegramDeliver(channel: TelegramChannel): void {
};
}
-function stateFromMessage(
- message: TelegramMessage,
- config: TelegramChannelConfig,
-): TelegramChannelState {
- const privateChat = message.chat.type === "private";
- return {
- ...initialTelegramState(config.botUsername),
- chatId: message.chat.id,
- chatType: message.chat.type,
- conversationId: privateChat ? null : conversationIdForMessage(message),
- messageThreadId: message.messageThreadId ?? null,
- triggeringUserId: message.from?.id ?? null,
- };
-}
-
-function stateFromCallbackQuery(
- query: TelegramCallbackQuery,
- config: TelegramChannelConfig,
-): TelegramChannelState {
- const message = query.message;
- if (!message) {
- return {
- ...initialTelegramState(config.botUsername),
- triggeringUserId: query.from.id,
- };
- }
- const privateChat = message.chat.type === "private";
- return {
- ...initialTelegramState(config.botUsername),
- chatId: message.chat.id,
- chatType: message.chat.type,
- conversationId: privateChat ? null : message.messageId,
- messageThreadId: message.messageThreadId ?? null,
- triggeringUserId: query.from.id,
- };
-}
-
-function conversationIdForMessage(message: TelegramMessage): string {
- if (message.replyToMessage?.from?.isBot === true) {
- return message.replyToMessage.messageId;
- }
- return message.messageId;
-}
-
-function continuationTokenFromState(state: TelegramChannelState): string {
- const chatId = state.chatId ?? "";
- return telegramContinuationToken({
- chatId,
- conversationId: state.chatType === "private" ? undefined : (state.conversationId ?? undefined),
- messageThreadId: state.messageThreadId ?? undefined,
- });
-}
-
-function initialTelegramState(botUsername: string | undefined): TelegramChannelState {
- return {
- botUsername: botUsername ?? null,
- chatId: null,
- chatType: null,
- conversationId: null,
- hitlCallbacks: {},
- messageThreadId: null,
- nextHitlCallbackId: 0,
- pendingFreeformReplies: {},
- triggeringUserId: null,
- };
-}
-
function readChatId(value: unknown): string | undefined {
if (typeof value === "string" && value.length > 0) return value;
if (typeof value === "number" && Number.isFinite(value)) return String(value);