Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

[1/6] test(eve): add a HITL conformance suite for first-party channels (#4147)

Ben Pankow17161770b57c
diff --git a/packages/eve/src/internal/testing/channel-conformance/chat-sdk-driver.ts b/packages/eve/src/internal/testing/channel-conformance/chat-sdk-driver.ts
new file mode 100644
index 000000000..d88ece98f
--- /dev/null
+++ b/packages/eve/src/internal/testing/channel-conformance/chat-sdk-driver.ts
@@ -0,0 +1,193 @@
+import { chatSdkChannel } from "#public/channels/chat-sdk/index.js";
+import {
+ type Adapter,
+ type AdapterPostableMessage,
+ type ChatInstance,
+ Message,
+ type StateAdapter,
+ type WebhookOptions,
+ parseMarkdown,
+} from "#compiled/chat/index.js";
+import { createMemoryState } from "#compiled/@chat-adapter/state-memory/index.js";
+import type { ChannelDriver, PlatformCall } from "#internal/testing/channel-conformance/harness.js";
+
+const ADAPTER = "conformance";
+const PERSON = { fullName: "Alice", isBot: false, isMe: false, userId: "alice", userName: "alice" };
+let nextThread = 0;
+
+interface CardNode {
+ readonly children?: readonly CardNode[];
+ readonly content?: string;
+ readonly id?: string;
+ readonly label?: string;
+ readonly type?: string;
+ readonly value?: string;
+}
+
+type Inbound =
+ | { readonly kind: "message"; readonly text: string }
+ | { readonly kind: "action"; readonly actionId: string; readonly value?: string };
+
+/**
+ * Drives `chatSdkChannel` with a card-capable direct-message adapter: one
+ * thread, no streaming, and every message handed to eve with an empty
+ * `context`. The fake adapter is the platform: it reads inbound JSON and
+ * records every post and edit. Text-only adapters such as Linq and Photon
+ * flatten cards, so they need their own drivers.
+ */
+export function chatSdkDriver(): ChannelDriver {
+ nextThread += 1;
+ const threadId = `${ADAPTER}:D${nextThread}`;
+ let sequence = 0;
+
+ function inbound(body: Inbound): Request {
+ return new Request(`https://agent.example.com/eve/v1/${ADAPTER}`, {
+ body: JSON.stringify(body),
+ headers: { "content-type": "application/json" },
+ method: "POST",
+ });
+ }
+
+ return {
+ name: "chat-sdk",
+ capabilities: ["buttons", "text-replies"],
+ createChannel(record) {
+ const bridge = chatSdkChannel({
+ adapters: { [ADAPTER]: fakeAdapter(threadId, record, () => (sequence += 1)) },
+ concurrency: "concurrent",
+ routes: { [ADAPTER]: `/eve/v1/${ADAPTER}` },
+ state: createMemoryState() as StateAdapter,
+ streaming: false,
+ userName: "eve",
+ });
+ bridge.bot.onDirectMessage(async (thread, message) => {
+ await bridge.send(message.text, { auth: null, context: [], thread });
+ });
+ return bridge.channel;
+ },
+ message: (text) => inbound({ kind: "message", text }),
+ findOptions(call, prompt) {
+ if (call.method !== "postMessage" && call.method !== "editMessage") return undefined;
+ const card = cardOf(call.body as AdapterPostableMessage);
+ if (card === undefined || !texts(card).includes(prompt)) return undefined;
+ const buttons = nodes(card).filter((node) => node.type === "button" && node.id !== undefined);
+ return buttons.length === 0
+ ? undefined
+ : buttons.map((button) => ({ handle: button, label: button.label ?? "" }));
+ },
+ press(option) {
+ const button = option.handle as CardNode;
+ return inbound({ actionId: button.id!, kind: "action", value: button.value });
+ },
+ postedText(call: PlatformCall) {
+ if (call.method !== "postMessage" && call.method !== "editMessage") return undefined;
+ const posted = call.body as AdapterPostableMessage;
+ if (typeof posted === "string") return posted;
+ if ("markdown" in posted) return posted.markdown;
+ if ("raw" in posted) return posted.raw;
+ return undefined;
+ },
+ };
+}
+
+function fakeAdapter(
+ threadId: string,
+ record: (call: PlatformCall) => void,
+ nextId: () => number,
+): Adapter {
+ let chat: ChatInstance | null = null;
+ const self = {
+ name: ADAPTER,
+ userName: "eve",
+ async initialize(instance: ChatInstance) {
+ chat = instance;
+ },
+ async handleWebhook(request: Request, options?: WebhookOptions) {
+ const body = (await request.json()) as Inbound;
+ const id = `inbound-${nextId()}`;
+ if (body.kind === "action") {
+ await chat?.processAction(
+ {
+ actionId: body.actionId,
+ adapter,
+ messageId: id,
+ raw: body,
+ threadId,
+ user: PERSON,
+ value: body.value,
+ },
+ options,
+ );
+ } else {
+ await chat?.processMessage(
+ adapter,
+ threadId,
+ inboundMessage(threadId, id, body.text),
+ options,
+ );
+ }
+ return new Response("ok");
+ },
+ channelIdFromThreadId: () => threadId,
+ decodeThreadId: (id: string) => ({ threadId: id }),
+ encodeThreadId: (input: { threadId: string }) => input.threadId,
+ getChannelVisibility: () => "private" as const,
+ isDM: () => true,
+ parseMessage: (raw: { text?: string }) => inboundMessage(threadId, "parsed", raw.text ?? ""),
+ renderFormatted: () => "",
+ fetchMessages: async () => ({ messages: [] }),
+ fetchThread: async (id: string) => ({
+ channelId: threadId,
+ channelVisibility: "private" as const,
+ id,
+ isDM: true,
+ metadata: {},
+ }),
+ async postMessage(id: string, posted: AdapterPostableMessage) {
+ const messageId = `posted-${nextId()}`;
+ record({ body: posted, method: "postMessage", response: { id: messageId } });
+ return { id: messageId, raw: posted, threadId: id };
+ },
+ async editMessage(id: string, messageId: string, posted: AdapterPostableMessage) {
+ record({ body: posted, method: "editMessage", response: { id: messageId } });
+ return { id: messageId, raw: posted, threadId: id };
+ },
+ async addReaction() {},
+ async deleteMessage() {},
+ async removeReaction() {},
+ async startTyping() {},
+ };
+ // Chat SDK adapters have many optional members; the fake implements the ones eve calls.
+ const adapter: Adapter = self as typeof self & Adapter;
+ return adapter;
+}
+
+function inboundMessage(threadId: string, id: string, text: string): Message {
+ return new Message({
+ attachments: [],
+ author: PERSON,
+ formatted: parseMarkdown(text),
+ id,
+ isMention: false,
+ metadata: { dateSent: new Date("2026-01-01T00:00:00.000Z"), edited: false },
+ raw: { text },
+ text,
+ threadId,
+ });
+}
+
+function cardOf(posted: AdapterPostableMessage): CardNode | undefined {
+ if (typeof posted !== "object" || posted === null) return undefined;
+ if ("card" in posted) return posted.card as CardNode;
+ return (posted as CardNode).type === "card" ? (posted as CardNode) : undefined;
+}
+
+function nodes(node: CardNode): CardNode[] {
+ return [node, ...(node.children ?? []).flatMap(nodes)];
+}
+
+function texts(node: CardNode): string {
+ return nodes(node)
+ .flatMap((child) => (child.content === undefined ? [] : [child.content]))
+ .join("\n");
+}
diff --git a/packages/eve/src/internal/testing/channel-conformance/contract.ts b/packages/eve/src/internal/testing/channel-conformance/contract.ts
new file mode 100644
index 000000000..a1e8c9ce0
--- /dev/null
+++ b/packages/eve/src/internal/testing/channel-conformance/contract.ts
@@ -0,0 +1,63 @@
+import { expect } from "vitest";
+
+import type {
+ ChannelCapability,
+ ChannelConversation,
+} from "#internal/testing/channel-conformance/harness.js";
+
+/**
+ * One behavior every first-party channel owes a person, stated once and run
+ * against every channel whose platform has the capabilities it `requires`.
+ */
+export interface ContractRule {
+ /** The behavior, in one sentence. Also the test name. */
+ readonly rule: string;
+ /** Where the behavior is promised: a docs anchor or the PR that introduced it. */
+ readonly source: string;
+ readonly requires: readonly ChannelCapability[];
+ run(conversation: ChannelConversation): Promise<void>;
+}
+
+const ASK =
+ 'Use ask_question and set question to: "Which day works for the review?" with label "Saturday" and label "Sunday".';
+const PROMPT = "Which day works for the review?";
+
+async function askWhichDay(conversation: ChannelConversation) {
+ await conversation.say(ASK);
+ const options = await conversation.waitForQuestion(PROMPT);
+ expect(options.map((option) => option.label)).toEqual(["Saturday", "Sunday"]);
+ return options;
+}
+
+function expectAnsweredSaturday(output: unknown) {
+ // The message carries the real output so a broken cell's symptom can match it.
+ expect(output, `ask_question returned ${JSON.stringify(output)}`).toEqual({
+ answer: "Saturday",
+ status: "answered",
+ });
+}
+
+export const hitlContract = [
+ {
+ rule: "pressing a rendered option answers the pending question with that option",
+ source: "docs/tools/human-in-the-loop.md#answering-from-a-client-or-channel",
+ requires: ["buttons"],
+ async run(conversation) {
+ const [saturday] = await askWhichDay(conversation);
+ await conversation.press(saturday!);
+ expectAnsweredSaturday(await conversation.waitForToolResult("ask_question"));
+ },
+ },
+ {
+ rule: "a text reply matching an option answers the only pending question",
+ source: "docs/tools/human-in-the-loop.md#how-pause-and-resume-works",
+ requires: ["text-replies"],
+ async run(conversation) {
+ await askWhichDay(conversation);
+ await conversation.say("Saturday");
+ expectAnsweredSaturday(await conversation.waitForToolResult("ask_question"));
+ },
+ },
+] as const satisfies readonly ContractRule[];
+
+export type HitlRule = (typeof hitlContract)[number]["rule"];
diff --git a/packages/eve/src/internal/testing/channel-conformance/harness.ts b/packages/eve/src/internal/testing/channel-conformance/harness.ts
new file mode 100644
index 000000000..57d75d2fd
--- /dev/null
+++ b/packages/eve/src/internal/testing/channel-conformance/harness.ts
@@ -0,0 +1,224 @@
+import { createChannelOperations } from "#channel/channel-operations.js";
+import { type CompiledChannel, isCompiledChannel } from "#channel/compiled-channel.js";
+import { type RouteHandlerArgs, isHttpRouteDefinition } from "#channel/routes.js";
+import { createWorkflowRuntime } from "#execution/workflow-runtime.js";
+import { createTestRuntime } from "#internal/testing/app-harness.js";
+import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
+import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";
+import type { Session } from "#channel/session.js";
+import { askQuestion } from "#tools/provided/ask-question.js";
+
+/** One outbound call a channel made to its platform API. */
+export interface PlatformCall {
+ readonly body: unknown;
+ readonly method: string;
+ /** The JSON the fake platform answered with. */
+ readonly response: unknown;
+}
+
+/** A choice the platform rendered for a person, with whatever the driver needs to press it. */
+export interface RenderedOption {
+ readonly label: string;
+ readonly handle: unknown;
+}
+
+/**
+ * What a platform can do for a person, independent of eve. A rule that needs a
+ * capability a driver lacks is skipped for that channel as "not supported".
+ */
+export type ChannelCapability =
+ /** A person can press a rendered choice. */
+ | "buttons"
+ /** A person can send a plain-text message to the conversation. */
+ | "text-replies";
+
+/**
+ * Teaches the HITL conformance suite to speak one channel's platform protocol.
+ *
+ * Drivers translate only between platform wire formats and conversation
+ * actions. They never read session state, so they keep working across changes
+ * to how eve stores and routes requests.
+ */
+export interface ChannelDriver {
+ readonly name: string;
+ readonly capabilities: readonly ChannelCapability[];
+ /**
+ * Builds the channel against a fake platform that reports each outbound call
+ * to `record`. HTTP platforms use {@link recordingFetch}.
+ */
+ createChannel(record: (call: PlatformCall) => void): unknown;
+ /** A webhook request carrying a person's message. */
+ message(text: string): Request;
+ /** Options rendered in one outbound call for a question, or `undefined` when it isn't one. */
+ findOptions(call: PlatformCall, prompt: string): readonly RenderedOption[] | undefined;
+ /** A webhook request pressing a rendered option. */
+ press(option: RenderedOption): Request;
+ /** Text the bot posted in one outbound call, if any. */
+ postedText(call: PlatformCall): string | undefined;
+}
+
+/** What a person can do and see in one channel conversation. Contract rules use only this. */
+export interface ChannelConversation {
+ /** The person sends a plain-text message. */
+ say(text: string): Promise<void>;
+ /** Waits for the bot to post `prompt` with choices, returning them. */
+ waitForQuestion(prompt: string): Promise<readonly RenderedOption[]>;
+ /** The person presses one rendered choice. */
+ press(option: RenderedOption): Promise<void>;
+ /** Waits until `tool` returns, as visible in the bot's reply, and returns its output. */
+ waitForToolResult(tool: string): Promise<unknown>;
+}
+
+const WAIT_TIMEOUT_MS = 15_000;
+
+/** A `fetch` for an HTTP platform API: `decode` turns each request into a call and its answer. */
+export function recordingFetch(
+ record: (call: PlatformCall) => void,
+ decode: (request: Request) => Promise<PlatformCall>,
+): typeof globalThis.fetch {
+ return async (input, init) => {
+ const call = await decode(new Request(input, init));
+ record(call);
+ return Response.json(call.response);
+ };
+}
+
+/**
+ * Runs `body` against an agent with `ask_question` and `driver`'s channel. Every
+ * interaction goes through the channel's real webhook routes; the only fake is
+ * the platform API behind the channel's injected `fetch`.
+ */
+export async function withChannelConversation(
+ driver: ChannelDriver,
+ body: (conversation: ChannelConversation) => Promise<void>,
+): Promise<void> {
+ const calls: PlatformCall[] = [];
+ const created = driver.createChannel((call) => void calls.push(call));
+ if (!isCompiledChannel(created)) throw new Error(`${driver.name} is not a compiled channel.`);
+ const channel: CompiledChannel = created;
+
+ const runtime = await createTestRuntime({
+ agent: { name: `${driver.name}-hitl-conformance` },
+ modules: [
+ {
+ logicalPath: "tools/ask_question.ts",
+ loadNamespace: async () => ({ default: askQuestion() }),
+ },
+ {
+ logicalPath: `channels/${driver.name}.ts`,
+ loadNamespace: async () => ({ default: channel }),
+ },
+ ],
+ });
+
+ await runtime.run(async () => {
+ const compiledArtifactsSource = createBundledRuntimeCompiledArtifactsSource();
+ const bundle = await getCompiledRuntimeAgentBundle({ compiledArtifactsSource });
+ const entry = bundle.graph.root.channels.find((candidate) => candidate.name === driver.name);
+ if (entry?.adapter === undefined) throw new Error(`Expected the ${driver.name} adapter.`);
+ // Mirrors the operations production route dispatch builds for each request.
+ const operations = createChannelOperations({
+ adapter: entry.adapter,
+ channelName: driver.name,
+ runtime: createWorkflowRuntime({ compiledArtifactsSource }),
+ turnPolicy: entry.turnPolicy,
+ });
+ const sessions = new Map<string, Session>();
+
+ async function post(request: Request): Promise<void> {
+ const pending: Promise<unknown>[] = [];
+ const args: RouteHandlerArgs = {
+ ...operations,
+ from: (address) => {
+ const source = operations.from(address);
+ return {
+ ...source,
+ send: async (...sendArgs) => track(await source.send(...sendArgs)),
+ respond: async (...respondArgs) => track(await source.respond(...respondArgs)),
+ };
+ },
+ attachSession: unsupported("attachSession"),
+ params: {},
+ requestIp: null,
+ to: unsupported("to"),
+ waitUntil: (task) => void pending.push(task),
+ };
+ const response = await findRoute(channel, request).handler(request, args);
+ await Promise.all(pending);
+ if (!response.ok) throw new Error(`${driver.name} webhook answered ${response.status}.`);
+ }
+
+ async function waitFor<T>(label: string, select: (call: PlatformCall) => T | undefined) {
+ const deadline = Date.now() + WAIT_TIMEOUT_MS;
+ while (Date.now() < deadline) {
+ for (const call of calls) {
+ const selected = select(call);
+ if (selected !== undefined) return selected;
+ }
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ }
+ throw new Error(
+ `Timed out waiting for ${label} on ${driver.name}. Platform calls:\n${JSON.stringify(calls, null, 2)}`,
+ );
+ }
+
+ const conversation: ChannelConversation = {
+ say: (text) => post(driver.message(text)),
+ press: (option) => post(driver.press(option)),
+ waitForQuestion: (prompt) =>
+ waitFor(`the question "${prompt}"`, (call) => driver.findOptions(call, prompt)),
+ waitForToolResult: (tool) =>
+ waitFor(`${tool} to return`, (call) => {
+ const text = driver.postedText(call);
+ return text === undefined ? undefined : readMockToolReply(text, tool);
+ }),
+ };
+
+ function track(session: Session): Session {
+ sessions.set(session.id, session);
+ return session;
+ }
+
+ try {
+ await body(conversation);
+ } finally {
+ await Promise.allSettled([...sessions.values()].map((session) => session.cancel()));
+ }
+ });
+}
+
+function findRoute(channel: CompiledChannel, request: Request) {
+ const { pathname } = new URL(request.url);
+ const route = channel.routes.find(
+ (candidate) =>
+ isHttpRouteDefinition(candidate) &&
+ candidate.method === request.method &&
+ candidate.path === pathname,
+ );
+ if (route === undefined || !isHttpRouteDefinition(route)) {
+ throw new Error(`No ${request.method} route for ${pathname}.`);
+ }
+ return route;
+}
+
+function unsupported(name: string): () => never {
+ return () => {
+ throw new Error(`The HITL conformance harness does not provide ctx.${name}.`);
+ };
+}
+
+/**
+ * After a tool returns, the deterministic test model replies
+ * `Used <tool> for "<message>": <JSON output>`. Reading the output back from
+ * the posted reply keeps rules on what a person sees.
+ */
+function readMockToolReply(text: string, tool: string): unknown {
+ if (!text.startsWith(`Used ${tool} for "`)) return undefined;
+ const output = /": (\{.*\})\s*$/su.exec(text)?.[1];
+ if (output === undefined) return undefined;
+ try {
+ return JSON.parse(output) as unknown;
+ } catch {
+ return undefined;
+ }
+}
diff --git a/packages/eve/src/internal/testing/channel-conformance/slack-driver.ts b/packages/eve/src/internal/testing/channel-conformance/slack-driver.ts
new file mode 100644
index 000000000..1cc36f454
--- /dev/null
+++ b/packages/eve/src/internal/testing/channel-conformance/slack-driver.ts
@@ -0,0 +1,181 @@
+import { createHmac } from "node:crypto";
+
+import { slackChannel } from "#public/channels/slack/index.js";
+import { HITL_ACTION_PREFIX } from "#public/channels/slack/hitl.js";
+import {
+ type ChannelDriver,
+ type PlatformCall,
+ type RenderedOption,
+ recordingFetch,
+} from "#internal/testing/channel-conformance/harness.js";
+import { decodeSlackApiBody } from "#internal/testing/slack-api-body.js";
+
+const SIGNING_SECRET = "slack-conformance-secret";
+const PERSON = "U_ALICE";
+let nextChannel = 0;
+const TEAM = "T01";
+
+interface SlackText {
+ readonly text: string;
+ readonly type: string;
+}
+
+interface SlackOption {
+ readonly text: SlackText;
+ readonly value: string;
+}
+
+/** The HITL widgets eve renders: one button per option, or one single-click radio/select. */
+interface SlackElement {
+ readonly action_id: string;
+ readonly options?: readonly SlackOption[];
+ readonly text?: SlackText;
+ readonly type: string;
+ readonly value?: string;
+}
+
+interface PressHandle {
+ readonly action: Record<string, unknown>;
+ readonly messageTs: string;
+}
+
+/** Drives the Slack channel through its Events API and interactivity webhooks in a DM. */
+export function slackDriver(): ChannelDriver {
+ // A fresh DM per driver keeps each test's session apart in the shared workflow world.
+ nextChannel += 1;
+ const CHANNEL = `D${String(nextChannel).padStart(3, "0")}`;
+ let sequence = 0;
+ // Every message is a reply in the thread the first one starts.
+ const threadTs = "1700000000.000001";
+ let threadStarted = false;
+
+ function nextTs(): string {
+ sequence += 1;
+ return `1700000001.${String(sequence).padStart(6, "0")}`;
+ }
+
+ function signed(body: string, contentType: string): Request {
+ const timestamp = Math.floor(Date.now() / 1000);
+ const signature = `v0=${createHmac("sha256", SIGNING_SECRET).update(`v0:${timestamp}:${body}`).digest("hex")}`;
+ return new Request("https://agent.example.com/eve/v1/slack", {
+ body,
+ headers: {
+ "content-type": contentType,
+ "x-slack-request-timestamp": String(timestamp),
+ "x-slack-signature": signature,
+ },
+ method: "POST",
+ });
+ }
+
+ async function decode(request: Request): Promise<PlatformCall> {
+ const method = new URL(request.url).pathname.split("/").at(-1)!;
+ const body = decodeSlackApiBody(await request.text(), request.headers.get("content-type"));
+ const ts = nextTs();
+ return {
+ body,
+ method,
+ response: {
+ bot_id: "B_EVE",
+ channel: CHANNEL,
+ message: { ts },
+ messages: [],
+ ok: true,
+ team_id: TEAM,
+ ts,
+ user_id: "U_EVE",
+ },
+ };
+ }
+
+ return {
+ name: "slack",
+ capabilities: ["buttons", "text-replies"],
+ createChannel: (record) =>
+ slackChannel({
+ api: { fetch: recordingFetch(record, decode) },
+ credentials: { botToken: "xoxb-conformance", signingSecret: SIGNING_SECRET },
+ }),
+ message: (text) => {
+ const ts = threadStarted ? nextTs() : threadTs;
+ const thread = threadStarted ? { thread_ts: threadTs } : {};
+ threadStarted = true;
+ return signed(
+ JSON.stringify({
+ event: {
+ ...thread,
+ channel: CHANNEL,
+ channel_type: "im",
+ event_ts: ts,
+ text,
+ ts,
+ type: "message",
+ user: PERSON,
+ },
+ event_id: `Ev${ts}`,
+ team_id: TEAM,
+ type: "event_callback",
+ }),
+ "application/json",
+ );
+ },
+ findOptions(call, prompt) {
+ if (call.method !== "chat.postMessage" && call.method !== "chat.update") return undefined;
+ const body = call.body as { readonly blocks?: readonly unknown[] };
+ if (body.blocks === undefined || !JSON.stringify(body.blocks).includes(prompt))
+ return undefined;
+ const messageTs = (call.response as { readonly ts: string }).ts;
+ const options = body.blocks.flatMap((block) =>
+ ((block as { readonly elements?: readonly SlackElement[] }).elements ?? [])
+ .filter((element) => element.action_id.startsWith(HITL_ACTION_PREFIX))
+ .flatMap((element) => renderedOptions(element, messageTs)),
+ );
+ return options.length === 0 ? undefined : options;
+ },
+ press: (option) => {
+ const { action, messageTs } = option.handle as PressHandle;
+ const payload = {
+ actions: [action],
+ channel: { id: CHANNEL },
+ message: { thread_ts: threadTs, ts: messageTs },
+ team: { id: TEAM },
+ type: "block_actions",
+ user: { id: PERSON, name: "alice", team_id: TEAM, username: "alice" },
+ };
+ return signed(
+ new URLSearchParams({ payload: JSON.stringify(payload) }).toString(),
+ "application/x-www-form-urlencoded",
+ );
+ },
+ postedText(call: PlatformCall) {
+ if (!call.method.startsWith("chat.")) return undefined;
+ const body = call.body as {
+ readonly chunks?: readonly { readonly text?: string }[];
+ readonly markdown_text?: string;
+ readonly text?: string;
+ };
+ return (
+ body.markdown_text ?? body.text ?? body.chunks?.map((chunk) => chunk.text ?? "").join("")
+ );
+ },
+ };
+}
+
+function renderedOptions(element: SlackElement, messageTs: string): RenderedOption[] {
+ if (element.type === "button" && element.text !== undefined) {
+ const action = {
+ action_id: element.action_id,
+ text: element.text,
+ type: "button",
+ value: element.value,
+ };
+ return [{ handle: { action, messageTs } satisfies PressHandle, label: element.text.text }];
+ }
+ return (element.options ?? []).map((option) => ({
+ handle: {
+ action: { action_id: element.action_id, selected_option: option, type: element.type },
+ messageTs,
+ } satisfies PressHandle,
+ label: option.text.text,
+ }));
+}
diff --git a/packages/eve/src/internal/testing/channel-conformance/telegram-driver.ts b/packages/eve/src/internal/testing/channel-conformance/telegram-driver.ts
new file mode 100644
index 000000000..a724288c5
--- /dev/null
+++ b/packages/eve/src/internal/testing/channel-conformance/telegram-driver.ts
@@ -0,0 +1,83 @@
+import { telegramChannel } from "#public/channels/telegram/index.js";
+import {
+ type ChannelDriver,
+ type PlatformCall,
+ recordingFetch,
+} from "#internal/testing/channel-conformance/harness.js";
+
+const SECRET = "telegram-conformance-secret";
+let nextChatId = 1000;
+
+interface InlineButton {
+ readonly callback_data?: string;
+ readonly text: string;
+}
+
+/** Drives the Telegram channel through its Bot API webhook in a private chat. */
+export function telegramDriver(): ChannelDriver {
+ // A fresh chat per driver keeps each test's session apart in the shared workflow world.
+ nextChatId += 1;
+ const CHAT = { id: nextChatId, type: "private" } as const;
+ const PERSON = { first_name: "Alice", id: nextChatId, is_bot: false } as const;
+ let updateId = 0;
+ let messageId = 0;
+
+ function update(payload: Record<string, unknown>): Request {
+ updateId += 1;
+ return new Request("https://agent.example.com/eve/v1/telegram", {
+ body: JSON.stringify({ update_id: updateId, ...payload }),
+ headers: {
+ "content-type": "application/json",
+ "x-telegram-bot-api-secret-token": SECRET,
+ },
+ method: "POST",
+ });
+ }
+
+ async function decode(request: Request): Promise<PlatformCall> {
+ const method = new URL(request.url).pathname.split("/").at(-1)!;
+ const text = await request.text();
+ messageId += 1;
+ return {
+ body: text === "" ? {} : JSON.parse(text),
+ method,
+ response: { ok: true, result: { chat: CHAT, date: 0, message_id: messageId } },
+ };
+ }
+
+ return {
+ name: "telegram",
+ capabilities: ["buttons", "text-replies"],
+ createChannel: (record) =>
+ telegramChannel({
+ api: { fetch: recordingFetch(record, decode) },
+ credentials: { botToken: "bot-token", webhookSecretToken: SECRET },
+ }),
+ message: (text) =>
+ update({ message: { chat: CHAT, date: 0, from: PERSON, message_id: 1000 + updateId, text } }),
+ findOptions(call, prompt) {
+ const body = call.body as {
+ readonly reply_markup?: { readonly inline_keyboard?: readonly InlineButton[][] };
+ readonly text?: string;
+ };
+ if (call.method !== "sendMessage" || body.text?.includes(prompt) !== true) return undefined;
+ return body.reply_markup?.inline_keyboard
+ ?.flat()
+ .filter((button) => button.callback_data !== undefined)
+ .map((button) => ({ handle: button.callback_data, label: button.text }));
+ },
+ press: (option) =>
+ update({
+ callback_query: {
+ data: option.handle,
+ from: PERSON,
+ id: `callback-${updateId}`,
+ message: { chat: CHAT, date: 0, message_id: 1 },
+ },
+ }),
+ postedText: (call: PlatformCall) =>
+ call.method === "sendMessage" || call.method === "editMessageText"
+ ? (call.body as { readonly text?: string }).text
+ : undefined,
+ };
+}
diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts
index 52c311729..747c67a8d 100644
--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts
+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts
@@ -718,7 +718,7 @@ describe("chatSdkChannel", () => {
expect(state.pendingToolCallMessage).toBe("Let me check that.");
});
- it("renders input requests as Chat SDK cards and resumes on button actions", async () => {
+ it("renders input requests as Chat SDK cards with one button per option", async () => {
const adapter = testAdapter();
const bridge = chatSdkChannel({
adapters: { test: adapter },
@@ -780,17 +780,6 @@ describe("chatSdkChannel", () => {
],
type: "card",
});
-
- const { send } = await firePost(bridge.channel, "/eve/v1/test", {
- actionId: "eve_input:request-1:approve",
- kind: "action",
- value: "approve",
- });
-
- expect(send).toHaveBeenCalledWith(THREAD_ID, {
- auth: null,
- inputResponses: [{ optionId: "approve", requestId: "request-1" }],
- });
});
});
diff --git a/packages/eve/src/public/channels/hitl-conformance.integration.test.ts b/packages/eve/src/public/channels/hitl-conformance.integration.test.ts
new file mode 100644
index 000000000..74596ba6e
--- /dev/null
+++ b/packages/eve/src/public/channels/hitl-conformance.integration.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it } from "vitest";
+
+import { type HitlRule, hitlContract } from "#internal/testing/channel-conformance/contract.js";
+import {
+ type ChannelDriver,
+ withChannelConversation,
+} from "#internal/testing/channel-conformance/harness.js";
+import { chatSdkDriver } from "#internal/testing/channel-conformance/chat-sdk-driver.js";
+import { slackDriver } from "#internal/testing/channel-conformance/slack-driver.js";
+import { telegramDriver } from "#internal/testing/channel-conformance/telegram-driver.js";
+
+interface BrokenCell {
+ readonly reason: string;
+ /** Matches the error this rule fails with today. */
+ readonly symptom: RegExp;
+}
+
+/**
+ * Runs the HITL contract against every registered channel driver. Each cell is one of:
+ *
+ * - must pass;
+ * - not supported: the platform lacks a capability the rule requires (skipped);
+ * - broken: the channel should pass but doesn't yet. The cell passes only when
+ * the rule fails with the recorded `symptom`, so a fix or an unrelated
+ * failure (such as harness breakage) both turn it red.
+ */
+const channels: readonly {
+ readonly driver: () => ChannelDriver;
+ readonly broken?: Partial<Record<HitlRule, BrokenCell>>;
+}[] = [
+ { driver: chatSdkDriver },
+ {
+ driver: slackDriver,
+ broken: {
+ "a text reply matching an option answers the only pending question": {
+ reason: "the answer is the whole <slack_message> envelope",
+ symptom: /ask_question returned \{"answer":"<slack_message>/,
+ },
+ },
+ },
+ {
+ driver: telegramDriver,
+ broken: {
+ "a text reply matching an option answers the only pending question": {
+ reason: "the reply's context block reaches the model as its own message after the answer",
+ // The question resolves, then the bot answers the leftover context block.
+ symptom:
+ /Timed out waiting for ask_question to return[\s\S]*Bootstrap reply \[Tool execution\]: <telegram_context>/,
+ },
+ },
+ },
+];
+
+describe.each(channels.map((entry) => ({ ...entry, name: entry.driver().name })))(
+ "$name HITL contract",
+ ({ driver, broken }) => {
+ for (const rule of hitlContract) {
+ const { capabilities } = driver();
+ const supported = rule.requires.every((capability) => capabilities.includes(capability));
+ const known = broken?.[rule.rule];
+ const run = () => withChannelConversation(driver(), (c) => rule.run(c));
+ if (!supported) {
+ it.skip(`${rule.rule} (not supported)`, run);
+ } else if (known === undefined) {
+ it(rule.rule, run, 60_000);
+ } else {
+ it(
+ `${rule.rule} (broken: ${known.reason})`,
+ () => expect(run()).rejects.toThrow(known.symptom),
+ 60_000,
+ );
+ }
+ }
+ },
+);
diff --git a/packages/eve/src/public/channels/telegram/telegramChannel.integration.test.ts b/packages/eve/src/public/channels/telegram/telegramChannel.integration.test.ts
deleted file mode 100644
index b13e60e64..000000000
--- a/packages/eve/src/public/channels/telegram/telegramChannel.integration.test.ts
+++ /dev/null
@@ -1,174 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { createChannelOperations } from "#channel/channel-operations.js";
-import { isCompiledChannel } from "#channel/compiled-channel.js";
-import { isHttpRouteDefinition } from "#channel/routes.js";
-import { workflowEntry } from "#execution/session/entry.js";
-import { createWorkflowRuntime } from "#execution/workflow-runtime.js";
-import { createTestRuntime } from "#internal/testing/app-harness.js";
-import { captureTurnEvents, filterEventsByType } from "#internal/testing/events.js";
-import { buildWorkflowToolSerializedContext } from "#internal/testing/workflow-tool-run-harness.js";
-import { start } from "#internal/workflow/runtime.js";
-import { telegramContinuationToken } from "#public/channels/telegram/api.js";
-import { telegramChannel } from "#public/channels/telegram/index.js";
-import { initialTelegramState } from "#public/channels/telegram/state.js";
-import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
-import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";
-import { askQuestion } from "#tools/provided/ask-question.js";
-
-const SECRET = "telegram-secret";
-const CHAT_ID = "42";
-
-interface TelegramApiCall {
- readonly body: Record<string, unknown>;
- readonly method: string;
-}
-
-async function withTimeout<T>(promise: Promise<T>, label: string): Promise<T> {
- let timer: ReturnType<typeof setTimeout> | undefined;
- const timeout = new Promise<never>((_, reject) => {
- timer = setTimeout(() => reject(new Error(`Timed out waiting for ${label}.`)), 15_000);
- });
- try {
- return await Promise.race([promise, timeout]);
- } finally {
- clearTimeout(timer);
- }
-}
-
-describe("telegram channel", () => {
- it("answers an ask_question question when its inline button is pressed", async () => {
- const calls: TelegramApiCall[] = [];
- const channel = telegramChannel({
- api: {
- fetch: async (input, init) => {
- const method = String(input).split("/").at(-1)!;
- calls.push({ body: JSON.parse(String(init?.body ?? "{}")), method });
- return Response.json({
- ok: true,
- result: { chat: { id: 42, type: "private" }, date: 0, message_id: calls.length },
- });
- },
- },
- credentials: { botToken: "bot-token", webhookSecretToken: SECRET },
- });
- if (!isCompiledChannel(channel)) throw new Error("Expected a compiled Telegram channel.");
- const route = channel.routes.find((candidate) => candidate.method === "POST");
- if (route === undefined || !isHttpRouteDefinition(route)) {
- throw new Error("Expected the Telegram webhook route.");
- }
- const runtime = await createTestRuntime({
- agent: { name: "telegram-ask-question" },
- modules: [
- {
- logicalPath: "tools/ask_question.ts",
- loadNamespace: async () => ({ default: askQuestion() }),
- },
- { logicalPath: "channels/telegram.ts", loadNamespace: async () => ({ default: channel }) },
- ],
- });
-
- await runtime.run(async () => {
- const bundle = await getCompiledRuntimeAgentBundle({
- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
- });
- const adapter = bundle.graph.root.channels.find(
- (entry) => entry.name === "telegram",
- )?.adapter;
- if (adapter === undefined) throw new Error("Expected the Telegram adapter.");
- // Channel addresses namespace their token with the channel name.
- const continuationToken = `telegram:${telegramContinuationToken({ chatId: CHAT_ID })}`;
- const run = await start(workflowEntry, [
- {
- kind: "initial",
- ownerDeploymentId: "dpl_inline",
- input: {
- message:
- 'Use ask_question and set question to: "When?" with label "Saturday" and label "Sunday".',
- },
- serializedContext: {
- ...buildWorkflowToolSerializedContext({ continuationToken, requestInput: true }),
- "eve.channel": {
- kind: adapter.kind,
- state: {
- ...initialTelegramState(undefined),
- chatId: CHAT_ID,
- chatType: "private",
- triggeringUserId: CHAT_ID,
- },
- },
- },
- },
- ]);
- const stream = captureTurnEvents(run);
-
- try {
- const asked = await withTimeout(stream.nextTurn(), "the question");
- expect(filterEventsByType(asked, "input.requested")).toHaveLength(1);
- expect(asked.at(-1)?.type).toBe("turn.waiting");
-
- const question = calls.find(
- (call) => call.method === "sendMessage" && call.body.text === "When?",
- );
- const keyboard = (
- question?.body.reply_markup as
- | { inline_keyboard: { callback_data: string; text: string }[][] }
- | undefined
- )?.inline_keyboard.flat();
- const saturday = keyboard?.find((button) => button.text === "Saturday");
- expect(saturday?.callback_data).toMatch(/^eve:/);
-
- const operations = createChannelOperations<unknown>({
- adapter,
- channelName: "telegram",
- runtime: createWorkflowRuntime({
- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
- }),
- });
- const pending: Promise<unknown>[] = [];
- const response = await route.handler(
- new Request("https://agent.example.com/eve/v1/telegram", {
- body: JSON.stringify({
- callback_query: {
- data: saturday!.callback_data,
- from: { id: 42, is_bot: false },
- id: "cb-saturday",
- message: { chat: { id: 42, type: "private" }, date: 0, message_id: 1 },
- },
- update_id: 2,
- }),
- headers: {
- "content-type": "application/json",
- "x-telegram-bot-api-secret-token": SECRET,
- },
- method: "POST",
- }),
- {
- ...operations,
- attachSession: (() => undefined) as never,
- params: {},
- requestIp: null,
- to: (() => undefined) as never,
- waitUntil: (task) => void pending.push(task),
- },
- );
- expect(response.status).toBe(200);
- await Promise.all(pending);
-
- const answered = await withTimeout(stream.nextTurn(), "the pressed answer");
- const result = filterEventsByType(answered, "action.result").find(
- (event) =>
- event.data.result.kind === "tool-result" &&
- event.data.result.toolName === "ask_question",
- );
- expect(result?.data.result.output).toEqual({
- answer: "Saturday",
- status: "answered",
- });
- } finally {
- stream.dispose();
- await run.cancel();
- }
- });
- }, 60_000);
-});
diff --git a/packages/eve/src/public/channels/telegram/telegramChannel.test.ts b/packages/eve/src/public/channels/telegram/telegramChannel.test.ts
index 8ef596aba..4421ce60b 100644
--- a/packages/eve/src/public/channels/telegram/telegramChannel.test.ts
+++ b/packages/eve/src/public/channels/telegram/telegramChannel.test.ts
@@ -249,33 +249,6 @@ describe("telegramChannel() inbound route", () => {
);
});
- it("delivers Telegram callback queries as compact HITL input responses", async () => {
- const channel = telegramChannel({
- api: { fetch: fakeTelegramFetch() },
- credentials: { botToken: "bot-token", webhookSecretToken: SECRET },
- });
-
- const { send } = await firePost(channel, {
- callback_query: {
- id: "cb1",
- from: { id: 42, is_bot: false },
- data: "eve:0",
- message: {
- message_id: 55,
- chat: { id: -1001, type: "supergroup" },
- },
- },
- });
-
- expect(send).toHaveBeenCalledWith(
- "-1001::55",
- expect.objectContaining({
- auth: null,
- inputResponses: [{ optionId: "selected", requestId: "telegram_callback:eve:0" }],
- }),
- );
- });
-
it("sends authorization privately after the requester taps its group callback", async () => {
const logs = captureLogRecords();
const fetchMock = vi
@@ -409,26 +382,14 @@ describe("telegramChannel() inbound route", () => {
});
describe("telegramChannel() deliver hook", () => {
- it("maps compact callback and freeform reply responses through durable state", async () => {
+ it("maps freeform reply responses through durable state", async () => {
const adapter = withState(getAdapter(telegramChannel()), {
- hitlCallbacks: {
- "eve:0": { optionId: "approve", requestId: "call_1" },
- },
pendingFreeformReplies: {
"55": "call_2",
},
});
const ctx = buildAdapterContext(adapter, { get: () => undefined, set: () => {} } as any);
- expect(
- await adapter.deliver!(
- { inputResponses: [{ optionId: "selected", requestId: "telegram_callback:eve:0" }] },
- ctx,
- ),
- ).toEqual({
- inputResponses: [{ optionId: "approve", requestId: "call_1" }],
- context: undefined,
- });
expect(
await adapter.deliver!({ message: "because", state: { replyToBotMessageId: "55" } }, ctx),
).toEqual({
@@ -611,47 +572,6 @@ describe("telegramChannel() default event handlers", () => {
expect(body).toEqual({ action: "typing", chat_id: "42" });
});
- it("input.requested posts an inline keyboard and stores compact callback mappings", async () => {
- const fetchMock = vi
- .fn()
- .mockResolvedValue(
- new Response(JSON.stringify({ ok: true, result: { message_id: 50, chat: { id: 42 } } })),
- );
- 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("input.requested", {
- requests: [
- {
- action: { callId: "call_1", input: {}, kind: "tool-call", toolName: "ask_question" },
- options: [{ id: "approve", label: "Approve" }],
- prompt: "Approve?",
- requestId: "call_1",
- },
- ],
- sequence: 0,
- stepIndex: 0,
- turnId: "t1",
- }),
- ctx,
- );
-
- const body = JSON.parse(String((fetchMock.mock.calls[0]![1] as RequestInit).body));
- expect(body.reply_markup.inline_keyboard[0][0]).toEqual({
- callback_data: "eve:0",
- text: "Approve",
- });
- expect(ctx.state.hitlCallbacks).toEqual({
- "eve:0": { optionId: "approve", requestId: "call_1" },
- });
- });
-
it("freeform input requests register the prompt message id", async () => {
const fetchMock = vi
.fn()