The Open Framework for Building Agents
feat(eve): chat-sdk - add experimental steering policy (#1438)
Andrew Barba0c0de19d3169
diff --git a/.changeset/chat-sdk-experimental-steer.md b/.changeset/chat-sdk-experimental-steer.mdnew file mode 100644index 000000000..ff09059bb--- /dev/null+++ b/.changeset/chat-sdk-experimental-steer.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Add an opt-in experimental steering policy to Chat SDK sends that cancels an active turn before delivering its replacement message.diff --git a/docs/channels/chat-sdk.mdx b/docs/channels/chat-sdk.mdxindex 67dd6039f..79799d8c9 100644--- a/docs/channels/chat-sdk.mdx+++ b/docs/channels/chat-sdk.mdx@@ -97,7 +97,24 @@ bot.onNewMention(async (thread, message) => {});```-`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.+`options` accepts `{ thread, auth?, title?, mode?, callback?, adapterName?, turnPolicy? }`. `title` sets the eve session's display title without changing the model message; `auth` attaches an authenticated principal to the turn.++### Experimental steering++By default, a message sent while an eve turn is active waits for the next turn. Pass `turnPolicy: "experimental-steer"` to cancel the active turn before sending the new message:++```ts+bot.onSubscribedMessage(async (thread, message) => {+ await send(message.text, {+ thread,+ turnPolicy: "experimental-steer",+ });+});+```++This is cancellation-backed steering: the interrupted turn emits `turn.cancelled`, and the replacement message starts a new turn with a new turn ID. Partial output and completed side effects from the interrupted turn are not rolled back. If no turn is active, the message is sent normally. Use the default `turnPolicy: "queue"` when every turn should finish in order.++This policy controls overlapping eve turns. Chat SDK's separate `concurrency` option controls overlapping webhook handlers; use `concurrency: "concurrent"` when each inbound message should reach the experimental steering path immediately.### Deliverydiff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.tsindex ef4aaf71e..fdf51b3c4 100644--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts@@ -13,7 +13,7 @@ import {messageToUserContent,type ChatSdkChannelState,} from "#public/channels/chat-sdk/index.js";-import type { RouteHandlerArgs, SendFn } from "#public/definitions/channel.js";+import type { CancelFn, RouteHandlerArgs, SendFn } from "#public/definitions/channel.js";import type {Adapter,AdapterPostableMessage,@@ -88,6 +88,7 @@ async function firePost(path: string,body: Record<string, unknown>,): Promise<{+ cancel: ReturnType<typeof vi.fn<CancelFn>>;response: Response;send: ReturnType<typeof vi.fn<SendFn<ChatSdkChannelState>>>;waitUntil: ReturnType<typeof vi.fn>;@@ -110,6 +111,7 @@ async function firePost(return -1;},});+ const cancel = vi.fn<CancelFn>().mockResolvedValue({ status: "accepted" });const waitUntil = vi.fn();const response = await post.handler(@@ -121,7 +123,7 @@ async function firePost({getSession: vi.fn() as any,resolveActiveSession: async () => undefined,- cancel: vi.fn(),+ cancel,reset: vi.fn(),params: {},receive: vi.fn() as any,@@ -138,7 +140,7 @@ async function firePost(await Promise.allSettled(pending);}- return { response, send, waitUntil };+ return { cancel, response, send, waitUntil };}describe("chatSdkChannel", () => {@@ -205,11 +207,12 @@ describe("chatSdkChannel", () => {await bridge.send(message.text, { auth: AUTH, thread, title: "mention" });});- const { response, send } = await firePost(bridge.channel, "/eve/v1/test", {+ const { cancel, response, send } = await firePost(bridge.channel, "/eve/v1/test", {text: "@bot hello",});expect(response.status).toBe(200);+ expect(cancel).not.toHaveBeenCalled();expect(send).toHaveBeenCalledTimes(1);expect(send.mock.calls[0]?.[0]).toBe("@bot hello");expect(send.mock.calls[0]?.[1]).toMatchObject({@@ -227,6 +230,68 @@ describe("chatSdkChannel", () => {});});+ it("cancels the active turn before an experimental steering send", async () => {+ const bridge = chatSdkChannel({+ adapters: { test: testAdapter() },+ concurrency: "concurrent",+ state: memoryState(),+ userName: "bot",+ });++ bridge.bot.onNewMention(async (thread: Thread, message: Message) => {+ await bridge.send(message.text, {+ auth: AUTH,+ thread,+ turnPolicy: "experimental-steer",+ });+ });++ const { cancel, response, send } = await firePost(bridge.channel, "/eve/v1/test", {+ text: "@bot correction",+ });++ expect(response.status).toBe(200);+ expect(cancel).toHaveBeenCalledWith({ continuationToken: THREAD_ID });+ expect(send).toHaveBeenCalledWith("@bot correction", {+ auth: AUTH,+ continuationToken: THREAD_ID,+ state: {+ thread: expect.objectContaining({+ adapterName: "test",+ id: THREAD_ID,+ }),+ },+ });+ expect(cancel.mock.invocationCallOrder[0]).toBeLessThan(send.mock.invocationCallOrder[0]!);+ });++ it("does not cancel for an experimental steering response without a message", async () => {+ const bridge = chatSdkChannel({+ adapters: { test: testAdapter() },+ concurrency: "concurrent",+ state: memoryState(),+ userName: "bot",+ });++ bridge.bot.onNewMention(async (thread: Thread) => {+ await bridge.send(+ { inputResponses: [{ optionId: "approve", requestId: "request-1" }] },+ { thread, turnPolicy: "experimental-steer" },+ );+ });++ const { cancel, response, send } = await firePost(bridge.channel, "/eve/v1/test", {+ text: "@bot approve",+ });++ expect(response.status).toBe(200);+ expect(cancel).not.toHaveBeenCalled();+ expect(send).toHaveBeenCalledWith(+ { inputResponses: [{ optionId: "approve", requestId: "request-1" }] },+ expect.objectContaining({ continuationToken: THREAD_ID }),+ );+ });+it("fails loudly when bridge.send is called outside a Chat SDK webhook", async () => {const bridge = chatSdkChannel({adapters: { test: testAdapter() },diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.tsindex ce1411f5b..516cd531e 100644--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts@@ -30,6 +30,7 @@ import {type Channel,type ChannelEvents,type ChannelSessionOps,+ type CancelFn,type RouteHandlerArgs,type SendFn,type SendOptions,@@ -48,6 +49,7 @@ type EventData<T extends UnstampedMessageStreamEvent["type"]> =Extract<UnstampedMessageStreamEvent, { type: T }> extends { data: infer D } ? D : undefined;interface ActiveWebhookContext {+ readonly cancel: CancelFn;readonly send: SendFn<ChatSdkChannelState>;}@@ -134,6 +136,13 @@ export interface ChatSdkSendOptions {readonly mode?: SendOptions<ChatSdkChannelState>["mode"];readonly thread: SerializedThread | Thread | string;readonly title?: string;+ /**+ * Controls how this input interacts with an active eve turn on the same+ * thread. Defaults to `"queue"`. `"experimental-steer"` requests+ * cancellation of the active turn before sending this input as its+ * replacement.+ */+ readonly turnPolicy?: "queue" | "experimental-steer";/*** 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@@ -295,7 +304,7 @@ export function chatSdkChannel<TAdapters extends ChatSdkAdapters>(): Promise<Response> => {const webhook = bot.webhooks[adapterName];const ctx = new ContextContainer();- ctx.setVirtualContext(ActiveWebhookKey, { send: args.send });+ ctx.setVirtualContext(ActiveWebhookKey, { cancel: args.cancel, send: args.send });return contextStorage.run(ctx, () =>webhook(request, {...config.webhook,@@ -559,9 +568,16 @@ async function bridgeSend<TAdapters extends ChatSdkAdapters>(if (options.title) {sendOptions.title = options.title;}+ if (options.turnPolicy === "experimental-steer" && hasMessageInput(input)) {+ await active.cancel({ continuationToken: thread.id });+ }return active.send(input, sendOptions);}+function hasMessageInput(input: ChatSdkSendInput): boolean {+ return typeof input === "string" || Array.isArray(input) || input.message !== undefined;+}+function initialState(): ChatSdkChannelState {return { thread: null };}