Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(channels): expand chat sdk channel defaults (#546)

Ben Sabic79e9959a9539
diff --git a/.changeset/chat-sdk-channel-updates.md b/.changeset/chat-sdk-channel-updates.md
new file mode 100644
index 000000000..127c56a43
--- /dev/null
+++ b/.changeset/chat-sdk-channel-updates.md
@@ -0,0 +1,5 @@
+---
+"eve": minor
+---
+
+Expand the Chat SDK channel (`chatSdkChannel`): post completed assistant messages as markdown, stream replies via post-then-edit (configurable with `streaming` and `streamingEditIntervalMs`), surface typing status on turn start and tool calls, and degrade optional adapter operations (`startTyping`, `editMessage`) gracefully when an adapter does not implement them. Add the `messageToUserContent` inbound helper and export `isNotImplemented`. The default adapter webhook route is now `/eve/v1/{adapter}`.
diff --git a/docs/channels/chat-sdk.mdx b/docs/channels/chat-sdk.mdx
new file mode 100644
index 000000000..67dd6039f
--- /dev/null
+++ b/docs/channels/chat-sdk.mdx
@@ -0,0 +1,209 @@
+---
+title: "Chat SDK"
+description: "Bridge any Vercel Chat SDK adapter — Slack, Discord, Telegram, WhatsApp, email, and more — to your agent through one channel, using your own credentials and state store."
+---
+
+The Chat SDK channel connects your agent to any [Vercel Chat SDK](https://chat-sdk.dev) adapter. You pick an adapter (`@chat-adapter/slack`, `@resend/chat-sdk-adapter`, and so on), register handlers for the messages you care about, and call `send` to hand each turn to eve. Use it to reach a surface eve does not ship a first-class channel for, or when you want to manage credentials and state with the Chat SDK's own primitives rather than [Vercel Connect](../guides/auth-and-route-protection). See [Channels](./overview) for the contract this builds on.
+
+You supply an adapter and a state store: the adapter owns provider auth, webhook verification, and delivery, while eve owns session dispatch, streaming, typing, and human-in-the-loop. First-class channels such as [Slack](./slack) manage credentials through Vercel Connect instead — reach for whichever fits the surface you are targeting.
+
+## Install
+
+Add eve, the Chat SDK core (`chat`), an adapter, and a state adapter. The example below uses the Resend email adapter with the in-memory state store:
+
+```bash
+npm install eve@latest chat @resend/chat-sdk-adapter @chat-adapter/state-memory
+```
+
+Swap in whichever adapter matches your surface — `@chat-adapter/slack`, `@chat-adapter/discord`, `@chat-adapter/telegram`, and so on. Any Chat SDK adapter works.
+
+## Add the channel
+
+`chatSdkChannel` returns `{ bot, channel, send }`. Register Chat SDK handlers on `bot`, call `send` from those handlers to start or resume an eve session, and export `channel` as the module default:
+
+```ts title="agent/channels/resend.ts"
+import { createMemoryState } from "@chat-adapter/state-memory";
+import { createResendAdapter } from "@resend/chat-sdk-adapter";
+import type { Message, Thread } from "chat";
+import { chatSdkChannel } from "eve/channels/chat-sdk";
+
+export const { bot, channel, send } = chatSdkChannel({
+ userName: "Resend Bot",
+ adapters: {
+ resend: createResendAdapter({
+ fromAddress: "[email protected]",
+ fromName: "Resend Bot",
+ }),
+ },
+ state: createMemoryState(),
+ streaming: false,
+});
+
+bot.onNewMention(async (thread: Thread, message: Message) => {
+ await thread.subscribe();
+ await send(message.text, { thread });
+});
+
+bot.onSubscribedMessage(async (thread: Thread, message: Message) => {
+ await send(message.text, { thread });
+});
+
+export default channel;
+```
+
+`adapters` is a map of adapter name to adapter instance; each entry mounts its own webhook (see below). `state` takes any Chat SDK state adapter: `createMemoryState()` is fine for local development, but use a durable adapter (Redis, Upstash, etc.) in production so thread subscriptions and inbound deduplication survive restarts. `send` accepts a plain string, an AI SDK `UserContent` array, or a `SendPayload`, and must be called from inside a Chat SDK handler — it dispatches the turn on the webhook that is currently running.
+
+Deploy once the channel file is in place:
+
+```bash
+eve deploy
+```
+
+`eve deploy` links the project if needed and deploys to Vercel production.
+
+## Configure the webhook route
+
+Each adapter mounts one `POST` route at `/eve/v1/{adapterName}`, so the `resend` adapter above is served at `/eve/v1/resend`. Point your provider's webhook (the Resend inbound address, the Slack Event Subscriptions URL, etc.) at that path.
+
+Override the base path for every adapter with `route`, or pin an individual adapter's path with `routes`:
+
+```ts
+export const { bot, channel, send } = chatSdkChannel({
+ userName: "Resend Bot",
+ adapters: { resend: createResendAdapter({ fromAddress: "[email protected]" }) },
+ state: createMemoryState(),
+ route: "/webhooks", // resend now mounts at /webhooks/resend
+ routes: { resend: "/webhooks/inbound-email" }, // …or pin it exactly
+});
+```
+
+Use `routes` when a provider requires a fixed URL or when you are migrating an existing endpoint without changing the provider's settings.
+
+## How the channel handles messages
+
+### Dispatch
+
+You choose which Chat SDK events start a turn by registering handlers on `bot` and calling `send`:
+
+- `bot.onNewMention(thread, message)` fires on a fresh `@mention` (or, for surfaces like email, a new inbound thread). Call `thread.subscribe()` when you want later replies in the same thread to keep reaching the agent.
+- `bot.onSubscribedMessage(thread, message)` fires on subsequent messages in a subscribed thread.
+- `bot.onAction`, `bot.onReaction`, and `bot.onSlashCommand` are available for adapters that emit them.
+
+`send(input, options)` starts or resumes the eve session. The `thread` you pass determines the continuation token and the persisted channel state, so replies land back on the originating thread:
+
+```ts
+bot.onNewMention(async (thread, message) => {
+ await send(message.text, { thread, title: "Support request" });
+});
+```
+
+`options` accepts `{ thread, auth?, title?, mode?, callback?, adapterName? }`. `title` sets the eve session's display title without changing the model message; `auth` attaches an authenticated principal to the turn.
+
+### Delivery
+
+The default handlers post the agent's reply back to the thread — no `events` override required. Completed assistant messages are posted as markdown (`{ markdown: … }`) so adapters render rich text and email HTML rather than a raw string.
+
+Streaming is on by default: the channel posts an initial message and edits it as tokens arrive (`message.appended`), throttled by `streamingEditIntervalMs` (default `1000`). Set `streaming: false` for surfaces that deliver one message per turn — email, for example — so the reply posts once on completion instead of editing:
+
+```ts
+chatSdkChannel({
+ userName: "Resend Bot",
+ adapters: { resend: createResendAdapter({ fromAddress: "[email protected]" }) },
+ state: createMemoryState(),
+ streaming: false,
+});
+```
+
+Typing indicators post automatically where the adapter supports them: `Working…` on `turn.started`, and tool status on `actions.requested`.
+
+### Optional capabilities degrade gracefully
+
+Adapters do not all implement every operation. When an adapter's `startTyping` or `editMessage` throws a `NotImplementedError` (or an error with code `NOT_IMPLEMENTED`), the channel swallows it: typing indicators are skipped, and a streaming edit falls back to a single final post for the rest of the session. You never have to guard optional capabilities in your own handlers. The same predicate is exported as `isNotImplemented` if you want it in custom `events`:
+
+```ts
+import { isNotImplemented } from "eve/channels/chat-sdk";
+```
+
+Override any default by passing `events`. Handlers receive `(eventData, channel, ctx)`, with the rebuilt Chat SDK thread on `channel.thread`:
+
+```ts
+chatSdkChannel({
+ userName: "Resend Bot",
+ adapters: { resend: createResendAdapter({ fromAddress: "[email protected]" }) },
+ state: createMemoryState(),
+ events: {
+ "message.completed"(eventData, channel) {
+ if (eventData.finishReason === "tool-calls" || !eventData.message || !channel.thread) return;
+ return channel.thread.post({ markdown: eventData.message });
+ },
+ },
+});
+```
+
+### Human-in-the-loop (HITL)
+
+HITL prompts render as a Chat SDK `Card` with buttons. Button clicks resume the parked session automatically — the channel wires `bot.onAction` for you. Change the action-id prefix with `inputActionPrefix` (default `eve_input:`) if your app already uses it, and provide `resolveInputAuth` to carry user or tenant auth across the resume:
+
+```ts
+chatSdkChannel({
+ userName: "Support Bot",
+ adapters: { slack: createSlackAdapter() },
+ state: createMemoryState(),
+ resolveInputAuth: (event) => ({
+ authenticator: "slack",
+ principalType: "user",
+ principalId: event.user?.userId ?? "unknown",
+ attributes: {},
+ }),
+});
+```
+
+### Proactive sessions
+
+Start a session without an inbound webhook through `channel.receive({ message, target, auth })` — from a schedule `run` handler, or `args.receive(channel, ...)` from another channel. The target is a serialized Chat SDK thread, or `{ threadId, adapterName }` when you only have a provider-native thread id:
+
+```ts
+await channel.receive({
+ message: "Your weekly digest is ready.",
+ target: { adapterName: "resend", threadId: "resend:[email protected]" },
+ auth: null,
+});
+```
+
+### Attachments
+
+`send` takes plain text or an AI SDK `UserContent` array. To forward a Chat SDK message's attachments, convert it with `messageToUserContent`, which returns `message.text` when there are no attachments and a `UserContent` array (text plus one file part per attachment URL) when there are:
+
+```ts
+import { messageToUserContent } from "eve/channels/chat-sdk";
+
+bot.onNewMention(async (thread, message) => {
+ await send(messageToUserContent(message), { thread });
+});
+```
+
+See [File uploads](./custom#file-uploads) for how eve stages remote file URLs before the model call.
+
+## Configuration reference
+
+| Option | Default | Purpose |
+| ------------------------- | ------------ | ------------------------------------------------------------------------ |
+| `adapters` | — | Map of adapter name to Chat SDK adapter instance. One webhook per entry. |
+| `state` | — | Chat SDK state adapter for subscriptions, locks, and dedupe. |
+| `userName` | — | Display name for the bot (a standard Chat SDK `ChatConfig` field). |
+| `route` | `/eve/v1` | Base path for generated adapter webhooks (`{route}/{adapter}`). |
+| `routes` | — | Per-adapter path overrides for fixed or migrated webhook URLs. |
+| `streaming` | `true` | Post-then-edit streaming. Set `false` for one-message-per-turn surfaces. |
+| `streamingEditIntervalMs` | `1000` | Minimum interval between streaming edits. |
+| `events` | built-in | Per-event handlers. A supplied handler replaces that built-in default. |
+| `inputActionPrefix` | `eve_input:` | Prefix for default HITL button action ids. |
+| `resolveInputAuth` | `null` | Auth resolver applied when a HITL button click resumes a session. |
+| `webhook` | — | Extra Chat SDK webhook options (eve owns `waitUntil`). |
+
+Any other Chat SDK `ChatConfig` field (for example `concurrency`) is accepted and passed through.
+
+## What to read next
+
+- [Channels overview](./overview): the channel contract and every built-in channel
+- [Custom channels](./custom): build a channel for any surface with `defineChannel`
+- [Auth & route protection](../guides/auth-and-route-protection): authenticating inbound traffic
diff --git a/docs/channels/meta.json b/docs/channels/meta.json
index 32cb56fa4..c0bcc03d2 100644
--- a/docs/channels/meta.json
+++ b/docs/channels/meta.json
@@ -10,6 +10,7 @@
"twilio",
"github",
"linear",
+ "chat-sdk",
"custom"
]
}
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 753ba8f92..0fe3dd94d 100644
--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts
+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts
@@ -7,7 +7,12 @@ 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 {
+ chatSdkChannel,
+ isNotImplemented,
+ messageToUserContent,
+ type ChatSdkChannelState,
+} from "#public/channels/chat-sdk/index.js";
import type { RouteHandlerArgs, SendFn } from "#public/definitions/defineChannel.js";
import type {
Adapter,
@@ -139,7 +144,7 @@ describe("chatSdkChannel", () => {
expect(
bridge.channel.routes.map((route) => ({ method: route.method, path: route.path })),
- ).toEqual([{ method: "POST", path: "/eve/v1/chat/test" }]);
+ ).toEqual([{ method: "POST", path: "/eve/v1/test" }]);
});
it("hands Chat SDK mentions to Eve through bridge.send", async () => {
@@ -155,7 +160,7 @@ describe("chatSdkChannel", () => {
await bridge.send(message.text, { auth: AUTH, thread, title: "mention" });
});
- const { response, send } = await firePost(bridge.channel, "/eve/v1/chat/test", {
+ const { response, send } = await firePost(bridge.channel, "/eve/v1/test", {
text: "@bot hello",
});
@@ -232,7 +237,7 @@ describe("chatSdkChannel", () => {
});
});
- it("posts completed Eve messages through the stored Chat SDK thread", async () => {
+ it("posts completed Eve messages as markdown through the stored Chat SDK thread", async () => {
const adapter = testAdapter();
const bridge = chatSdkChannel({
adapters: { test: adapter },
@@ -258,12 +263,177 @@ describe("chatSdkChannel", () => {
expect(adapter.posted).toEqual([
{
- message: "done",
+ message: { markdown: "done" },
threadId: THREAD_ID,
},
]);
});
+ it("does not throw when the adapter's startTyping is not implemented", async () => {
+ const adapter = testAdapter();
+ adapter.startTypingError = new NotImplementedError("startTyping");
+ const bridge = chatSdkChannel({
+ adapters: { test: adapter },
+ state: memoryState(),
+ userName: "bot",
+ });
+ const channelAdapter = withState(getAdapter(bridge.channel), {
+ thread: serializedThread(),
+ });
+ const ctx = buildAdapterContext(channelAdapter, stubAccessor());
+
+ await expect(
+ callEvent(channelAdapter, makeEvent("turn.started", { sequence: 0, turnId: "turn-1" }), ctx),
+ ).resolves.toBeDefined();
+ expect(adapter.typingStatuses).toEqual(["Working..."]);
+ });
+
+ it("streams assistant deltas by posting an anchor then editing it", async () => {
+ const adapter = testAdapter();
+ const bridge = chatSdkChannel({
+ adapters: { test: adapter },
+ state: memoryState(),
+ streamingEditIntervalMs: 0,
+ userName: "bot",
+ });
+ const state: ChatSdkChannelState = { thread: serializedThread() };
+ const channelAdapter = withState(getAdapter(bridge.channel), state);
+ const ctx = buildAdapterContext(channelAdapter, stubAccessor());
+
+ await callEvent(
+ channelAdapter,
+ makeEvent("message.appended", {
+ messageDelta: "Hel",
+ messageSoFar: "Hel",
+ sequence: 1,
+ stepIndex: 0,
+ turnId: "turn-1",
+ }),
+ ctx,
+ );
+ expect(adapter.posted).toEqual([{ message: { markdown: "Hel" }, threadId: THREAD_ID }]);
+ expect(state.anchorMessageId).toBe("posted-1");
+
+ await callEvent(
+ channelAdapter,
+ makeEvent("message.appended", {
+ messageDelta: "lo",
+ messageSoFar: "Hello",
+ sequence: 2,
+ stepIndex: 0,
+ turnId: "turn-1",
+ }),
+ ctx,
+ );
+ expect(adapter.edited).toEqual([
+ { message: { markdown: "Hello" }, messageId: "posted-1", threadId: THREAD_ID },
+ ]);
+ });
+
+ it("falls back to a fresh post when streaming edits are not implemented", async () => {
+ const adapter = testAdapter();
+ adapter.editError = new NotImplementedError("editMessage");
+ const bridge = chatSdkChannel({
+ adapters: { test: adapter },
+ state: memoryState(),
+ userName: "bot",
+ });
+ const state: ChatSdkChannelState = {
+ anchorMessageId: "posted-1",
+ editSupported: true,
+ streamStepIndex: 0,
+ thread: serializedThread(),
+ };
+ const channelAdapter = withState(getAdapter(bridge.channel), state);
+ const ctx = buildAdapterContext(channelAdapter, stubAccessor());
+
+ await callEvent(
+ channelAdapter,
+ makeEvent("message.completed", {
+ finishReason: "stop",
+ message: "final answer",
+ sequence: 2,
+ stepIndex: 0,
+ turnId: "turn-1",
+ }),
+ ctx,
+ );
+
+ expect(adapter.posted).toEqual([
+ { message: { markdown: "final answer" }, threadId: THREAD_ID },
+ ]);
+ expect(state.editSupported).toBe(false);
+ });
+
+ it("finalizes the streamed anchor when a step completes with tool-calls", async () => {
+ const adapter = testAdapter();
+ const bridge = chatSdkChannel({
+ adapters: { test: adapter },
+ state: memoryState(),
+ userName: "bot",
+ });
+ const state: ChatSdkChannelState = {
+ anchorMessageId: "posted-1",
+ editSupported: true,
+ streamStepIndex: 0,
+ thread: serializedThread(),
+ };
+ const channelAdapter = withState(getAdapter(bridge.channel), state);
+ const ctx = buildAdapterContext(channelAdapter, stubAccessor());
+
+ await callEvent(
+ channelAdapter,
+ makeEvent("message.completed", {
+ finishReason: "tool-calls",
+ message: "Let me check that.\nlooking now",
+ sequence: 2,
+ stepIndex: 0,
+ turnId: "turn-1",
+ }),
+ ctx,
+ );
+
+ expect(adapter.edited).toEqual([
+ {
+ message: { markdown: "Let me check that.\nlooking now" },
+ messageId: "posted-1",
+ threadId: THREAD_ID,
+ },
+ ]);
+ expect(adapter.posted).toEqual([]);
+ expect(state.pendingToolCallMessage).toBe("Let me check that.");
+ expect(state.anchorMessageId).toBeNull();
+ });
+
+ it("does not post intermediate tool-call narration when streaming is off", async () => {
+ const adapter = testAdapter();
+ const bridge = chatSdkChannel({
+ adapters: { test: adapter },
+ state: memoryState(),
+ streaming: false,
+ userName: "bot",
+ });
+ const state: ChatSdkChannelState = { thread: serializedThread() };
+ const channelAdapter = withState(getAdapter(bridge.channel), state);
+ const ctx = buildAdapterContext(channelAdapter, stubAccessor());
+
+ await callEvent(
+ channelAdapter,
+ makeEvent("message.completed", {
+ finishReason: "tool-calls",
+ message: "Let me check that.",
+ sequence: 1,
+ stepIndex: 0,
+ turnId: "turn-1",
+ }),
+ ctx,
+ );
+
+ expect(adapter.posted).toEqual([]);
+ expect(adapter.edited).toEqual([]);
+ expect(state.pendingToolCallMessage).toBe("Let me check that.");
+ });
+
it("renders input requests as Chat SDK cards and resumes on button actions", async () => {
const adapter = testAdapter();
const bridge = chatSdkChannel({
@@ -326,7 +496,7 @@ describe("chatSdkChannel", () => {
type: "card",
});
- const { send } = await firePost(bridge.channel, "/eve/v1/chat/test", {
+ const { send } = await firePost(bridge.channel, "/eve/v1/test", {
actionId: "eve_input:request-1:approve",
kind: "action",
value: "approve",
@@ -348,15 +518,113 @@ describe("chatSdkChannel", () => {
});
});
+describe("messageToUserContent", () => {
+ it("returns the plain text when there are no attachments", () => {
+ expect(messageToUserContent(message("just text"))).toBe("just text");
+ });
+
+ it("builds text and file parts when attachments have URLs", () => {
+ const withAttachment = new Message({
+ attachments: [
+ {
+ mimeType: "application/pdf",
+ name: "a.pdf",
+ type: "file",
+ url: "https://example.com/a.pdf",
+ },
+ ],
+ author: author(),
+ formatted: parseMarkdown("see attached"),
+ id: "message-2",
+ isMention: true,
+ metadata: metadata(),
+ raw: { text: "see attached" },
+ text: "see attached",
+ threadId: THREAD_ID,
+ });
+
+ const content = messageToUserContent(withAttachment);
+ expect(Array.isArray(content)).toBe(true);
+ const parts = content as Exclude<typeof content, string>;
+ expect(parts[0]).toEqual({ text: "see attached", type: "text" });
+ expect(parts[1]).toMatchObject({
+ filename: "a.pdf",
+ mediaType: "application/pdf",
+ type: "file",
+ });
+ expect((parts[1] as { data: URL }).data.href).toBe("https://example.com/a.pdf");
+ });
+
+ it("skips attachments without a URL, keeping the text part", () => {
+ const withUrllessAttachment = new Message({
+ attachments: [{ name: "pasted", type: "image" }],
+ author: author(),
+ formatted: parseMarkdown("no url"),
+ id: "message-3",
+ isMention: true,
+ metadata: metadata(),
+ raw: { text: "no url" },
+ text: "no url",
+ threadId: THREAD_ID,
+ });
+
+ expect(messageToUserContent(withUrllessAttachment)).toEqual([{ text: "no url", type: "text" }]);
+ });
+
+ it("falls back to text when there are no usable parts", () => {
+ const emptyWithUrllessAttachment = new Message({
+ attachments: [{ name: "pasted", type: "image" }],
+ author: author(),
+ formatted: parseMarkdown(""),
+ id: "message-4",
+ isMention: true,
+ metadata: metadata(),
+ raw: { text: "" },
+ text: "",
+ threadId: THREAD_ID,
+ });
+
+ expect(messageToUserContent(emptyWithUrllessAttachment)).toBe("");
+ });
+});
+
+describe("isNotImplemented", () => {
+ it("matches errors by name and by code", () => {
+ expect(isNotImplemented(new NotImplementedError("startTyping"))).toBe(true);
+ expect(isNotImplemented(Object.assign(new Error("nope"), { code: "NOT_IMPLEMENTED" }))).toBe(
+ true,
+ );
+ });
+
+ it("ignores unrelated errors and non-errors", () => {
+ expect(isNotImplemented(new Error("boom"))).toBe(false);
+ expect(isNotImplemented("NOT_IMPLEMENTED")).toBe(false);
+ expect(isNotImplemented(null)).toBe(false);
+ });
+});
+
function testAdapter(): TestAdapter & Adapter {
return new TestAdapter() as TestAdapter & Adapter;
}
+class NotImplementedError extends Error {
+ readonly code = "NOT_IMPLEMENTED";
+
+ constructor(feature: string) {
+ super(`${feature} is not implemented`);
+ this.name = "NotImplementedError";
+ }
+}
+
class TestAdapter {
readonly name = "test";
readonly userName = "bot";
chat: ChatInstance | null = null;
posted: Array<{ message: AdapterPostableMessage; threadId: string }> = [];
+ edited: Array<{ message: AdapterPostableMessage; messageId: string; threadId: string }> = [];
+ typingStatuses: Array<string | undefined> = [];
+ startTypingError: Error | null = null;
+ editError: Error | null = null;
async initialize(chat: ChatInstance): Promise<void> {
this.chat = chat;
@@ -449,9 +717,11 @@ class TestAdapter {
async editMessage(
threadId: string,
- _messageId: string,
+ messageId: string,
posted: AdapterPostableMessage,
): Promise<RawMessage> {
+ if (this.editError) throw this.editError;
+ this.edited.push({ message: posted, messageId, threadId });
return {
id: "edited",
raw: posted,
@@ -462,7 +732,10 @@ class TestAdapter {
async addReaction(): Promise<void> {}
async deleteMessage(): Promise<void> {}
async removeReaction(): Promise<void> {}
- async startTyping(): Promise<void> {}
+ async startTyping(_threadId: string, status?: string): Promise<void> {
+ this.typingStatuses.push(status);
+ if (this.startTypingError) throw this.startTypingError;
+ }
}
function message(text: string): Message {
diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts
index c9929e602..274ea200c 100644
--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts
+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts
@@ -22,6 +22,7 @@ import {
Message,
ThreadImpl,
} from "#compiled/chat/index.js";
+import { isNotImplemented } from "#public/channels/chat-sdk/notImplemented.js";
import {
defineChannel,
POST,
@@ -34,8 +35,10 @@ import {
} from "#public/definitions/defineChannel.js";
const log = createLogger("chat-sdk.channel");
-const DEFAULT_ROUTE = "/eve/v1/chat";
+const DEFAULT_ROUTE = "/eve/v1";
const DEFAULT_INPUT_ACTION_PREFIX = "eve_input:";
+const DEFAULT_STREAMING_EDIT_INTERVAL_MS = 1_000;
+const MAX_TYPING_STATUS = 80;
type ChatSdkAdapters = Record<string, Adapter>;
type ChatSdkSendInput = Parameters<SendFn<ChatSdkChannelState>>[0];
@@ -51,10 +54,25 @@ const ActiveWebhookKey = new ContextKey<ActiveWebhookContext>("chat-sdk.active-w
/**
* 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.
+ * depending on hidden Chat SDK subscription state, plus the bookkeeping the
+ * default handlers use to stream assistant output and surface typing status.
*/
export interface ChatSdkChannelState extends Record<string, unknown> {
thread: SerializedThread | null;
+ /** Message id of the in-flight streamed assistant post (edit fallback). */
+ anchorMessageId?: string | null;
+ /**
+ * Whether `adapter.editMessage` works for this session. Set to `false` once
+ * an edit throws {@link isNotImplemented}, which disables streaming edits for
+ * the rest of the session.
+ */
+ editSupported?: boolean;
+ /** Epoch ms of the last streaming edit, used to throttle edits. */
+ lastEditAtMs?: number | null;
+ /** Buffered first line of a tool-call message, surfaced as typing status. */
+ pendingToolCallMessage?: string | null;
+ /** Step index the current stream anchor belongs to (resets per step). */
+ streamStepIndex?: number | null;
}
/**
@@ -87,6 +105,10 @@ export interface ChatSdkChannelContext<TAdapters extends ChatSdkAdapters = ChatS
readonly bot: Chat<TAdapters>;
readonly thread: Thread | null;
state: ChatSdkChannelState;
+ /** Whether streamed deltas are delivered via a post+edit fallback. */
+ readonly streaming: boolean;
+ /** Minimum interval between streaming edits, in ms. */
+ readonly streamingEditIntervalMs: number;
}
/** Event-handler context for `chatSdkChannel`, including Eve session helpers. */
@@ -128,8 +150,8 @@ export interface ChatSdkChannelConfig<
/** 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`.
+ * Base route for generated adapter webhooks. Defaults to `/eve/v1`, so an
+ * adapter named `slack` mounts at `/eve/v1/slack`.
*/
readonly route?: string;
/**
@@ -154,6 +176,18 @@ export interface ChatSdkChannelConfig<
readonly resolveInputAuth?: (
event: ActionEvent,
) => SessionAuthContext | null | Promise<SessionAuthContext | null>;
+ /**
+ * Whether the default handlers stream assistant output by posting an initial
+ * message and editing it as deltas arrive. Defaults to `true`. Set to `false`
+ * for adapters that only deliver a single message per turn (e.g. email), so
+ * replies post once on completion.
+ */
+ readonly streaming?: boolean;
+ /**
+ * Minimum interval between streaming edits, in ms. Defaults to `1000`. Only
+ * used when `streaming` is enabled and the adapter supports editing.
+ */
+ readonly streamingEditIntervalMs?: number;
}
/** Concrete channel value returned on `bridge.channel`. */
@@ -204,6 +238,9 @@ export function chatSdkChannel<TAdapters extends ChatSdkAdapters>(
): ChatSdkChannelBridge<TAdapters> {
const bot = new Chat<TAdapters>(config as ChatConfig<TAdapters>);
const inputActionPrefix = config.inputActionPrefix ?? DEFAULT_INPUT_ACTION_PREFIX;
+ const streaming = config.streaming ?? true;
+ const streamingEditIntervalMs =
+ config.streamingEditIntervalMs ?? DEFAULT_STREAMING_EDIT_INTERVAL_MS;
const mergedEvents: ChatSdkChannelEvents<TAdapters> = {
...defaultEvents<TAdapters>(inputActionPrefix),
...config.events,
@@ -240,6 +277,8 @@ export function chatSdkChannel<TAdapters extends ChatSdkAdapters>(
return {
bot,
state,
+ streaming,
+ streamingEditIntervalMs,
thread: threadFromState(bot, state),
};
},
@@ -283,15 +322,69 @@ function defaultEvents<TAdapters extends ChatSdkAdapters>(
): ChatSdkChannelEvents<TAdapters> {
return {
async "turn.started"(_event, channel, _ctx) {
- await channel.thread?.startTyping("Working...");
+ channel.state.pendingToolCallMessage = null;
+ clearStream(channel.state);
+ await safeStartTyping(channel.thread, "Working...");
+ },
+ async "actions.requested"(event, channel, _ctx) {
+ const buffered = channel.state.pendingToolCallMessage;
+ channel.state.pendingToolCallMessage = null;
+ if (buffered) {
+ await safeStartTyping(channel.thread, truncate(buffered));
+ return;
+ }
+ const labels = event.actions.map((action) =>
+ action.kind === "tool-call" ? action.toolName : action.kind,
+ );
+ await safeStartTyping(channel.thread, truncate(`Running ${labels.join(", ")}...`));
+ },
+ async "message.appended"(event, channel, _ctx) {
+ if (!channel.thread || !event.messageSoFar || !canStream(channel)) return;
+ const anchor = channel.state.anchorMessageId;
+ if (!anchor || channel.state.streamStepIndex !== event.stepIndex) {
+ const sent = await channel.thread.post({ markdown: event.messageSoFar });
+ channel.state.anchorMessageId = sent.id;
+ channel.state.streamStepIndex = event.stepIndex;
+ channel.state.lastEditAtMs = Date.now();
+ return;
+ }
+ const lastEdit = channel.state.lastEditAtMs ?? 0;
+ if (Date.now() - lastEdit < channel.streamingEditIntervalMs) return;
+ try {
+ await editMessage(channel.thread, anchor, event.messageSoFar);
+ channel.state.lastEditAtMs = Date.now();
+ } catch (error) {
+ if (!isNotImplemented(error)) throw error;
+ channel.state.editSupported = false;
+ clearStream(channel.state);
+ }
},
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);
+ if (event.finishReason === "tool-calls") {
+ channel.state.pendingToolCallMessage = event.message
+ ? (firstNonEmptyLine(event.message) ?? null)
+ : null;
+ // Finalize the streamed anchor so it shows the complete pre-tool-call
+ // text rather than the last throttled edit. Pass `false` so nothing new
+ // is posted when nothing was streamed — intermediate tool-call narration
+ // must not become a standalone message on non-streaming surfaces.
+ if (event.message) {
+ await finalizeStreamedMessage(channel, event.message, false);
+ } else {
+ clearStream(channel.state);
+ }
+ return;
+ }
+ channel.state.pendingToolCallMessage = null;
+ if (!event.message) {
+ clearStream(channel.state);
+ return;
+ }
+ await finalizeStreamedMessage(channel, event.message, true);
},
async "turn.failed"(event, channel, _ctx) {
await postFailure(channel.thread, "I hit an error while handling your request", event);
@@ -302,6 +395,88 @@ function defaultEvents<TAdapters extends ChatSdkAdapters>(
};
}
+/**
+ * Posts a typing indicator without failing the turn when the adapter does not
+ * support one. Swallows {@link isNotImplemented} errors (e.g. email adapters)
+ * and rethrows anything else.
+ */
+async function safeStartTyping(thread: Thread | null, status?: string): Promise<void> {
+ if (!thread) return;
+ try {
+ await thread.startTyping(status);
+ } catch (error) {
+ if (!isNotImplemented(error)) throw error;
+ }
+}
+
+/**
+ * Edits a previously posted message in place via the adapter. Rendered as
+ * markdown so streamed edits match the completed-message formatting. Callers
+ * handle {@link isNotImplemented} to fall back to a fresh post.
+ */
+async function editMessage(thread: Thread, messageId: string, markdown: string): Promise<void> {
+ await thread.adapter.editMessage(thread.id, messageId, { markdown });
+}
+
+/**
+ * Finalizes a completed assistant message. When a streamed anchor exists, edits
+ * it in place so it shows the complete text instead of the last throttled
+ * delta. When no anchor was streamed and `postWhenNoAnchor` is `true`, posts the
+ * message fresh (the normal path for a final reply on a non-streaming surface);
+ * when `false`, leaves the surface untouched so intermediate tool-call narration
+ * does not become a standalone message. Clears the stream anchor either way.
+ */
+async function finalizeStreamedMessage(
+ channel: ChatSdkChannelContext,
+ message: string,
+ postWhenNoAnchor: boolean,
+): Promise<void> {
+ const thread = channel.thread;
+ if (!thread) {
+ clearStream(channel.state);
+ return;
+ }
+ const anchor = channel.state.anchorMessageId;
+ if (canStream(channel) && anchor) {
+ try {
+ await editMessage(thread, anchor, message);
+ } catch (error) {
+ if (!isNotImplemented(error)) throw error;
+ channel.state.editSupported = false;
+ if (postWhenNoAnchor) await thread.post({ markdown: message });
+ }
+ } else if (postWhenNoAnchor) {
+ await thread.post({ markdown: message });
+ }
+ clearStream(channel.state);
+}
+
+/** Whether streamed edits are enabled and still supported by the adapter. */
+function canStream(channel: ChatSdkChannelContext): boolean {
+ return channel.streaming && channel.state.editSupported !== false;
+}
+
+/** Resets the streaming anchor so the next step starts a fresh message. */
+function clearStream(state: ChatSdkChannelState): void {
+ state.anchorMessageId = null;
+ state.lastEditAtMs = null;
+ state.streamStepIndex = null;
+}
+
+/** First non-blank line of `text`, used as a compact typing status. */
+function firstNonEmptyLine(text: string): string | undefined {
+ for (const line of text.split(/\r?\n/u)) {
+ const trimmed = line.trim();
+ if (trimmed.length > 0) return trimmed;
+ }
+ return undefined;
+}
+
+/** Caps `text` at `max` characters with a trailing ellipsis. */
+function truncate(text: string, max = MAX_TYPING_STATUS): string {
+ return text.length <= max ? text : `${text.slice(0, max - 1)}\u2026`;
+}
+
function renderInputRequests(requests: readonly InputRequest[], inputActionPrefix: string) {
return Card({
children: requests.flatMap((request) => renderInputRequest(request, inputActionPrefix)),
diff --git a/packages/eve/src/public/channels/chat-sdk/index.ts b/packages/eve/src/public/channels/chat-sdk/index.ts
index c67756c50..2d397cc6a 100644
--- a/packages/eve/src/public/channels/chat-sdk/index.ts
+++ b/packages/eve/src/public/channels/chat-sdk/index.ts
@@ -11,3 +11,5 @@ export {
type ChatSdkReceiveTarget,
type ChatSdkSendOptions,
} from "#public/channels/chat-sdk/chatSdkChannel.js";
+export { messageToUserContent } from "#public/channels/chat-sdk/messageToUserContent.js";
+export { isNotImplemented } from "#public/channels/chat-sdk/notImplemented.js";
diff --git a/packages/eve/src/public/channels/chat-sdk/messageToUserContent.ts b/packages/eve/src/public/channels/chat-sdk/messageToUserContent.ts
new file mode 100644
index 000000000..3763d2a53
--- /dev/null
+++ b/packages/eve/src/public/channels/chat-sdk/messageToUserContent.ts
@@ -0,0 +1,37 @@
+import type { UserContent } from "ai";
+
+import type { Message } from "#compiled/chat/index.js";
+
+type UserContentParts = Exclude<UserContent, string>;
+
+/**
+ * Converts a Chat SDK `Message` into the input shape `chatSdkChannel().send`
+ * accepts.
+ *
+ * Returns `message.text` when the message has no attachments. When attachments
+ * are present, returns an AI SDK `UserContent` array: the text (when non-empty)
+ * followed by one `file` part per attachment that exposes a URL. Attachments
+ * without a URL are skipped, and a message whose only attachments lack URLs
+ * falls back to `message.text`.
+ */
+export function messageToUserContent(message: Message): string | UserContent {
+ const attachments = message.attachments ?? [];
+ if (attachments.length === 0) {
+ return message.text;
+ }
+
+ const parts: UserContentParts = [];
+ if (message.text) {
+ parts.push({ text: message.text, type: "text" });
+ }
+ for (const attachment of attachments) {
+ if (!attachment.url) continue;
+ parts.push({
+ data: new URL(attachment.url),
+ filename: attachment.name,
+ mediaType: attachment.mimeType ?? "application/octet-stream",
+ type: "file",
+ });
+ }
+ return parts.length > 0 ? parts : message.text;
+}
diff --git a/packages/eve/src/public/channels/chat-sdk/notImplemented.ts b/packages/eve/src/public/channels/chat-sdk/notImplemented.ts
new file mode 100644
index 000000000..22f5e1db7
--- /dev/null
+++ b/packages/eve/src/public/channels/chat-sdk/notImplemented.ts
@@ -0,0 +1,13 @@
+/**
+ * True when `error` signals a Chat SDK operation the active adapter does not
+ * support. Matched by both `name` and `code` so optional capabilities such as
+ * typing indicators and streaming edits can degrade gracefully instead of
+ * failing the whole event handler.
+ */
+export function isNotImplemented(error: unknown): boolean {
+ return (
+ error instanceof Error &&
+ (error.name === "NotImplementedError" ||
+ (error as { code?: unknown }).code === "NOT_IMPLEMENTED")
+ );
+}