Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(channels): add chat sdk channel (#429)

josh92f51629add6
diff --git a/.changeset/cute-colts-mix.md b/.changeset/cute-colts-mix.md
new file mode 100644
index 000000000..4af61b12a
--- /dev/null
+++ b/.changeset/cute-colts-mix.md
@@ -0,0 +1,5 @@
+---
+"eve": minor
+---
+
+add generic chat sdk channel for adapter-backed agents
diff --git a/packages/eve/package.json b/packages/eve/package.json
index 1fc410667..dbc1088df 100644
--- a/packages/eve/package.json
+++ b/packages/eve/package.json
@@ -216,6 +216,11 @@
"import": "./dist/src/public/channels/slack/index.js",
"default": "./dist/src/public/channels/slack/index.js"
},
+ "./channels/chat-sdk": {
+ "types": "./dist/src/public/channels/chat-sdk/index.d.ts",
+ "import": "./dist/src/public/channels/chat-sdk/index.js",
+ "default": "./dist/src/public/channels/chat-sdk/index.js"
+ },
"./channels/github": {
"types": "./dist/src/public/channels/github/index.d.ts",
"import": "./dist/src/public/channels/github/index.js",
diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts
new file mode 100644
index 000000000..753ba8f92
--- /dev/null
+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts
@@ -0,0 +1,561 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { buildAdapterContext } from "#channel/adapter-context.js";
+import { callAdapterEventHandler, type ChannelAdapter } from "#channel/adapter.js";
+import { isCompiledChannel, type CompiledChannel } from "#channel/compiled-channel.js";
+import { isHttpRouteDefinition } from "#channel/routes.js";
+import { ContextContainer, contextStorage } from "#context/container.js";
+import { SessionKey } from "#context/keys.js";
+import type { HandleMessageStreamEvent } from "#protocol/message.js";
+import { chatSdkChannel, type ChatSdkChannelState } from "#public/channels/chat-sdk/index.js";
+import type { RouteHandlerArgs, SendFn } from "#public/definitions/defineChannel.js";
+import type {
+ Adapter,
+ AdapterPostableMessage,
+ ChatInstance,
+ FetchResult,
+ FormattedContent,
+ MessageMetadata,
+ RawMessage,
+ StateAdapter,
+ Thread,
+ ThreadInfo,
+ WebhookOptions,
+} from "#compiled/chat/index.js";
+import { Message, parseMarkdown } from "#compiled/chat/index.js";
+
+const THREAD_ID = "test:C01:1700000000.000001";
+const CHANNEL_ID = "test:C01";
+
+const AUTH = {
+ attributes: {},
+ authenticator: "test",
+ principalId: "user-1",
+ principalType: "user",
+} as const;
+
+function asCompiled<T = unknown>(channel: unknown): CompiledChannel<T> {
+ if (!isCompiledChannel(channel)) {
+ throw new Error("Expected a CompiledChannel.");
+ }
+ return channel as CompiledChannel<T>;
+}
+
+function getAdapter(channel: unknown): ChannelAdapter<any> {
+ return asCompiled(channel).adapter;
+}
+
+function withState(adapter: ChannelAdapter<any>, state: ChatSdkChannelState): ChannelAdapter<any> {
+ return { ...adapter, state };
+}
+
+function stubAccessor() {
+ return { get: () => undefined, set: () => {} } as any;
+}
+
+const stubAlsContext = (() => {
+ const ctx = new ContextContainer();
+ ctx.setVirtualContext(SessionKey, {
+ sessionId: "test-session",
+ auth: { current: null, initiator: null },
+ turn: { id: "test-turn", sequence: 0 },
+ });
+ return ctx;
+})();
+
+function callEvent(
+ adapter: ChannelAdapter,
+ event: HandleMessageStreamEvent,
+ ctx: any,
+): Promise<HandleMessageStreamEvent> {
+ return contextStorage.run(stubAlsContext, () => callAdapterEventHandler(adapter, event, ctx));
+}
+
+function makeEvent<T extends HandleMessageStreamEvent["type"]>(
+ type: T,
+ data: unknown,
+): HandleMessageStreamEvent {
+ return { type, data } as HandleMessageStreamEvent;
+}
+
+async function firePost(
+ channel: unknown,
+ path: string,
+ body: Record<string, unknown>,
+): Promise<{
+ response: Response;
+ send: ReturnType<typeof vi.fn<SendFn<ChatSdkChannelState>>>;
+ waitUntil: ReturnType<typeof vi.fn>;
+}> {
+ const compiled = asCompiled<ChatSdkChannelState>(channel);
+ const post = compiled.routes.find((route) => route.method === "POST" && route.path === path);
+ if (!post || !isHttpRouteDefinition(post)) {
+ throw new Error(`Expected POST ${path}.`);
+ }
+ const send = vi.fn<SendFn<ChatSdkChannelState>>().mockResolvedValue({
+ continuationToken: "chat-sdk:test",
+ id: "session-1",
+ async getEventStream() {
+ return new ReadableStream();
+ },
+ });
+ const waitUntil = vi.fn();
+
+ const response = await post.handler(
+ new Request(`https://example.com${path}`, {
+ body: JSON.stringify(body),
+ headers: { "content-type": "application/json" },
+ method: "POST",
+ }),
+ {
+ getSession: vi.fn() as any,
+ params: {},
+ receive: vi.fn() as any,
+ requestIp: null,
+ send,
+ waitUntil,
+ } satisfies RouteHandlerArgs<ChatSdkChannelState>,
+ );
+
+ let drained = 0;
+ while (drained < waitUntil.mock.calls.length) {
+ const pending = waitUntil.mock.calls.slice(drained).map(([task]) => task as Promise<unknown>);
+ drained = waitUntil.mock.calls.length;
+ await Promise.allSettled(pending);
+ }
+
+ return { response, send, waitUntil };
+}
+
+describe("chatSdkChannel", () => {
+ it("mounts one webhook route per Chat SDK adapter", () => {
+ const bridge = chatSdkChannel({
+ adapters: {
+ test: testAdapter(),
+ },
+ state: memoryState(),
+ userName: "bot",
+ });
+
+ expect(
+ bridge.channel.routes.map((route) => ({ method: route.method, path: route.path })),
+ ).toEqual([{ method: "POST", path: "/eve/v1/chat/test" }]);
+ });
+
+ it("hands Chat SDK mentions to Eve through bridge.send", async () => {
+ const adapter = testAdapter();
+ const bridge = chatSdkChannel({
+ adapters: { test: adapter },
+ concurrency: "concurrent",
+ state: memoryState(),
+ userName: "bot",
+ });
+
+ bridge.bot.onNewMention(async (thread: Thread, message: Message) => {
+ await bridge.send(message.text, { auth: AUTH, thread, title: "mention" });
+ });
+
+ const { response, send } = await firePost(bridge.channel, "/eve/v1/chat/test", {
+ text: "@bot hello",
+ });
+
+ expect(response.status).toBe(200);
+ expect(send).toHaveBeenCalledTimes(1);
+ expect(send.mock.calls[0]?.[0]).toBe("@bot hello");
+ expect(send.mock.calls[0]?.[1]).toMatchObject({
+ auth: AUTH,
+ continuationToken: THREAD_ID,
+ state: {
+ thread: {
+ _type: "chat:Thread",
+ adapterName: "test",
+ channelId: CHANNEL_ID,
+ id: THREAD_ID,
+ },
+ },
+ title: "mention",
+ });
+ });
+
+ it("fails loudly when bridge.send is called outside a Chat SDK webhook", async () => {
+ const bridge = chatSdkChannel({
+ adapters: { test: testAdapter() },
+ state: memoryState(),
+ userName: "bot",
+ });
+
+ await expect(
+ bridge.send("hello", {
+ auth: null,
+ adapterName: "test",
+ thread: THREAD_ID,
+ }),
+ ).rejects.toThrow("chatSdkChannel().send can only run during a Chat SDK webhook handler");
+ });
+
+ it("supports proactive receive with a thread id target", async () => {
+ const bridge = chatSdkChannel({
+ adapters: { test: testAdapter() },
+ state: memoryState(),
+ userName: "bot",
+ });
+ const send = vi.fn<SendFn<ChatSdkChannelState>>().mockResolvedValue({
+ continuationToken: "chat-sdk:test",
+ id: "session-1",
+ async getEventStream() {
+ return new ReadableStream();
+ },
+ });
+
+ await bridge.channel.receive?.(
+ {
+ auth: AUTH,
+ message: "proactive",
+ target: { adapterName: "test", threadId: THREAD_ID },
+ },
+ { send },
+ );
+
+ expect(send).toHaveBeenCalledWith("proactive", {
+ auth: AUTH,
+ continuationToken: THREAD_ID,
+ state: {
+ thread: {
+ _type: "chat:Thread",
+ adapterName: "test",
+ channelId: CHANNEL_ID,
+ channelVisibility: "workspace",
+ id: THREAD_ID,
+ isDM: false,
+ },
+ },
+ });
+ });
+
+ it("posts completed Eve messages through the stored Chat SDK thread", async () => {
+ const adapter = testAdapter();
+ const bridge = chatSdkChannel({
+ adapters: { test: adapter },
+ state: memoryState(),
+ userName: "bot",
+ });
+ const channelAdapter = withState(getAdapter(bridge.channel), {
+ thread: serializedThread(),
+ });
+ const ctx = buildAdapterContext(channelAdapter, stubAccessor());
+
+ await callEvent(
+ channelAdapter,
+ makeEvent("message.completed", {
+ finishReason: "stop",
+ message: "done",
+ sequence: 1,
+ stepIndex: 0,
+ turnId: "turn-1",
+ }),
+ ctx,
+ );
+
+ expect(adapter.posted).toEqual([
+ {
+ message: "done",
+ threadId: THREAD_ID,
+ },
+ ]);
+ });
+
+ it("renders input requests as Chat SDK cards and resumes on button actions", async () => {
+ const adapter = testAdapter();
+ const bridge = chatSdkChannel({
+ adapters: { test: adapter },
+ concurrency: "concurrent",
+ state: memoryState(),
+ userName: "bot",
+ });
+ const channelAdapter = withState(getAdapter(bridge.channel), {
+ thread: serializedThread(),
+ });
+ const ctx = buildAdapterContext(channelAdapter, stubAccessor());
+
+ await callEvent(
+ channelAdapter,
+ makeEvent("input.requested", {
+ requests: [
+ {
+ action: { callId: "call-1", name: "deploy", type: "tool-call" },
+ display: "confirmation",
+ options: [
+ { id: "approve", label: "Approve", style: "primary" },
+ { id: "deny", label: "Deny", style: "danger" },
+ ],
+ prompt: "Deploy?",
+ requestId: "request-1",
+ },
+ ],
+ sequence: 1,
+ stepIndex: 0,
+ turnId: "turn-1",
+ }),
+ ctx,
+ );
+
+ const card = adapter.posted[0]?.message as AdapterPostableMessage;
+ expect(card).toMatchObject({
+ children: [
+ { content: "Deploy?", type: "text" },
+ {
+ children: [
+ {
+ id: "eve_input:request-1:approve",
+ label: "Approve",
+ style: "primary",
+ type: "button",
+ value: "approve",
+ },
+ {
+ id: "eve_input:request-1:deny",
+ label: "Deny",
+ style: "danger",
+ type: "button",
+ value: "deny",
+ },
+ ],
+ type: "actions",
+ },
+ ],
+ type: "card",
+ });
+
+ const { send } = await firePost(bridge.channel, "/eve/v1/chat/test", {
+ actionId: "eve_input:request-1:approve",
+ kind: "action",
+ value: "approve",
+ });
+
+ expect(send).toHaveBeenCalledWith(
+ { inputResponses: [{ optionId: "approve", requestId: "request-1" }] },
+ {
+ auth: null,
+ continuationToken: THREAD_ID,
+ state: {
+ thread: expect.objectContaining({
+ adapterName: "test",
+ id: THREAD_ID,
+ }),
+ },
+ },
+ );
+ });
+});
+
+function testAdapter(): TestAdapter & Adapter {
+ return new TestAdapter() as TestAdapter & Adapter;
+}
+
+class TestAdapter {
+ readonly name = "test";
+ readonly userName = "bot";
+ chat: ChatInstance | null = null;
+ posted: Array<{ message: AdapterPostableMessage; threadId: string }> = [];
+
+ async initialize(chat: ChatInstance): Promise<void> {
+ this.chat = chat;
+ }
+
+ async handleWebhook(request: Request, options?: WebhookOptions): Promise<Response> {
+ const body = (await request.json()) as {
+ actionId?: string;
+ kind?: string;
+ text?: string;
+ value?: string;
+ };
+ if (body.kind === "action") {
+ const adapter = this as Adapter;
+ await this.chat?.processAction(
+ {
+ actionId: body.actionId ?? "",
+ adapter,
+ messageId: "message-1",
+ raw: body,
+ threadId: THREAD_ID,
+ user: author(),
+ value: body.value,
+ },
+ options,
+ );
+ return new Response("ok");
+ }
+
+ const adapter = this as Adapter;
+ await this.chat?.processMessage(
+ adapter,
+ THREAD_ID,
+ message(body.text ?? "@bot hello"),
+ options,
+ );
+ return new Response("ok");
+ }
+
+ channelIdFromThreadId(_threadId: string): string {
+ return CHANNEL_ID;
+ }
+
+ decodeThreadId(threadId: string): { threadId: string } {
+ return { threadId };
+ }
+
+ encodeThreadId(input: { threadId: string }): string {
+ return input.threadId;
+ }
+
+ getChannelVisibility(): "workspace" {
+ return "workspace";
+ }
+
+ isDM(): boolean {
+ return false;
+ }
+
+ parseMessage(raw: { text?: string }): Message {
+ return message(raw.text ?? "");
+ }
+
+ renderFormatted(_content: FormattedContent): string {
+ return "";
+ }
+
+ async fetchMessages(): Promise<FetchResult> {
+ return { messages: [] };
+ }
+
+ async fetchThread(threadId: string): Promise<ThreadInfo> {
+ return {
+ channelId: CHANNEL_ID,
+ channelVisibility: "workspace",
+ id: threadId,
+ isDM: false,
+ metadata: {},
+ };
+ }
+
+ async postMessage(threadId: string, posted: AdapterPostableMessage): Promise<RawMessage> {
+ this.posted.push({ message: posted, threadId });
+ return {
+ id: `posted-${this.posted.length}`,
+ raw: posted,
+ threadId,
+ };
+ }
+
+ async editMessage(
+ threadId: string,
+ _messageId: string,
+ posted: AdapterPostableMessage,
+ ): Promise<RawMessage> {
+ return {
+ id: "edited",
+ raw: posted,
+ threadId,
+ };
+ }
+
+ async addReaction(): Promise<void> {}
+ async deleteMessage(): Promise<void> {}
+ async removeReaction(): Promise<void> {}
+ async startTyping(): Promise<void> {}
+}
+
+function message(text: string): Message {
+ return new Message({
+ attachments: [],
+ author: author(),
+ formatted: parseMarkdown(text),
+ id: "message-1",
+ isMention: true,
+ metadata: metadata(),
+ raw: { text },
+ text,
+ threadId: THREAD_ID,
+ });
+}
+
+function serializedThread() {
+ return {
+ _type: "chat:Thread",
+ adapterName: "test",
+ channelId: CHANNEL_ID,
+ channelVisibility: "workspace",
+ id: THREAD_ID,
+ isDM: false,
+ } as const;
+}
+
+function author() {
+ return {
+ fullName: "Test User",
+ isBot: false,
+ isMe: false,
+ userId: "user-1",
+ userName: "alice",
+ } as const;
+}
+
+function metadata(): MessageMetadata {
+ return { dateSent: new Date("2026-01-01T00:00:00.000Z"), edited: false };
+}
+
+function memoryState(): StateAdapter {
+ const values = new Map<string, unknown>();
+ const lists = new Map<string, unknown[]>();
+ const subscriptions = new Set<string>();
+ return {
+ async acquireLock(threadId: string) {
+ return { expiresAt: Date.now() + 1_000, threadId, token: "lock" };
+ },
+ async appendToList(key: string, value: unknown) {
+ lists.set(key, [...(lists.get(key) ?? []), value]);
+ },
+ async connect() {},
+ async delete(key: string) {
+ values.delete(key);
+ },
+ async dequeue() {
+ return null;
+ },
+ async disconnect() {},
+ async enqueue() {
+ return 1;
+ },
+ async extendLock() {
+ return true;
+ },
+ async forceReleaseLock() {},
+ async get(key: string) {
+ return (values.get(key) ?? null) as any;
+ },
+ async getList(key: string) {
+ return (lists.get(key) ?? []) as any[];
+ },
+ async isSubscribed(threadId: string) {
+ return subscriptions.has(threadId);
+ },
+ async queueDepth() {
+ return 0;
+ },
+ async releaseLock() {},
+ async set(key: string, value: unknown) {
+ values.set(key, value);
+ },
+ async setIfNotExists(key: string, value: unknown) {
+ if (values.has(key)) return false;
+ values.set(key, value);
+ return true;
+ },
+ async subscribe(threadId: string) {
+ subscriptions.add(threadId);
+ },
+ async unsubscribe(threadId: string) {
+ subscriptions.delete(threadId);
+ },
+ };
+}
diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts
new file mode 100644
index 000000000..c9929e602
--- /dev/null
+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts
@@ -0,0 +1,497 @@
+import type { SessionAuthContext } from "#channel/types.js";
+import { ContextContainer, contextStorage } from "#context/container.js";
+import { ContextKey } from "#context/key.js";
+import { createLogger, extractErrorId, formatErrorHint } from "#internal/logging.js";
+import type { HandleMessageStreamEvent } from "#protocol/message.js";
+import type { InputRequest } from "#runtime/input/types.js";
+import type {
+ ActionEvent,
+ Adapter,
+ CardChild,
+ ChatConfig,
+ SerializedThread,
+ Thread,
+ WebhookOptions,
+} from "#compiled/chat/index.js";
+import {
+ Actions,
+ Button,
+ Card,
+ CardText,
+ Chat,
+ Message,
+ ThreadImpl,
+} from "#compiled/chat/index.js";
+import {
+ defineChannel,
+ POST,
+ type Channel,
+ type ChannelEvents,
+ type ChannelSessionOps,
+ type SendFn,
+ type SendOptions,
+ type Session,
+} from "#public/definitions/defineChannel.js";
+
+const log = createLogger("chat-sdk.channel");
+const DEFAULT_ROUTE = "/eve/v1/chat";
+const DEFAULT_INPUT_ACTION_PREFIX = "eve_input:";
+
+type ChatSdkAdapters = Record<string, Adapter>;
+type ChatSdkSendInput = Parameters<SendFn<ChatSdkChannelState>>[0];
+type EventData<T extends HandleMessageStreamEvent["type"]> =
+ Extract<HandleMessageStreamEvent, { type: T }> extends { data: infer D } ? D : undefined;
+
+interface ActiveWebhookContext {
+ readonly send: SendFn<ChatSdkChannelState>;
+}
+
+const ActiveWebhookKey = new ContextKey<ActiveWebhookContext>("chat-sdk.active-webhook");
+
+/**
+ * Durable channel state used by `chatSdkChannel`. Stores the last Chat SDK
+ * thread for the Eve session so event handlers can post replies without
+ * depending on hidden Chat SDK subscription state.
+ */
+export interface ChatSdkChannelState extends Record<string, unknown> {
+ thread: SerializedThread | null;
+}
+
+/**
+ * Thread selector accepted by `chatSdkChannel().receive`. Pass a serialized
+ * Chat SDK thread when possible; `threadId` plus `adapterName` is supported for
+ * proactive sends that only have a provider-native thread id.
+ */
+export interface ChatSdkReceiveTarget {
+ readonly adapterName?: string;
+ readonly thread?: SerializedThread;
+ readonly threadId?: string;
+}
+
+/**
+ * Channel-owned metadata exposed to Eve instrumentation.
+ */
+export interface ChatSdkInstrumentationMetadata extends Record<string, unknown> {
+ readonly adapterName: string | null;
+ readonly channelId: string | null;
+ readonly isDM: boolean | null;
+ readonly threadId: string | null;
+}
+
+/**
+ * Per-session context passed to `chatSdkChannel({ events })` handlers. `thread`
+ * is rebuilt from persisted channel state using the configured Chat SDK
+ * adapter, so default handlers can post back to the originating chat thread.
+ */
+export interface ChatSdkChannelContext<TAdapters extends ChatSdkAdapters = ChatSdkAdapters> {
+ readonly bot: Chat<TAdapters>;
+ readonly thread: Thread | null;
+ state: ChatSdkChannelState;
+}
+
+/** Event-handler context for `chatSdkChannel`, including Eve session helpers. */
+export interface ChatSdkEventContext<TAdapters extends ChatSdkAdapters = ChatSdkAdapters>
+ extends ChatSdkChannelContext<TAdapters>, ChannelSessionOps {}
+
+/**
+ * Per-event handlers for `chatSdkChannel({ events })`. Each supplied handler
+ * replaces the built-in default for that event.
+ */
+export type ChatSdkChannelEvents<TAdapters extends ChatSdkAdapters = ChatSdkAdapters> =
+ ChannelEvents<ChatSdkChannelContext<TAdapters>>;
+
+/**
+ * Options for `bridge.send(...)` inside Chat SDK handlers. The `thread`
+ * determines the Eve continuation token and the persisted channel state.
+ */
+export interface ChatSdkSendOptions {
+ readonly auth?: SessionAuthContext | null;
+ readonly callback?: SendOptions<ChatSdkChannelState>["callback"];
+ readonly mode?: SendOptions<ChatSdkChannelState>["mode"];
+ readonly thread: SerializedThread | Thread | string;
+ readonly title?: string;
+ /**
+ * Required when `thread` is a string that does not include the Chat SDK
+ * adapter prefix. Prefer passing the `Thread` object from the Chat SDK handler
+ * when possible.
+ */
+ readonly adapterName?: string;
+}
+
+/**
+ * Configuration for {@link chatSdkChannel}. It accepts normal Chat SDK
+ * `ChatConfig` fields, plus Eve route and event settings.
+ */
+export interface ChatSdkChannelConfig<
+ TAdapters extends ChatSdkAdapters = ChatSdkAdapters,
+> extends Omit<ChatConfig<TAdapters>, "adapters"> {
+ /** Map of Chat SDK adapter name to adapter instance. */
+ readonly adapters: TAdapters;
+ /**
+ * Base route for generated adapter webhooks. Defaults to `/eve/v1/chat`, so
+ * an adapter named `slack` mounts at `/eve/v1/chat/slack`.
+ */
+ readonly route?: string;
+ /**
+ * Per-adapter route overrides. Use when a provider requires a fixed webhook
+ * URL or when migrating an existing endpoint without changing provider
+ * settings.
+ */
+ readonly routes?: Partial<Record<Extract<keyof TAdapters, string>, string>>;
+ /** Extra Chat SDK webhook options. Eve owns `waitUntil`. */
+ readonly webhook?: Omit<WebhookOptions, "waitUntil">;
+ /** Optional Eve event handlers. Supplied handlers replace built-in defaults. */
+ readonly events?: ChatSdkChannelEvents<TAdapters>;
+ /**
+ * Prefix for default Eve HITL button action ids. Change this if your Chat SDK
+ * app already uses the `eve_input:` prefix.
+ */
+ readonly inputActionPrefix?: string;
+ /**
+ * Auth resolver for default HITL button clicks. Defaults to `null`; provide a
+ * resolver when continued sessions should keep user or tenant auth.
+ */
+ readonly resolveInputAuth?: (
+ event: ActionEvent,
+ ) => SessionAuthContext | null | Promise<SessionAuthContext | null>;
+}
+
+/** Concrete channel value returned on `bridge.channel`. */
+export interface ChatSdkChannel extends Channel<
+ ChatSdkChannelState,
+ ChatSdkReceiveTarget,
+ ChatSdkInstrumentationMetadata
+> {}
+
+/**
+ * Return value of {@link chatSdkChannel}. Export `channel` from
+ * `agent/channels/<name>.ts`, then register handlers on `bot` and call `send`
+ * from those handlers to hand work to Eve.
+ */
+export interface ChatSdkChannelBridge<TAdapters extends ChatSdkAdapters = ChatSdkAdapters> {
+ readonly bot: Chat<TAdapters>;
+ readonly channel: ChatSdkChannel;
+ /**
+ * Starts or resumes an Eve session from inside a Chat SDK webhook handler.
+ * Use `channel.receive(...)` for proactive sends that are not handling an
+ * inbound Chat SDK webhook.
+ */
+ send(input: ChatSdkSendInput, options: ChatSdkSendOptions): Promise<Session>;
+}
+
+/**
+ * Creates an Eve channel backed by one Chat SDK runtime and its adapters.
+ *
+ * @example
+ * ```ts
+ * import { createSlackAdapter } from "@chat-adapter/slack";
+ * import { createMemoryState } from "@chat-adapter/state-memory";
+ * import { chatSdkChannel } from "eve/channels/chat-sdk";
+ *
+ * export const { bot, channel, send } = chatSdkChannel({
+ * userName: "acme",
+ * adapters: { slack: createSlackAdapter() },
+ * state: createMemoryState(),
+ * });
+ *
+ * bot.onNewMention(async (thread, message) => {
+ * await send(message.text, { thread });
+ * });
+ * ```
+ */
+export function chatSdkChannel<TAdapters extends ChatSdkAdapters>(
+ config: ChatSdkChannelConfig<TAdapters>,
+): ChatSdkChannelBridge<TAdapters> {
+ const bot = new Chat<TAdapters>(config as ChatConfig<TAdapters>);
+ const inputActionPrefix = config.inputActionPrefix ?? DEFAULT_INPUT_ACTION_PREFIX;
+ const mergedEvents: ChatSdkChannelEvents<TAdapters> = {
+ ...defaultEvents<TAdapters>(inputActionPrefix),
+ ...config.events,
+ };
+
+ bot.onAction(async (event: ActionEvent) => {
+ const response = decodeInputAction(event.actionId, inputActionPrefix, event.value);
+ if (!response) return;
+ if (!event.thread) {
+ throw new Error(
+ "chatSdkChannel input actions require a thread on the Chat SDK action event.",
+ );
+ }
+ await bridgeSend(
+ bot,
+ { inputResponses: [response] },
+ {
+ auth: config.resolveInputAuth ? await config.resolveInputAuth(event) : null,
+ thread: event.thread,
+ },
+ );
+ });
+
+ const channel = defineChannel<
+ ChatSdkChannelState,
+ ChatSdkChannelContext<TAdapters>,
+ ChatSdkReceiveTarget,
+ ChatSdkInstrumentationMetadata
+ >({
+ kindHint: "chat-sdk",
+ state: initialState(),
+ metadata: metadataFromState,
+ context(state) {
+ return {
+ bot,
+ state,
+ thread: threadFromState(bot, state),
+ };
+ },
+ routes: adapterNames(config.adapters).map((adapterName) =>
+ POST<ChatSdkChannelState>(routeForAdapter(adapterName, config), async (request, args) => {
+ const webhook = bot.webhooks[adapterName];
+ const ctx = new ContextContainer();
+ ctx.setVirtualContext(ActiveWebhookKey, { send: args.send });
+ return contextStorage.run(ctx, () =>
+ webhook(request, {
+ ...config.webhook,
+ waitUntil(task: Promise<unknown>) {
+ args.waitUntil(task);
+ },
+ }),
+ );
+ }),
+ ),
+ async receive(input, { send }) {
+ const thread = serializeReceiveTarget(bot, input.target);
+ return send(input.message, {
+ auth: input.auth,
+ continuationToken: thread.id,
+ state: { thread },
+ });
+ },
+ events: mergedEvents,
+ });
+
+ return {
+ bot,
+ channel,
+ send(input, options) {
+ return bridgeSend(bot, input, options);
+ },
+ };
+}
+
+function defaultEvents<TAdapters extends ChatSdkAdapters>(
+ inputActionPrefix: string,
+): ChatSdkChannelEvents<TAdapters> {
+ return {
+ async "turn.started"(_event, channel, _ctx) {
+ await channel.thread?.startTyping("Working...");
+ },
+ async "input.requested"(event, channel, _ctx) {
+ if (!channel.thread || event.requests.length === 0) return;
+ await channel.thread.post(renderInputRequests(event.requests, inputActionPrefix));
+ },
+ async "message.completed"(event, channel, _ctx) {
+ if (event.finishReason === "tool-calls" || !event.message || !channel.thread) return;
+ await channel.thread.post(event.message);
+ },
+ async "turn.failed"(event, channel, _ctx) {
+ await postFailure(channel.thread, "I hit an error while handling your request", event);
+ },
+ async "session.failed"(event, channel) {
+ await postFailure(channel.thread, "This session could not recover from an error", event);
+ },
+ };
+}
+
+function renderInputRequests(requests: readonly InputRequest[], inputActionPrefix: string) {
+ return Card({
+ children: requests.flatMap((request) => renderInputRequest(request, inputActionPrefix)),
+ });
+}
+
+function renderInputRequest(request: InputRequest, inputActionPrefix: string) {
+ const children: CardChild[] = [CardText(request.prompt)];
+ if (request.options && request.options.length > 0) {
+ children.push(
+ Actions(
+ request.options.map((option) =>
+ Button({
+ id: encodeInputAction(inputActionPrefix, request.requestId, option.id),
+ label: option.label,
+ style: option.style,
+ value: option.id,
+ }),
+ ),
+ ),
+ );
+ return children;
+ }
+ children.push(
+ CardText("This request needs a freeform answer. Continue from the Eve session UI."),
+ );
+ return children;
+}
+
+async function postFailure(
+ thread: Thread | null,
+ prefix: string,
+ event: EventData<"turn.failed"> | EventData<"session.failed">,
+): Promise<void> {
+ if (!thread) return;
+ const hint = formatErrorHint(event);
+ const errorId = extractErrorId(event.details);
+ await thread.post(
+ [
+ `${prefix}${hint}.`,
+ "Please try again, rephrase, or reach out if it keeps failing.",
+ ...(errorId ? [`Error id: ${errorId}`] : []),
+ ].join("\n\n"),
+ );
+}
+
+async function bridgeSend<TAdapters extends ChatSdkAdapters>(
+ bot: Chat<TAdapters>,
+ input: ChatSdkSendInput,
+ options: ChatSdkSendOptions,
+): Promise<Session> {
+ const active = contextStorage.getStore()?.get(ActiveWebhookKey);
+ if (!active) {
+ throw new Error(
+ "chatSdkChannel().send can only run during a Chat SDK webhook handler for this bridge.",
+ );
+ }
+ const thread = serializeThread(bot, options.thread, options.adapterName);
+ const sendOptions: SendOptions<ChatSdkChannelState> = {
+ auth: options.auth ?? null,
+ continuationToken: thread.id,
+ state: { thread },
+ };
+ if (options.callback) {
+ sendOptions.callback = options.callback;
+ }
+ if (options.mode) {
+ sendOptions.mode = options.mode;
+ }
+ if (options.title) {
+ sendOptions.title = options.title;
+ }
+ return active.send(input, sendOptions);
+}
+
+function initialState(): ChatSdkChannelState {
+ return { thread: null };
+}
+
+function metadataFromState(state: ChatSdkChannelState): ChatSdkInstrumentationMetadata {
+ return {
+ adapterName: state.thread?.adapterName ?? null,
+ channelId: state.thread?.channelId ?? null,
+ isDM: state.thread?.isDM ?? null,
+ threadId: state.thread?.id ?? null,
+ };
+}
+
+function threadFromState<TAdapters extends ChatSdkAdapters>(
+ bot: Chat<TAdapters>,
+ state: ChatSdkChannelState,
+): Thread | null {
+ if (!state.thread) return null;
+ try {
+ const serialized = state.thread;
+ return new ThreadImpl({
+ adapter: bot.getAdapter(serialized.adapterName),
+ channelId: serialized.channelId,
+ channelVisibility: serialized.channelVisibility,
+ currentMessage: serialized.currentMessage
+ ? Message.fromJSON(serialized.currentMessage)
+ : undefined,
+ id: serialized.id,
+ isDM: serialized.isDM,
+ stateAdapter: bot.getState(),
+ });
+ } catch (error) {
+ log.warn("failed to rebuild Chat SDK thread from channel state", { error });
+ return null;
+ }
+}
+
+function serializeReceiveTarget<TAdapters extends ChatSdkAdapters>(
+ bot: Chat<TAdapters>,
+ target: ChatSdkReceiveTarget,
+): SerializedThread {
+ if (target.thread) return target.thread;
+ if (!target.threadId) {
+ throw new Error("chatSdkChannel().receive requires target.thread or target.threadId.");
+ }
+ return serializeThread(bot, target.threadId, target.adapterName);
+}
+
+function serializeThread<TAdapters extends ChatSdkAdapters>(
+ bot: Chat<TAdapters>,
+ thread: SerializedThread | Thread | string,
+ adapterName?: string,
+): SerializedThread {
+ if (typeof thread === "string") {
+ const resolvedAdapterName = adapterName ?? inferAdapterName(thread);
+ const adapter = bot.getAdapter(resolvedAdapterName);
+ return {
+ _type: "chat:Thread",
+ adapterName: resolvedAdapterName,
+ channelId: adapter.channelIdFromThreadId(thread),
+ channelVisibility: adapter.getChannelVisibility?.(thread),
+ id: thread,
+ isDM: false,
+ };
+ }
+ if (isSerializedThread(thread)) return thread;
+ return thread.toJSON();
+}
+
+function isSerializedThread(value: SerializedThread | Thread): value is SerializedThread {
+ return "_type" in value && value._type === "chat:Thread";
+}
+
+function inferAdapterName(threadId: string): string {
+ const separator = threadId.indexOf(":");
+ if (separator <= 0) {
+ throw new Error("chatSdkChannel string thread references require options.adapterName.");
+ }
+ return threadId.slice(0, separator);
+}
+
+function adapterNames<TAdapters extends ChatSdkAdapters>(
+ adapters: TAdapters,
+): Extract<keyof TAdapters, string>[] {
+ return Object.keys(adapters) as Extract<keyof TAdapters, string>[];
+}
+
+function routeForAdapter<TAdapters extends ChatSdkAdapters>(
+ adapterName: Extract<keyof TAdapters, string>,
+ config: ChatSdkChannelConfig<TAdapters>,
+): string {
+ const override = config.routes?.[adapterName];
+ if (override) return override;
+ const route = config.route ?? DEFAULT_ROUTE;
+ return `${route.replace(/\/$/u, "")}/${adapterName}`;
+}
+
+function encodeInputAction(prefix: string, requestId: string, optionId: string): string {
+ return `${prefix}${encodeURIComponent(requestId)}:${encodeURIComponent(optionId)}`;
+}
+
+function decodeInputAction(
+ actionId: string,
+ prefix: string,
+ value: string | undefined,
+): { optionId: string; requestId: string } | null {
+ if (!actionId.startsWith(prefix)) return null;
+ const encoded = actionId.slice(prefix.length);
+ const separator = encoded.indexOf(":");
+ if (separator <= 0) return null;
+ try {
+ const requestId = decodeURIComponent(encoded.slice(0, separator));
+ const optionId = value ?? decodeURIComponent(encoded.slice(separator + 1));
+ return { optionId, requestId };
+ } catch {
+ return null;
+ }
+}
diff --git a/packages/eve/src/public/channels/chat-sdk/index.ts b/packages/eve/src/public/channels/chat-sdk/index.ts
new file mode 100644
index 000000000..c67756c50
--- /dev/null
+++ b/packages/eve/src/public/channels/chat-sdk/index.ts
@@ -0,0 +1,13 @@
+export {
+ chatSdkChannel,
+ type ChatSdkChannel,
+ type ChatSdkChannelBridge,
+ type ChatSdkChannelConfig,
+ type ChatSdkChannelContext,
+ type ChatSdkChannelEvents,
+ type ChatSdkChannelState,
+ type ChatSdkEventContext,
+ type ChatSdkInstrumentationMetadata,
+ type ChatSdkReceiveTarget,
+ type ChatSdkSendOptions,
+} from "#public/channels/chat-sdk/chatSdkChannel.js";
diff --git a/packages/eve/src/public/channels/index.ts b/packages/eve/src/public/channels/index.ts
index 3b518055d..06c036ea1 100644
--- a/packages/eve/src/public/channels/index.ts
+++ b/packages/eve/src/public/channels/index.ts
@@ -60,6 +60,7 @@ export interface ChannelMetadataMap {
readonly subagent: InstrumentationChannelMetadata;
readonly unknown: InstrumentationChannelMetadata;
readonly "channel:slack": import("#public/channels/slack/slackChannel.js").SlackInstrumentationMetadata;
+ readonly "channel:chat-sdk": import("#public/channels/chat-sdk/chatSdkChannel.js").ChatSdkInstrumentationMetadata;
readonly "channel:discord": import("#public/channels/discord/index.js").DiscordInstrumentationMetadata;
readonly "channel:twilio": import("#public/channels/twilio/twilioChannel.js").TwilioInstrumentationMetadata;
readonly "channel:teams": import("#public/channels/teams/index.js").TeamsInstrumentationMetadata;
@@ -84,6 +85,7 @@ export type InstrumentationChannelKind = keyof ChannelMetadataMap;
*/
export interface ChannelReferenceMap {
readonly "channel:slack": import("#public/channels/slack/slackChannel.js").SlackChannel;
+ readonly "channel:chat-sdk": import("#public/channels/chat-sdk/chatSdkChannel.js").ChatSdkChannel;
readonly "channel:discord": import("#public/channels/discord/discordChannel.js").DiscordChannel;
readonly "channel:twilio": import("#public/channels/twilio/twilioChannel.js").TwilioChannel;
readonly "channel:teams": import("#public/channels/teams/teamsChannel.js").TeamsChannel;