The Open Framework for Building Agents
feat(eve): channels - steer active turns by default (#1836)
Andrew Barba2dd193b6655b
diff --git a/.changeset/steer-channel-turns.md b/.changeset/steer-channel-turns.mdnew file mode 100644index 000000000..7158f488c--- /dev/null+++ b/.changeset/steer-channel-turns.md@@ -0,0 +1,5 @@+---+"eve": minor+---++Channel message sends now use `turnPolicy: "steer"` by default, so accepted messages replace active turns through cancellation-backed steering without a separate cancel request. Set `turnPolicy: "queue"` on a channel or individual send to preserve the previous wait-for-completion behavior.diff --git a/docs/channels/chat-sdk.mdx b/docs/channels/chat-sdk.mdxindex 18466a52d..2a82aa7cc 100644--- a/docs/channels/chat-sdk.mdx+++ b/docs/channels/chat-sdk.mdx@@ -99,22 +99,22 @@ bot.onNewMention(async (thread, message) => {`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+### 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:+Messages default to `turnPolicy: "steer"`: a message sent while an eve turn is active is durably buffered, then cancels that turn and starts as its replacement. Set `turnPolicy: "queue"` when the active turn should finish first:```tsbot.onSubscribedMessage(async (thread, message) => {await send(message.text, {thread,- turnPolicy: "experimental-steer",+ turnPolicy: "queue",});});```-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.+Cancellation-backed steering 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. You can set the policy once on `chatSdkChannel({ turnPolicy })` or override it per `send(...)`.-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.+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 steering path immediately.### Deliverydiff --git a/docs/channels/custom.mdx b/docs/channels/custom.mdxindex 46429f624..fb50a3812 100644--- a/docs/channels/custom.mdx+++ b/docs/channels/custom.mdx@@ -109,6 +109,26 @@ await session.reset({ reason: "Retire this session" });await session.getEventStream({ startIndex: 12 });```+Message sends use the channel's `turnPolicy`, which defaults to `"steer"`. An accepted message arriving during an active turn is durably buffered before eve cancels that turn and starts the message as a replacement turn. Configure `turnPolicy: "queue"` on `defineChannel(...)` when active turns should finish in order, or override one send:++```ts+export default defineChannel({+ turnPolicy: "queue",+ routes: [+ POST("/messages", async (request, { from }) => {+ const body = await request.json();+ await from(body.threadId).send(body.message, {+ auth: null,+ turnPolicy: "steer",+ });+ return new Response(null, { status: 202 });+ }),+ ],+});+```++The same override is available on fixed `Session.send(...)` and cross-channel `to(...).send(...)`. `respond(...)` never steers: it delivers only addressed input responses. Use `cancel()` when you need to stop work without a replacement message.+Attaching does no lookup. The first operation reports whether the ID is active.Call `resolveSession(address)` only when you explicitly need to snapshot anaddress's current owner as a fixed handle.diff --git a/docs/channels/eve.mdx b/docs/channels/eve.mdxindex 863c6ea39..3cdaa0153 100644--- a/docs/channels/eve.mdx+++ b/docs/channels/eve.mdx@@ -56,6 +56,8 @@ curl -X POST https://<deployment>/eve/v1/session/wrun_A \-d '{"inputResponses":[{"requestId":"req_A","optionId":"approve"}]}'```+Follow-up messages use `turnPolicy: "steer"` by default. If a turn is active, eve buffers the message before cooperatively cancelling that turn, then starts the follow-up as a replacement turn with a new turn ID. Set `turnPolicy: "queue"` on `eveChannel(...)` when follow-ups should wait for active turns to finish. `inputResponses` never steer.+Sending a message to an unknown or terminal session ID returns `409` with`{"code":"session_not_active","error":"The session is no longer active.","ok":false}`.TypeScript clients expose the stable code as `ClientError.code`. The route neverdiff --git a/docs/channels/overview.mdx b/docs/channels/overview.mdxindex 9c51735c5..efd34138d 100644--- a/docs/channels/overview.mdx+++ b/docs/channels/overview.mdx@@ -13,6 +13,25 @@ eve ships a base HTTP channel plus first-class platform channels, and you can auAfter a channel normalizes input, eve runs the same agent runtime regardless of where the message came from. Tools and instructions do not need channel-specific logic.+## Overlapping messages++Channels default to `turnPolicy: "steer"`. When an accepted message arrives while a turn is active, eve first durably buffers the message, then cooperatively cancels the active turn and starts a replacement turn. The cancelled turn emits `turn.cancelled` followed by `session.waiting`; the replacement starts with a new turn ID. Output already streamed and completed side effects are not rolled back.++Set `turnPolicy: "queue"` on any built-in or custom channel when each turn must finish before the next message starts:++```ts+export default defineChannel({+ turnPolicy: "queue",+ routes: [+ // ...+ ],+});+```++`from(address).send(...)`, fixed `Session.send(...)`, cross-channel sends, and Chat SDK bridge sends also accept a per-send `turnPolicy` override. Pure `inputResponses` deliveries answer their pending request without steering. Explicit `cancel()` remains the stop-without-replacement operation.++Channel admission still runs first. Ignored mentions, rejected signatures, duplicates, and any other dropped platform events never affect the active turn.+Each channel has its own provider terms, data flow, auth model, and user-consent expectations. Before sending non-public, sensitive, regulated, or production data through a channel, confirm that the channel provider and your configured scopes, signature checks, route auth, and delivery behavior are appropriate for your use case.## Where channels livediff --git a/docs/channels/photon.mdx b/docs/channels/photon.mdxindex 6ac095b61..da17c85b5 100644--- a/docs/channels/photon.mdx+++ b/docs/channels/photon.mdx@@ -27,6 +27,8 @@ read, and continues the same eve session for every message in an iMessageconversation. A new accepted message cooperatively cancels an active turn andsteers its replacement turn.+Set `turnPolicy: "queue"` when every response should finish before Photon starts the next message.+Customize inbound dispatch with `onMessage`. Return `null` to ignore a message:```tsdiff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdxindex 9db6971f7..6e5b313ee 100644--- a/docs/channels/slack.mdx+++ b/docs/channels/slack.mdx@@ -236,24 +236,18 @@ export default slackChannel({`threadContext` requires the matching Slack history scope. Thread helpers reuse messages already loaded within the same inbound handler, and overlapping refreshes share one `conversations.replies` request. Omit it when the agent should see only direct mentions. `loadThreadContextMessages` remains available when you need custom filtering or non-model processing of the raw thread messages.-#### Cancel an active turn+#### Control overlapping turns-Message hooks (`onMessage`, `onAppMention`, and `onDirectMessage`) receive thread-bound session operations directly on `ctx`. Call `ctx.cancel({ turnId? })` before returning `{ auth }` to stop the current turn and queue the new Slack message as replacement input, producing a debounce-like experience:+Accepted Slack messages use cancellation-backed steering by default: eve buffers the new message, cancels the active turn, and starts a replacement turn. Admission happens first, so ignored mentions and messages rejected by your hooks never cancel work. Set `turnPolicy: "queue"` when every active turn should finish:```ts title="agent/channels/slack.ts"export default slackChannel({credentials: connectSlackCredentials("slack/my-agent"),- async onMessage(ctx, message) {- const shouldHandle = ctx.isBotMentioned() || (await ctx.isSubscribed());- if (!shouldHandle || message.author?.isBot) return null;-- await ctx.cancel();- return { auth: null };- },+ turnPolicy: "queue",});```-`"accepted"` means the live thread session durably queued the cancellation request. A parked session consumes it as a no-op; `"no_active_turn"` means the thread has no active session owner. Both are successful outcomes, so the hook can still return `{ auth }` to deliver the replacement message. Cancellation never sends input itself. A custom `onInteraction` handler receives the same flat operations, which is useful for a Stop button that should cancel without replacement input.+Message hooks (`onMessage`, `onAppMention`, and `onDirectMessage`) also receive thread-bound session operations directly on `ctx`. `ctx.cancel({ turnId? })` remains useful for a Stop button: it cancels without sending replacement input. `"accepted"` means the live thread session durably queued that request; a parked session consumes it as a no-op, and `"no_active_turn"` means the thread has no active session owner.Message and interaction hooks expose every current-owner operation directly on `ctx`:diff --git a/docs/concepts/execution-model-and-durability.mdx b/docs/concepts/execution-model-and-durability.mdxindex d2eb75c5e..4e88e2370 100644--- a/docs/concepts/execution-model-and-durability.mdx+++ b/docs/concepts/execution-model-and-durability.mdx@@ -66,7 +66,7 @@ You don't write workflow code directly. Workflow primitives (`start()`, `resumeHSome work has to wait, including a human approving a [tool](../tools), an interactive OAuth sign-in for a [connection](../connections), or a long-running [subagent](../subagents). At those points the turn parks durably. The workflow suspends and holds no compute until the input it's waiting on arrives (a click, a callback, a child completing), even if that's much later. When it does, the conversation picks up exactly where it left off.-## Message delivery and queueing+## Message delivery and steeringeve does not maintain a durable FIFO queue of user messages for a session. AnID-addressed HTTP delivery and a channel-address delivery both target the@@ -79,14 +79,11 @@ channel alias. Rekeying replaces only that channel alias. An HTTP-createdsession has the stable ID alias and no channel continuation token. Competingchannel input is not forwarded to the owner.-When a session is waiting, a delivery through its ID or current channel address-wakes the session and starts the next turn. When a turn is already active, the-inbox may accept additional deliveries, but the runtime only drains them at-specific workflow boundaries. If more than one delivery is ready when the driver-checks, eve may fold them into the next turn; that drain is best-effort and-depends on workflow and transport timing.+When a session is waiting, a delivery through its ID or current channel address wakes it and starts the next turn. Message sends default to `turnPolicy: "steer"`: while a turn is active, the session driver durably buffers the replacement before requesting cooperative cancellation. The interrupted turn emits `turn.cancelled` followed by `session.waiting`, then the replacement starts with a new turn ID. Partial output and completed side effects are not rolled back.-So don't rely on concurrent sends to the same session behaving like a typical ordered chat queue. For deterministic behavior, send one user turn at a time and wait for `session.waiting` before sending the next message to the same session. If your channel can receive bursts while the agent is working, keep your own per-session queue in the channel or app layer, then deliver the next message after the session parks again. Separate sessions still run independently.+`turnPolicy: "queue"` preserves the message until the active turn settles. If several deliveries are ready when the driver checks, eve may fold adjacent messages into the next turn while preserving their arrival order. Pure `inputResponses` deliveries do not steer; they remain available to the pending request they address.++Every built-in and custom channel accepts a default `turnPolicy`, and imperative message sends can override it. The policy is part of the same durable delivery command as the message, so concurrent senders cannot separate replacement ownership from cancellation intent. Separate sessions still run independently.## Subagentsdiff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.mdindex 893f76d7c..864c91ed3 100644--- a/docs/concepts/sessions-runs-and-streaming.md+++ b/docs/concepts/sessions-runs-and-streaming.md@@ -148,7 +148,7 @@ curl -X POST http://127.0.0.1:2000/eve/v1/session/<sessionId> \-d '{"message":"Now send the short version."}'```-The follow-up reuses the same durable session: same history, same state.+The follow-up reuses the same durable session: same history, same state. Message sends default to cancellation-backed `"steer"`; if a turn is active, eve buffers the follow-up, cancels that turn, and starts the message under a new turn ID. Channels and TypeScript `Session.send(...)` calls can select `turnPolicy: "queue"` when active work should finish first. Structured `inputResponses` never steer.If the session is waiting on a human-in-the-loop approval, a matching text reply such as `approve` or `cancel` answers the approval. Other follow-up text is held until the approval is answered, so an unrelated message does not implicitly deny the pending tool call.@@ -158,7 +158,7 @@ A response is stale when its request is no longer pending: the question or approResponses match pending requests by request ID, so a response to an older request stays a plain user message even while a different question or approval is pending. Like any follow-up message, a stale response clears a pending question and is held while an approval is pending.-For deterministic ordering, send one follow-up at a time and wait for the next `session.waiting` event before sending another message to the same session. See [message delivery and queueing](./execution-model-and-durability#message-delivery-and-queueing) for the current runtime contract.+Multiple replacement messages retain their durable arrival order and may be folded into the same replacement turn when they arrive before cancellation settles. See [message delivery and steering](./execution-model-and-durability#message-delivery-and-steering) for the current runtime contract.## Cancel the in-flight turndiff --git a/e2e/fixtures/agent-cancellation/agent/agent.ts b/e2e/fixtures/agent-cancellation/agent/agent.tsindex 41a0bd9c1..b3c2be2c3 100644--- a/e2e/fixtures/agent-cancellation/agent/agent.ts+++ b/e2e/fixtures/agent-cancellation/agent/agent.ts@@ -1,7 +1,20 @@import { e2eAgentConfig } from "@eve-e2e/config";import { defineAgent } from "eve";-const base = e2eAgentConfig();+const base = e2eAgentConfig({+ mock: ({ lastUserMessage }) =>+ lastUserMessage?.includes("Please wait for cancellation.") === true+ ? {+ toolCalls: [+ {+ id: "wait-for-cancellation",+ input: {},+ name: "wait-for-cancellation",+ },+ ],+ }+ : `Mock reply: ${lastUserMessage ?? ""}`,+});export default defineAgent({...base,diff --git a/e2e/fixtures/agent-cancellation/agent/channels/threads.ts b/e2e/fixtures/agent-cancellation/agent/channels/threads.tsindex 74e585fb5..5893270a6 100644--- a/e2e/fixtures/agent-cancellation/agent/channels/threads.ts+++ b/e2e/fixtures/agent-cancellation/agent/channels/threads.ts@@ -1,4 +1,4 @@-import { defineChannel, POST } from "eve/channels";+import { defineChannel, POST, type TurnPolicy } from "eve/channels";const AUTH = {attributes: { source: "cancellation-eval" },@@ -15,11 +15,16 @@ const AUTH = {* knowing the runtime session id.*/export default defineChannel({+ turnPolicy: "queue",routes: [POST("/threads/:threadId/messages", async (request, { from, params }) => {- const body = (await request.json().catch(() => ({}))) as { message?: string };+ const body = (await request.json().catch(() => ({}))) as {+ message?: string;+ turnPolicy?: TurnPolicy;+ };const session = await from(params.threadId ?? "").send(body.message ?? "", {auth: AUTH,+ turnPolicy: body.turnPolicy,});return Response.json({ ok: true, sessionId: session.id });}),diff --git a/e2e/fixtures/agent-cancellation/evals/cancellation/steer-channel-message.eval.ts b/e2e/fixtures/agent-cancellation/evals/cancellation/steer-channel-message.eval.tsnew file mode 100644index 000000000..b9bd89f2e--- /dev/null+++ b/e2e/fixtures/agent-cancellation/evals/cancellation/steer-channel-message.eval.ts@@ -0,0 +1,86 @@+import type { TurnPolicy } from "eve/channels";+import { defineEval, type EveEvalTargetHandle } from "eve/evals";+import { satisfies } from "eve/evals/expect";++const TOOL_NAME = "wait-for-cancellation";++interface MessageResponse {+ readonly ok: boolean;+ readonly sessionId?: string;+}++async function postMessage(+ target: EveEvalTargetHandle,+ threadId: string,+ message: string,+ turnPolicy?: TurnPolicy,+): Promise<MessageResponse> {+ const path = `/threads/${threadId}/messages`;+ const response = await target.fetch(path, {+ body: JSON.stringify({ message, turnPolicy }),+ headers: { "content-type": "application/json" },+ method: "POST",+ });+ const text = await response.text();+ if (!response.ok) {+ throw new Error(`POST ${path} failed (${response.status}): ${text}`);+ }+ return JSON.parse(text) as MessageResponse;+}++/** Replaces an active turn through the custom channel's default steering policy. */+export default defineEval({+ description: "An accepted channel message replaces the active turn by default.",+ timeoutMs: 240_000,++ async test(t) {+ const threadId = crypto.randomUUID();+ const started = await postMessage(t.target, threadId, "Please wait for cancellation.");+ await t.require(+ started,+ satisfies(+ (value: MessageResponse) => value.ok === true && typeof value.sessionId === "string",+ "the initial channel message starts a session",+ ),+ );+ const sessionId = started.sessionId!;+ const activeTurn = t.target.watchTurn(sessionId);++ await activeTurn.waitForEvent("actions.requested", {+ data: {+ actions: (actions) =>+ actions.some((action) => action.kind === "tool-call" && action.toolName === TOOL_NAME),+ },+ });++ const replacement = await postMessage(+ t.target,+ threadId,+ "Reply with exactly CHANNEL-STEERING-REPLACEMENT-OK.",+ "steer",+ );+ await t.require(+ replacement,+ satisfies(+ (value: MessageResponse) => value.sessionId === sessionId,+ "the replacement remains in the same durable session",+ ),+ );++ const cancelled = await activeTurn.result();+ cancelled.event("turn.cancelled", { count: 1 });+ cancelled.eventOrder([{ type: "turn.cancelled" }, { type: "session.waiting" }]);+ cancelled.notEvent("turn.failed");+ cancelled.notEvent("session.failed");++ const replacementTurn = await t.target+ .watchTurn(sessionId, { startIndex: cancelled.events.length })+ .result();+ replacementTurn.notEvent("turn.cancelled");+ replacementTurn.notEvent("turn.failed");+ replacementTurn.notEvent("session.failed");+ replacementTurn.messageIncludes(/CHANNEL-STEERING-REPLACEMENT-OK/i);++ t.succeeded();+ },+});diff --git a/e2e/fixtures/agent-session-limits/evals/limits/session-token-limit-approve.eval.ts b/e2e/fixtures/agent-session-limits/evals/limits/session-token-limit-approve.eval.tsindex a2904f97d..e04ec9abe 100644--- a/e2e/fixtures/agent-session-limits/evals/limits/session-token-limit-approve.eval.ts+++ b/e2e/fixtures/agent-session-limits/evals/limits/session-token-limit-approve.eval.ts@@ -20,7 +20,7 @@ export default defineEval({const response = await t.target.fetch(`/eve/v1/session/${encodeURIComponent(active.sessionId)}`,{- body: JSON.stringify({ message }),+ body: JSON.stringify({ message, turnPolicy: "queue" }),headers: { "content-type": "application/json" },method: "POST",},diff --git a/packages/eve/CHANGELOG.md b/packages/eve/CHANGELOG.mdindex 9ad385ed7..bbbb769c2 100644--- a/packages/eve/CHANGELOG.md+++ b/packages/eve/CHANGELOG.md@@ -189,7 +189,7 @@### Patch Changes- 22bfa02: Add guided Photon setup through `eve add channel/photon-imessage`, including project creation, phone registration, Vercel Connect or portable credentials, and channel scaffolding.-- 0c0de19: Add an opt-in experimental steering policy to Chat SDK sends that cancels an active turn before delivering its replacement message.+- 0c0de19: Add an opt-in steering policy to Chat SDK sends that cancels an active turn before delivering its replacement message.- b00a79d: Add `photonIMessageChannel`, a first-class Photon iMessage channel with lazy credentials, Vercel OIDC webhook verification, and automatic eve session routing.- 495e93b: Resolve leading `$HOME` paths in the built-in `read_file`, `write_file`, `glob`, and `grep` tools so agents can directly access packaged skill references advertised in their prompt.- bf01952: Local trace spans now capture model and tool payloads: the system prompt, prompt messages, and response text/reasoning/tool calls on model spans, and call arguments/results on tool spans, each capped at 32 KB with provider transport metadata stripped. Set `EVE_TRACES_CONTENT=off` to keep payloads out of the spool.diff --git a/packages/eve/src/channel/channel-address.test.ts b/packages/eve/src/channel/channel-address.test.tsindex f52348257..ffcd8999a 100644--- a/packages/eve/src/channel/channel-address.test.ts+++ b/packages/eve/src/channel/channel-address.test.ts@@ -44,6 +44,7 @@ describe("createChannelAddress", () => {kind: "send",payload: { message: "hello" },requestId: undefined,+ turnPolicy: "steer",},continuationToken: "slack:C1:T1",});@@ -55,6 +56,36 @@ describe("createChannelAddress", () => {});});+ it("uses the channel policy unless a send overrides it", async () => {+ const runtime = createRuntime();+ const address = createChannelAddress({+ adapter: { kind: "slack" },+ channelName: "slack",+ continuationToken: "C1:T1",+ runtime,+ turnPolicy: "queue",+ });++ await address.send("queued", { auth: null });+ await address.send("replace", { auth: null, turnPolicy: "steer" });+ await address.respond([{ optionId: "yes", requestId: "input-1" }], { auth: null });++ expect(runtime.dispatchContinuation).toHaveBeenNthCalledWith(+ 1,+ expect.objectContaining({ command: expect.objectContaining({ turnPolicy: "queue" }) }),+ );+ expect(runtime.dispatchContinuation).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({+ command: expect.objectContaining({ turnPolicy: "steer" }),+ }),+ );+ expect(runtime.dispatchContinuation).toHaveBeenNthCalledWith(+ 3,+ expect.objectContaining({ command: expect.objectContaining({ turnPolicy: undefined }) }),+ );+ });+it("binds every control directly to the namespaced continuation token", async () => {const runtime = createRuntime();const address = createChannelAddress({diff --git a/packages/eve/src/channel/channel-address.ts b/packages/eve/src/channel/channel-address.tsindex e7834c754..bac4abb28 100644--- a/packages/eve/src/channel/channel-address.ts+++ b/packages/eve/src/channel/channel-address.ts@@ -14,7 +14,9 @@ import type {SessionAuthContext,SessionCallback,SessionCommand,+ TurnPolicy,} from "#channel/types.js";+import { DEFAULT_TURN_POLICY } from "#channel/types.js";import { isRuntimeSessionOwnershipConflictError } from "#execution/runtime-errors.js";import { isReservedSessionCommandToken } from "#execution/session-command-token.js";import type { RunMode } from "#shared/run-mode.js";@@ -25,6 +27,7 @@ interface BaseChannelAddressDeliveryOptions {readonly initiatorAuth?: SessionAuthContext | null;readonly mode?: RunMode;readonly title?: string;+ readonly turnPolicy?: TurnPolicy;}/** Delivery options for a channel address whose continuation token is already bound. */@@ -66,6 +69,7 @@ export function createChannelAddress<TState = undefined>(input: {readonly continuationToken: string;readonly metadata?: { readonly requestId?: string };readonly runtime: Runtime;+ readonly turnPolicy?: TurnPolicy;}): ChannelAddress<TState> {const metadata = input.metadata ?? {};const namespacedToken = `${input.channelName}:${input.continuationToken}`;@@ -86,6 +90,10 @@ export function createChannelAddress<TState = undefined>(input: {message: serializeUrlFilePartsInMessage(payload.message),},requestId: metadata.requestId,+ turnPolicy:+ payload.message === undefined+ ? undefined+ : (options.turnPolicy ?? input.turnPolicy ?? DEFAULT_TURN_POLICY),};const command: Extract<SessionCommand, { readonly kind: "send" }> =caller === undefined ? commandWithoutCaller : { ...commandWithoutCaller, caller };@@ -95,7 +103,10 @@ export function createChannelAddress<TState = undefined>(input: {continuationToken: namespacedToken,});return result.status === "accepted"- ? createSession(result.sessionId, input.runtime, metadata)+ ? createSession(result.sessionId, input.runtime, {+ ...metadata,+ turnPolicy: input.turnPolicy,+ }): undefined;};@@ -134,7 +145,10 @@ export function createChannelAddress<TState = undefined>(input: {};try {const handle = await input.runtime.createSession(runInput);- return createSession(handle.sessionId, input.runtime, metadata);+ return createSession(handle.sessionId, input.runtime, {+ ...metadata,+ turnPolicy: input.turnPolicy,+ });} catch (error) {if (!isRuntimeSessionOwnershipConflictError(error)) throw error;const winner = await dispatch();@@ -179,7 +193,10 @@ export function createChannelAddress<TState = undefined>(input: {const owner = await input.runtime.resolveContinuation(namespacedToken);return owner === undefined? undefined- : createSession(owner.sessionId, input.runtime, metadata);+ : createSession(owner.sessionId, input.runtime, {+ ...metadata,+ turnPolicy: input.turnPolicy,+ });},};}@@ -190,6 +207,7 @@ export function createChannelAddressFn<TState = undefined>(input: {readonly channelName: string;readonly metadata?: { readonly requestId?: string };readonly runtime: Runtime;+ readonly turnPolicy?: TurnPolicy;}): ChannelAddressFn<TState> {return (continuationToken) => createChannelAddress({ ...input, continuationToken });}diff --git a/packages/eve/src/channel/channel-operations.test.ts b/packages/eve/src/channel/channel-operations.test.tsindex 387062cb0..a0ec94e52 100644--- a/packages/eve/src/channel/channel-operations.test.ts+++ b/packages/eve/src/channel/channel-operations.test.ts@@ -38,6 +38,7 @@ describe("createChannelOperations", () => {kind: "send",payload: { message: "hello" },requestId: undefined,+ turnPolicy: "steer",},continuationToken: "slack:C1:T1",});diff --git a/packages/eve/src/channel/channel-operations.ts b/packages/eve/src/channel/channel-operations.tsindex c62528194..132e86460 100644--- a/packages/eve/src/channel/channel-operations.ts+++ b/packages/eve/src/channel/channel-operations.ts@@ -15,6 +15,7 @@ import type {Runtime,SessionAuthContext,SessionCallback,+ TurnPolicy,} from "#channel/types.js";import type { InputResponse } from "#runtime/input/types.js";import type { JsonObject } from "#shared/json.js";@@ -28,6 +29,7 @@ interface BaseChannelSendOptions {readonly mode?: RunMode;readonly outputSchema?: JsonObject;readonly title?: string;+ readonly turnPolicy?: TurnPolicy;}/** Options for sending a message from a channel-local continuation address. */@@ -91,6 +93,7 @@ export function createChannelOperations<TState = undefined>(input: {readonly channelName: string;readonly metadata?: { readonly requestId?: string };readonly runtime: Runtime;+ readonly turnPolicy?: TurnPolicy;}): ChannelReceiveContext<TState> {const channelAddress = createChannelAddressFn<TState>(input);diff --git a/packages/eve/src/channel/compiled-channel.ts b/packages/eve/src/channel/compiled-channel.tsindex 1b6fd49e9..7124fbe22 100644--- a/packages/eve/src/channel/compiled-channel.ts+++ b/packages/eve/src/channel/compiled-channel.ts@@ -5,7 +5,7 @@ import type { NormalizedChannelCorsOptions } from "#channel/cors.js";import type { TypedReceiveTarget } from "#channel/receive-target.js";import type { RouteDefinition } from "#channel/routes.js";import type { Session } from "#channel/session.js";-import type { SessionAuthContext } from "#channel/types.js";+import type { SessionAuthContext, TurnPolicy } from "#channel/types.js";export const CHANNEL_SENTINEL = "eve:channel" as const;const CHANNEL_INSTRUMENTATION_KIND = Symbol.for("eve.channel.instrumentationKind");@@ -45,6 +45,7 @@ export interface CompiledChannel<},ctx: ChannelReceiveContext<TState>,) => Promise<Session>;+ readonly turnPolicy?: TurnPolicy;}export function isCompiledChannel(value: unknown): value is CompiledChannel {diff --git a/packages/eve/src/channel/cross-channel-receive.ts b/packages/eve/src/channel/cross-channel-receive.tsindex 99279022f..e914ff584 100644--- a/packages/eve/src/channel/cross-channel-receive.ts+++ b/packages/eve/src/channel/cross-channel-receive.ts@@ -9,7 +9,7 @@ import {} from "#channel/compiled-channel.js";import type { InferReceiveTarget } from "#channel/receive-target.js";import type { Session } from "#channel/session.js";-import type { Runtime, SessionAuthContext } from "#channel/types.js";+import type { Runtime, SessionAuthContext, TurnPolicy } from "#channel/types.js";import type { ResolvedChannelDefinition } from "#runtime/types.js";/**@@ -17,6 +17,7 @@ import type { ResolvedChannelDefinition } from "#runtime/types.js";*/export interface CrossChannelSendOptions {readonly auth: SessionAuthContext | null;+ readonly turnPolicy?: TurnPolicy;}/** Message delivery bound to one channel-specific proactive target. */@@ -40,6 +41,7 @@ export interface CrossChannelTarget {readonly definition: CompiledChannel;readonly receive?: CompiledChannel["receive"];readonly adapter?: ChannelAdapter;+ readonly turnPolicy?: CompiledChannel["turnPolicy"];}/**@@ -61,6 +63,7 @@ export function toCrossChannelTargets(definition: channel.definition,receive: channel.receive,adapter: channel.adapter,+ turnPolicy: channel.turnPolicy,},],);@@ -85,6 +88,7 @@ export function createCrossChannelToFn(target: target as Readonly<Record<string, unknown>>,auth: options.auth,},+ turnPolicy: options.turnPolicy,describeMissingReceive: () =>`ctx.to(): channel "${targetChannel.name}" does not implement receive(). ` +`Declare a receive hook on the channel to accept cross-channel sessions.`,@@ -98,12 +102,13 @@ export function createCrossChannelToFn(interface InvokeChannelReceiveInput {readonly runtime: Runtime;- readonly target: Pick<CrossChannelTarget, "name" | "receive" | "adapter">;+ readonly target: Pick<CrossChannelTarget, "name" | "receive" | "adapter" | "turnPolicy">;readonly input: {readonly message: string | UserContent;readonly target: Readonly<Record<string, unknown>>;readonly auth: SessionAuthContext | null;};+ readonly turnPolicy?: TurnPolicy;readonly describeMissingReceive: () => string;readonly describeMissingAdapter: () => string;}@@ -122,6 +127,7 @@ export async function invokeChannelReceive(args: InvokeChannelReceiveInput): Proadapter: args.target.adapter,channelName: args.target.name,runtime: args.runtime,+ turnPolicy: args.turnPolicy ?? args.target.turnPolicy,});return await args.target.receive(args.input, channelOperations);}diff --git a/packages/eve/src/channel/session.test.ts b/packages/eve/src/channel/session.test.tsindex 408be8300..7e20941e1 100644--- a/packages/eve/src/channel/session.test.ts+++ b/packages/eve/src/channel/session.test.ts@@ -74,6 +74,7 @@ describe("fixed session operations", () => {kind: "send",payload: { message: "hello" },requestId: "req_1",+ turnPolicy: "steer",},sessionId: "sess_1",});@@ -128,6 +129,7 @@ describe("fixed session operations", () => {kind: "send",payload: { message: "continue" },requestId: undefined,+ turnPolicy: "steer",},sessionId: "sess_1",});diff --git a/packages/eve/src/channel/session.ts b/packages/eve/src/channel/session.tsindex 0f66c2501..ac46e7d13 100644--- a/packages/eve/src/channel/session.ts+++ b/packages/eve/src/channel/session.ts@@ -10,8 +10,10 @@ import type {SessionAuthContext,SessionCallback,SessionSendCommandResult,+ TurnPolicy,TurnCaller,} from "#channel/types.js";+import { DEFAULT_TURN_POLICY } from "#channel/types.js";import { serializeUrlFilePartsInMessage } from "#channel/send-input.js";import type { SessionAuth } from "#context/keys.js";import { AuthKey, ContinuationTokenKey, InitiatorAuthKey, SessionIdKey } from "#context/keys.js";@@ -53,7 +55,7 @@ interface SessionDeliveryOptions {}/** Options for sending a message through a fixed session handle. */-export type SessionSendOptions = SessionDeliveryOptions;+export type SessionSendOptions = SessionDeliveryOptions & { readonly turnPolicy?: TurnPolicy };/** Options for answering pending input requests through a fixed session handle. */export type SessionRespondOptions = SessionDeliveryOptions;@@ -77,7 +79,7 @@ export interface SessionHandle {export function createSession(id: string,runtime: Runtime,- metadata: { readonly requestId?: string } = {},+ metadata: { readonly requestId?: string; readonly turnPolicy?: TurnPolicy } = {},): Session {return {id,@@ -95,6 +97,7 @@ export function createSession(kind: "send" as const,payload,requestId: metadata.requestId,+ turnPolicy: options.turnPolicy ?? metadata.turnPolicy ?? DEFAULT_TURN_POLICY,};return await runtime.dispatchSession({command: caller === undefined ? commandWithoutCaller : { ...commandWithoutCaller, caller },@@ -154,7 +157,7 @@ export function createSession(/** Builds an I/O-free factory for fixed session-ID handles. */export function createAttachSessionFn(runtime: Runtime,- metadata: { readonly requestId?: string } = {},+ metadata: { readonly requestId?: string; readonly turnPolicy?: TurnPolicy } = {},): (sessionId: string) => Session {return (sessionId) => createSession(sessionId, runtime, metadata);}diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.tsindex 0488d044b..bc46efed5 100644--- a/packages/eve/src/channel/types.ts+++ b/packages/eve/src/channel/types.ts@@ -146,6 +146,12 @@ export interface DeliverPayload {readonly [key: string]: unknown;}+/** Controls how a channel message interacts with an active turn. */+export type TurnPolicy = "steer" | "queue";++/** Default policy for message sends produced by current channel surfaces. */+export const DEFAULT_TURN_POLICY: TurnPolicy = "steer";+/** One command accepted by a durable session inbox. */export type SessionCommand =| {@@ -154,6 +160,7 @@ export type SessionCommand =readonly kind: "send";readonly payload: DeliverPayload;readonly requestId?: string;+ readonly turnPolicy?: TurnPolicy;}| { readonly kind: "cancel"; readonly turnId?: string }| { readonly kind: "compact" }@@ -208,6 +215,7 @@ export interface DeliverHookPayload {readonly requestId?: string;readonly kind: "deliver";readonly payloads: readonly DeliverPayload[];+ readonly turnPolicy?: TurnPolicy;}/** Internal deadline signal sent through the stable session command inbox. */diff --git a/packages/eve/src/cli/dev/tui/runner.test.ts b/packages/eve/src/cli/dev/tui/runner.test.tsindex 68b8d22c2..6e3ebe636 100644--- a/packages/eve/src/cli/dev/tui/runner.test.ts+++ b/packages/eve/src/cli/dev/tui/runner.test.ts@@ -1104,6 +1104,7 @@ describe("EveTUIRunner initial input", () => {expect(session.send).toHaveBeenCalledTimes(1);expect(session.send).toHaveBeenNthCalledWith(1, "edited and sent", {signal: expect.any(AbortSignal),+ turnPolicy: "queue",});});});@@ -1169,6 +1170,7 @@ describe("EveTUIRunner native continuation state", () => {expect(session.send).toHaveBeenCalledTimes(1);expect(session.send).toHaveBeenNthCalledWith(1, "approve this", {signal: expect.any(AbortSignal),+ turnPolicy: "queue",});expect(session.respond).toHaveBeenCalledWith([{ requestId: "request-1", optionId: "approve" }],@@ -3090,7 +3092,11 @@ describe("EveTUIRunner mid-turn message queue", () => {expect(session.send).toHaveBeenCalledTimes(2);expect(session.send).toHaveBeenNthCalledWith(1, "hello", expect.any(Object));- expect(session.send).toHaveBeenNthCalledWith(2, "queued follow-up", expect.any(Object));+ expect(session.send).toHaveBeenNthCalledWith(+ 2,+ "queued follow-up",+ expect.objectContaining({ turnPolicy: "queue" }),+ );// The drained prompt bypasses the interactive prompt read entirely.expect(renderer.readPrompt).toHaveBeenCalledTimes(2);});diff --git a/packages/eve/src/cli/dev/tui/runner.ts b/packages/eve/src/cli/dev/tui/runner.tsindex 2bfed24bd..2d9860140 100644--- a/packages/eve/src/cli/dev/tui/runner.ts+++ b/packages/eve/src/cli/dev/tui/runner.ts@@ -1263,7 +1263,10 @@ export class EveTUIRunner {} else {response =sendInput.inputResponses === undefined- ? await this.#session.send(sendInput.message!, { signal: sendInput.signal })+ ? await this.#session.send(sendInput.message!, {+ signal: sendInput.signal,+ turnPolicy: "queue",+ }): await this.#session.respond(sendInput.inputResponses, { signal: sendInput.signal });}} catch (error) {diff --git a/packages/eve/src/client/session.test.ts b/packages/eve/src/client/session.test.tsindex c0818ca50..979fcce1d 100644--- a/packages/eve/src/client/session.test.ts+++ b/packages/eve/src/client/session.test.ts@@ -409,6 +409,19 @@ describe("ClientSession", () => {});});+ it("serializes turnPolicy with a fixed-session message", async () => {+ const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(createAcceptedResponse());+ const session = createSession();++ await session.send("Wait your turn", { turnPolicy: "queue" });++ const init = fetchMock.mock.calls[0]?.[1] as RequestInit;+ expect(JSON.parse(String(init.body))).toEqual({+ message: "Wait your turn",+ turnPolicy: "queue",+ });+ });+it("serializes clientContext when continuing a session", async () => {const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(createAcceptedResponse());const session = createSession({diff --git a/packages/eve/src/client/session.ts b/packages/eve/src/client/session.tsindex e1f80317c..704c8ebaf 100644--- a/packages/eve/src/client/session.ts+++ b/packages/eve/src/client/session.ts@@ -292,6 +292,9 @@ function createMessageBody(if (input.inputResponses !== undefined && input.inputResponses.length > 0) {body.inputResponses = input.inputResponses;}+ if (!requireMessage && input.message !== undefined && input.turnPolicy !== undefined) {+ body.turnPolicy = input.turnPolicy;+ }if (input.clientContext !== undefined) body.clientContext = input.clientContext;const outputSchema = serializeOutputSchema(input.outputSchema);if (outputSchema !== undefined) body.outputSchema = outputSchema;diff --git a/packages/eve/src/client/types.ts b/packages/eve/src/client/types.tsindex 6167083fe..8de10cf37 100644--- a/packages/eve/src/client/types.ts+++ b/packages/eve/src/client/types.ts@@ -6,6 +6,7 @@ import type { CancelTurnResult } from "#protocol/cancel-turn.js";import type { ClearStatus } from "#protocol/clear-session.js";import type { CompactStatus } from "#protocol/compact-session.js";import type { ResetStatus } from "#protocol/reset-session.js";+import type { TurnPolicy } from "#channel/types.js";import type { InputRequest, InputResponse } from "#runtime/input/types.js";import type { JsonObject } from "#shared/json.js";@@ -108,6 +109,9 @@ export interface SendTurnInput<TOutput = unknown> extends SendTurnOptions<TOutpu/** Options shared by message sends and HITL responses on a client session. */export interface SendTurnOptions<TOutput = unknown> {+ /** Policy for a message sent while the fixed session has an active turn. */+ readonly turnPolicy?: TurnPolicy;+/*** Ephemeral client/page context for the next model call only.*diff --git a/packages/eve/src/evals/runner/execute-task.test.ts b/packages/eve/src/evals/runner/execute-task.test.tsindex 56b58bb5d..964cb024e 100644--- a/packages/eve/src/evals/runner/execute-task.test.ts+++ b/packages/eve/src/evals/runner/execute-task.test.ts@@ -426,6 +426,7 @@ describe("executeTask", () => {expect(server.cancels).toEqual(["parent-session"]);expect(server.posts[1]?.body).toEqual({message: "continue child",+ turnPolicy: "queue",});expect(outcome.result.sessions?.map((session) => session.sessionId)).toEqual(["parent-session",@@ -548,6 +549,7 @@ describe("executeTask", () => {expect(new URL(server.posts[0]!.url).pathname).toBe("/eve/v1/session/channel-session");expect(server.posts[0]?.body).toEqual({message: "continue please",+ turnPolicy: "queue",});expect(outcome.assertions.every((assertion) => assertion.passed)).toBe(true);});diff --git a/packages/eve/src/evals/session.ts b/packages/eve/src/evals/session.tsindex d368dcc42..199405811 100644--- a/packages/eve/src/evals/session.ts+++ b/packages/eve/src/evals/session.ts@@ -170,11 +170,11 @@ export class EvalSessionDriver implements EveEvalSession {message: SendTurnInput["message"],options: SendTurnOptions = {},): Promise<EveEvalTurn> {- return await (await this.#start({ ...options, message })).result();+ return await (await this.#start({ turnPolicy: "queue", ...options, message })).result();}async start(message: string, options: SendTurnOptions = {}): Promise<EveEvalLiveTurn> {- return await this.#start({ ...options, message });+ return await this.#start({ turnPolicy: "queue", ...options, message });}async #start(input: SendTurnPayload): Promise<EveEvalLiveTurn> {diff --git a/packages/eve/src/execution/session-command-wire.test.ts b/packages/eve/src/execution/session-command-wire.test.tsindex 1acb3b08d..a2cff61b2 100644--- a/packages/eve/src/execution/session-command-wire.test.ts+++ b/packages/eve/src/execution/session-command-wire.test.ts@@ -17,6 +17,7 @@ describe("sendCommandToDelivery", () => {kind: "send",payload,requestId: "req-1",+ turnPolicy: "steer",});expect(wire).toEqual({@@ -26,6 +27,7 @@ describe("sendCommandToDelivery", () => {payload,payloads: [payload],requestId: "req-1",+ turnPolicy: "steer",});// The 0.30.3–0.30.8 parked decode reads `.payload`; everything else reads// `payloads`. Both views must reference the same delivery.diff --git a/packages/eve/src/execution/session-command-wire.ts b/packages/eve/src/execution/session-command-wire.tsindex 5198e7539..813f0dd23 100644--- a/packages/eve/src/execution/session-command-wire.ts+++ b/packages/eve/src/execution/session-command-wire.ts@@ -31,5 +31,6 @@ export function sendCommandToDelivery(payload: command.payload,payloads: [command.payload],requestId: command.requestId,+ turnPolicy: command.turnPolicy,};}diff --git a/packages/eve/src/execution/turn-cancellation.integration.test.ts b/packages/eve/src/execution/turn-cancellation.integration.test.tsindex e6bd10379..a6013cf30 100644--- a/packages/eve/src/execution/turn-cancellation.integration.test.ts+++ b/packages/eve/src/execution/turn-cancellation.integration.test.ts@@ -265,6 +265,70 @@ async function expectCancelResponse(}describe("turn cancellation integration", () => {+ it("buffers a default steering message before replacing the active turn", async () => {+ const fixture = createWaitToolRuntime("turn-steer-message");+ const rawToken = "turn-steer-message";+ const continuationToken = `http:${rawToken}`;+ const workflowRuntime = createWorkflowRuntime({+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),+ });+ const address = createChannelAddress({+ adapter: { kind: "http" },+ channelName: "http",+ continuationToken: rawToken,+ runtime: workflowRuntime,+ });++ await fixture.runtime.run(async () => {+ const run = await start(workflowEntry, [+ {+ input: { message: `Use the ${WAIT_TOOL_NAME} tool.` },+ serializedContext: buildSerializedContext({+ channelKind: "http",+ continuationToken,+ mode: "conversation",+ }),+ },+ ]);+ const stream = captureTurnEvents(run);++ try {+ await waitForHookByToken(continuationToken);+ await fixture.toolStarted;++ await expect(+ address.send("replacement after steer", { auth: null }),+ ).resolves.toMatchObject({ id: run.runId });++ const cancelledTurn = await stream.nextTurn();+ expect(+ containsEventSequence(cancelledTurn, [+ "turn.started",+ "turn.cancelled",+ "session.waiting",+ ]),+ ).toBe(true);+ expect(fixture.toolAborts()).toBe(1);++ const replacementTurn = await stream.nextTurn();+ expect(filterEventsByType(replacementTurn, "turn.started")).toHaveLength(1);+ expect(filterEventsByType(replacementTurn, "turn.cancelled")).toHaveLength(0);+ expectNoFailureEvents(replacementTurn);+ expect(+ replacementTurn.some(+ (event) =>+ event.type === "message.received" &&+ typeof event.data.message === "string" &&+ event.data.message.includes("replacement after steer"),+ ),+ ).toBe(true);+ } finally {+ stream.dispose();+ await run.cancel();+ }+ });+ }, 60_000);+it("cancels a turn mid-tool and accepts the next message normally", async () => {const fixture = createWaitToolRuntime("turn-cancel-tool");const continuationToken = "http:turn-cancel-tool";diff --git a/packages/eve/src/execution/turn-control-receiver.test.ts b/packages/eve/src/execution/turn-control-receiver.test.tsindex 928b85676..cd1548fce 100644--- a/packages/eve/src/execution/turn-control-receiver.test.ts+++ b/packages/eve/src/execution/turn-control-receiver.test.ts@@ -29,7 +29,10 @@ describe("TurnControlReceiver", () => {});it("forwards a buffered delivery and consumes it once the turn accepts", async () => {- const delivery: DeliverHookPayload = { kind: "deliver", payloads: [{ message: "hello" }] };+ const delivery: DeliverHookPayload = {+ kind: "deliver",+ payloads: [{ inputResponses: [{ optionId: "yes", requestId: "input-1" }] }],+ };installControlHook([deliveryRequest("req-1"),{ kind: "turn-delivery-accepted", requestId: "req-1" },@@ -48,7 +51,10 @@ describe("TurnControlReceiver", () => {});it("re-buffers the outstanding delivery when the turn cancels its request", async () => {- const delivery: DeliverHookPayload = { kind: "deliver", payloads: [{ message: "hello" }] };+ const delivery: DeliverHookPayload = {+ kind: "deliver",+ payloads: [{ inputResponses: [{ optionId: "yes", requestId: "input-1" }] }],+ };installControlHook([deliveryRequest("req-1"),{ kind: "turn-delivery-cancelled", requestId: "req-1" },@@ -66,7 +72,7 @@ describe("TurnControlReceiver", () => {it("keeps earlier remainders ahead of an unresolved delivery when the turn terminates", async () => {const outstanding: DeliverHookPayload = {kind: "deliver",- payloads: [{ message: "outstanding" }],+ payloads: [{ inputResponses: [{ optionId: "yes", requestId: "input-1" }] }],};const earlierRemainder: DeliverHookPayload = {kind: "deliver",@@ -133,12 +139,59 @@ describe("TurnControlReceiver", () => {payload: { message: "follow up" },payloads: [{ message: "follow up" }],requestId: undefined,+ turnPolicy: undefined,},{ kind: "deliver", payloads: [{ message: "legacy follow up" }] },]);expect(bufferedSessionControls).toEqual(["clear", "compact", "expired"]);});+ it("buffers a steering message before cancelling the active turn", async () => {+ installControlHook([parkResult()], true);+ const bufferedDeliveries: DeliverHookPayload[] = [];+ vi.mocked(forwardTurnCancellationStep).mockImplementation(async () => {+ expect(bufferedDeliveries).toEqual([+ expect.objectContaining({+ payloads: [{ message: "replace this turn" }],+ turnPolicy: "steer",+ }),+ ]);+ return true;+ });++ await runReceiver(bufferedDeliveries, {+ commandInbox: createCommandInbox([+ {+ kind: "send",+ payload: { message: "replace this turn" },+ turnPolicy: "steer",+ },+ ]),+ });++ expect(forwardTurnCancellationStep).toHaveBeenCalledWith({+ payload: {},+ token: "turn-control:cancel",+ });+ });++ it("does not cancel for queued messages or input responses", async () => {+ installControlHook([parkResult()], true);++ await runReceiver([], {+ commandInbox: createCommandInbox([+ { kind: "send", payload: { message: "later" }, turnPolicy: "queue" },+ {+ kind: "send",+ payload: { inputResponses: [{ optionId: "yes", requestId: "input-1" }] },+ turnPolicy: "steer",+ },+ ]),+ });++ expect(forwardTurnCancellationStep).not.toHaveBeenCalled();+ });+it("forwards cancel and reset through the active turn's private hook", async () => {installControlHook([parkResult()], true);const bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset"> = [];diff --git a/packages/eve/src/execution/turn-control-receiver.ts b/packages/eve/src/execution/turn-control-receiver.tsindex ce96d52bc..6c1f90569 100644--- a/packages/eve/src/execution/turn-control-receiver.ts+++ b/packages/eve/src/execution/turn-control-receiver.ts@@ -73,11 +73,11 @@ export class TurnControlReceiver {command: SessionInboxPayload,): Promise<TurnDriverAction | undefined> {if (command.kind === "deliver") {- this.bufferedDeliveries.push(command);+ await this.bufferDelivery(command);return undefined;}if (command.kind === "send") {- this.bufferedDeliveries.push(sendCommandToDelivery(command));+ await this.bufferDelivery(sendCommandToDelivery(command));return undefined;}if (command.kind === "clear" || command.kind === "compact") {@@ -106,6 +106,16 @@ export class TurnControlReceiver {return unsupportedSessionCommand(command);}+ private async bufferDelivery(delivery: DeliverHookPayload): Promise<void> {+ this.bufferedDeliveries.push(delivery);+ if (delivery.turnPolicy !== "steer" || !deliveryHasMessage(delivery)) return;++ await forwardTurnCancellationStep({+ payload: {},+ token: turnCancellationHookToken(this.control.token),+ });+ }+private bufferTurnDeliveries(payload: Extract<TurnControlPayload, { readonly kind: "turn-result" }>,): void {@@ -165,7 +175,7 @@ export class TurnControlReceiver {): Promise<TurnDriverAction | undefined> {await this.commandInbox.rekeyContinuation(request.continuationToken);- let delivery = this.bufferedDeliveries.shift();+ let delivery = this.takeInputResponseDelivery();while (delivery === undefined) {const winner = await Promise.race([this.getControlPromise().then((value) => ({ kind: "control" as const, value })),@@ -197,12 +207,16 @@ export class TurnControlReceiver {}this.commandInbox.consumeNext();- if (winner.value.value.kind === "deliver") {- delivery = winner.value.value;- continue;- }- if (winner.value.value.kind === "send") {- delivery = sendCommandToDelivery(winner.value.value);+ if (winner.value.value.kind === "deliver" || winner.value.value.kind === "send") {+ const candidate =+ winner.value.value.kind === "deliver"+ ? winner.value.value+ : sendCommandToDelivery(winner.value.value);+ if (deliveryHasMessage(candidate)) {+ await this.bufferDelivery(candidate);+ } else {+ delivery = candidate;+ }continue;}const terminal = await this.handleSessionCommand(winner.value.value);@@ -228,6 +242,12 @@ export class TurnControlReceiver {return await this.awaitForwardedDelivery(request.requestId, delivery);}+ private takeInputResponseDelivery(): DeliverHookPayload | undefined {+ const index = this.bufferedDeliveries.findIndex((delivery) => !deliveryHasMessage(delivery));+ if (index === -1) return undefined;+ return this.bufferedDeliveries.splice(index, 1)[0];+ }+/*** Waits for the active turn to resolve a forwarded delivery. The turn either* accepts it (consumed) or releases it on cancellation or termination, in@@ -270,6 +290,10 @@ export class TurnControlReceiver {}}+function deliveryHasMessage(delivery: DeliverHookPayload): boolean {+ return delivery.payloads.some((payload) => payload.message !== undefined);+}+function unsupportedSessionCommand(command: never): never {throw new Error(`Unsupported session command: ${JSON.stringify(command)}`);}diff --git a/packages/eve/src/execution/turn-dispatch.test.ts b/packages/eve/src/execution/turn-dispatch.test.tsindex 214522ad0..52a69a2d6 100644--- a/packages/eve/src/execution/turn-dispatch.test.ts+++ b/packages/eve/src/execution/turn-dispatch.test.ts@@ -136,7 +136,10 @@ describe("dispatchAndAwaitTurn", () => {commandInbox: createCommandInbox({next: async () => ({done: false,- value: { kind: "send", payload: { message: "later delivery" } },+ value: {+ kind: "send",+ payload: { inputResponses: [{ optionId: "yes", requestId: "input-1" }] },+ },}),}),controlToken: "turn-control",@@ -147,15 +150,20 @@ describe("dispatchAndAwaitTurn", () => {sessionState: state,});- expect(bufferedDeliveries.map((item) => item.payloads[0]?.message)).toEqual([- "earlier remainder",- "later delivery",+ expect(bufferedDeliveries).toEqual([+ { kind: "deliver", payloads: [{ message: "earlier remainder" }] },+ expect.objectContaining({+ payloads: [{ inputResponses: [{ optionId: "yes", requestId: "input-1" }] }],+ }),]);});it("re-buffers a forwarded delivery when the turn inbox is already gone", async () => {const state = createState("http:test");- const delivery: DeliverHookPayload = { kind: "deliver", payloads: [{ message: "relayed" }] };+ const delivery: DeliverHookPayload = {+ kind: "deliver",+ payloads: [{ inputResponses: [{ optionId: "yes", requestId: "input-1" }] }],+ };vi.mocked(forwardTurnDeliveryStep).mockRejectedValue(Object.assign(new Error("inbox gone"), { name: "HookNotFoundError" }),);diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.tsindex d57957df0..616bf80af 100644--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.ts@@ -203,8 +203,12 @@ function buildRouteArgs(channelName,metadata: { requestId },runtime: bundle.runtime,+ turnPolicy: channel?.turnPolicy,+ });+ const attachSession = createAttachSessionFn(bundle.runtime, {+ requestId,+ turnPolicy: channel?.turnPolicy,});- const attachSession = createAttachSessionFn(bundle.runtime, { requestId });const to = createCrossChannelToFn(bundle.runtime, toCrossChannelTargets(bundle.channels));const args = attachRouteSessionCreator(diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.tsindex 95c18baab..061c6145e 100644--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts@@ -220,7 +220,7 @@ describe("chatSdkChannel", () => {});});- it("cancels the active turn before an experimental steering send", async () => {+ it("carries a steering send on the shared delivery", async () => {const bridge = chatSdkChannel({adapters: { test: testAdapter() },concurrency: "concurrent",@@ -232,7 +232,7 @@ describe("chatSdkChannel", () => {await bridge.send(message.text, {auth: AUTH,thread,- turnPolicy: "experimental-steer",+ turnPolicy: "steer",});});@@ -241,7 +241,7 @@ describe("chatSdkChannel", () => {});expect(response.status).toBe(200);- expect(cancel).toHaveBeenCalledWith({ continuationToken: THREAD_ID });+ expect(cancel).not.toHaveBeenCalled();expect(send).toHaveBeenCalledWith(THREAD_ID, {auth: AUTH,message: "@bot correction",@@ -251,11 +251,11 @@ describe("chatSdkChannel", () => {id: THREAD_ID,}),},+ turnPolicy: "steer",});- expect(cancel.mock.invocationCallOrder[0]).toBeLessThan(send.mock.invocationCallOrder[0]!);});- it("does not cancel for an experimental steering response without a message", async () => {+ it("does not cancel for a steering response without a message", async () => {const bridge = chatSdkChannel({adapters: { test: testAdapter() },concurrency: "concurrent",@@ -266,7 +266,7 @@ describe("chatSdkChannel", () => {bridge.bot.onNewMention(async (thread: Thread) => {await bridge.send({ inputResponses: [{ optionId: "approve", requestId: "request-1" }] },- { thread, turnPolicy: "experimental-steer" },+ { thread, turnPolicy: "steer" },);});diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.tsindex a93f001bc..19d1ae0a8 100644--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts@@ -8,7 +8,7 @@ import {} from "#channel/channel-operations.js";import { normalizeSendInput } from "#channel/send-input.js";import type { SendPayload } from "#channel/routes.js";-import type { SessionAuthContext } from "#channel/types.js";+import type { SessionAuthContext, TurnPolicy } 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";@@ -142,11 +142,9 @@ export interface ChatSdkSendOptions {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.+ * thread. Defaults to `"steer"`.*/- readonly turnPolicy?: "queue" | "experimental-steer";+ readonly turnPolicy?: TurnPolicy;/*** 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@@ -175,6 +173,8 @@ export interface ChatSdkChannelConfig<* settings.*/readonly routes?: Partial<Record<Extract<keyof TAdapters, string>, string>>;+ /** Policy for accepted messages that arrive while a turn is active. */+ readonly turnPolicy?: TurnPolicy;/** Extra Chat SDK webhook options. eve owns `waitUntil`. */readonly webhook?: Omit<WebhookOptions, "waitUntil">;/** Optional eve event handlers. Supplied handlers replace built-in defaults. */@@ -286,6 +286,7 @@ export function chatSdkChannel<TAdapters extends ChatSdkAdapters>(ChatSdkInstrumentationMetadata>({kindHint: "chat-sdk",+ turnPolicy: config.turnPolicy,state: initialState(),metadata: metadataFromState,context(state) {@@ -565,17 +566,11 @@ async function bridgeSend<TAdapters extends ChatSdkAdapters>(if (options.callback !== undefined) deliveryOptions.callback = options.callback;if (options.mode !== undefined) deliveryOptions.mode = options.mode;if (options.title !== undefined) deliveryOptions.title = options.title;+ if (options.turnPolicy !== undefined) deliveryOptions.turnPolicy = options.turnPolicy;const source = active.from(thread.id) as InternalChannelSource<ChatSdkChannelState>;- if (options.turnPolicy === "experimental-steer" && hasMessageInput(input)) {- await source.cancel();- }return source[INTERNAL_CHANNEL_DELIVER](payload, deliveryOptions);}-function hasMessageInput(input: ChatSdkSendInput): boolean {- return typeof input === "string" || Array.isArray(input) || input.message !== undefined;-}-function initialState(): ChatSdkChannelState {return { thread: null };}diff --git a/packages/eve/src/public/channels/discord/discordChannel.ts b/packages/eve/src/public/channels/discord/discordChannel.tsindex 62cb98485..d99dbc4d1 100644--- a/packages/eve/src/public/channels/discord/discordChannel.ts+++ b/packages/eve/src/public/channels/discord/discordChannel.ts@@ -1,7 +1,7 @@import type { DiscordInstrumentationMetadata } from "#public/channels/discord/index.js";import type { ChannelFrom } from "#channel/channel-operations.js";import type { SessionHandle } from "#channel/session.js";-import type { SessionAuthContext } from "#channel/types.js";+import type { SessionAuthContext, TurnPolicy } from "#channel/types.js";import type { SessionContext } from "#public/definitions/callback-context.js";import type { ChannelContinuationOps } from "#public/definitions/channel.js";@@ -151,6 +151,8 @@ export interface DiscordChannelConfig {readonly credentials?: DiscordChannelCredentials;/** Override the default interaction route path (`/eve/v1/discord`). */readonly route?: string;+ /** Policy for accepted messages that arrive while a turn is active. */+ readonly turnPolicy?: TurnPolicy;/** Inbound command hook. Defaults to user-scoped Discord auth and dispatch. Return `{ auth }` to dispatch, or `null` to acknowledge without running the agent. */onCommand?(@@ -219,6 +221,7 @@ export function discordChannel(config: DiscordChannelConfig = {}): DiscordChanneDiscordInstrumentationMetadata>({kindHint: "discord",+ turnPolicy: config.turnPolicy,state: initialDiscordState(),metadata: (state) => ({ channelId: state.channelId, guildId: state.guildId }),diff --git a/packages/eve/src/public/channels/eve.test.ts b/packages/eve/src/public/channels/eve.test.tsindex 8b335d8ce..18ff6ca23 100644--- a/packages/eve/src/public/channels/eve.test.ts+++ b/packages/eve/src/public/channels/eve.test.ts@@ -1419,6 +1419,20 @@ describe("eveChannel — continue session HITL (inputResponses)", () => {);});+ it("forwards turnPolicy with a continue-session message", async () => {+ const handler = createEveContinueHandler({ auth: none() });++ const response = await handler.fetch(+ createJsonMessageRequest({ message: "Wait your turn", turnPolicy: "queue" }),+ );++ expect(response.status).toBe(202);+ expect(handler.send).toHaveBeenCalledWith(+ "Wait your turn",+ expect.objectContaining({ turnPolicy: "queue" }),+ );+ });+it("rejects invalid continue-session clientContext", async () => {const handler = createEveContinueHandler({ auth: none() });diff --git a/packages/eve/src/public/channels/eve.ts b/packages/eve/src/public/channels/eve.tsindex 72d053bac..2a90d3626 100644--- a/packages/eve/src/public/channels/eve.ts+++ b/packages/eve/src/public/channels/eve.ts@@ -1,6 +1,11 @@import { type FilePart, type TextPart, type UserContent } from "ai";-import type { SessionAuthContext, SessionCallback, SessionCapabilities } from "#channel/types.js";+import type {+ SessionAuthContext,+ SessionCallback,+ SessionCapabilities,+ TurnPolicy,+} from "#channel/types.js";import type { CancelTurnResponse } from "#protocol/cancel-turn.js";import type { ClearResponse } from "#protocol/clear-session.js";import type { CompactResponse } from "#protocol/compact-session.js";@@ -168,6 +173,8 @@ export interface EveChannelInput {* object to narrow the policy.*/readonly cors?: EveChannelCors;+ /** Policy for follow-up messages that arrive while a turn is active. */+ readonly turnPolicy?: TurnPolicy;/*** Pre-dispatch hook for inbound eve HTTP messages. Runs after route auth and body* parsing, before runtime dispatch.@@ -204,6 +211,7 @@ export function eveChannel(input: EveChannelInput): EveChannel {return defineChannel<undefined, EveEventContext>({cors: normalizeEveCors(input.cors),+ turnPolicy: input.turnPolicy,routes: [GET(EVE_INFO_ROUTE_PATH, async (req, args) => {const authResult = await routeAuth(req, input.auth);@@ -329,6 +337,7 @@ export function eveChannel(input: EveChannelInput): EveChannel {callback: body.callback,context,outputSchema: body.outputSchema,+ turnPolicy: body.turnPolicy,};result =body.inputResponses === undefined@@ -653,6 +662,7 @@ interface ParsedSessionMessageBody {inputResponses?: readonly InputResponse[];context?: readonly string[];outputSchema?: JsonObject;+ turnPolicy?: TurnPolicy;}function parseSessionMessageBody(@@ -677,6 +687,8 @@ function parseSessionMessageBody(if (context instanceof Response) return context;const outputSchema = parseOutputSchemaField(payload.outputSchema);if (outputSchema instanceof Response) return outputSchema;+ const turnPolicy = parseTurnPolicyField(payload.turnPolicy);+ if (turnPolicy instanceof Response) return turnPolicy;if (message === undefined && inputResponses === undefined) {return Response.json(@@ -695,7 +707,7 @@ function parseSessionMessageBody();}- return { callback, message, inputResponses, context, outputSchema };+ return { callback, message, inputResponses, context, outputSchema, turnPolicy };}interface ParsedCancelTurnBody {@@ -871,6 +883,15 @@ function parseModeField(value: unknown): RunMode | Response | undefined {);}+function parseTurnPolicyField(value: unknown): TurnPolicy | Response | undefined {+ if (value === undefined) return undefined;+ if (value === "queue" || value === "steer") return value;+ return Response.json(+ { error: "Expected 'turnPolicy' to be either 'queue' or 'steer'.", ok: false },+ { status: 400 },+ );+}+function parseMessageField(value: unknown): string | UserContent | undefined | Response {if (value === undefined) return undefined;if (typeof value === "string") return value.length > 0 ? value : undefined;diff --git a/packages/eve/src/public/channels/github/githubChannel.ts b/packages/eve/src/public/channels/github/githubChannel.tsindex 1f8f706b0..9472f5dac 100644--- a/packages/eve/src/public/channels/github/githubChannel.ts+++ b/packages/eve/src/public/channels/github/githubChannel.ts@@ -1,5 +1,5 @@import type { SessionHandle } from "#channel/session.js";-import type { SessionAuthContext } from "#channel/types.js";+import type { SessionAuthContext, TurnPolicy } from "#channel/types.js";import type { SessionContext } from "#public/definitions/callback-context.js";import type { ChannelContinuationOps } from "#public/definitions/channel.js";@@ -158,6 +158,8 @@ export interface GitHubChannelConfig {readonly progress?: GitHubProgressConfig;readonly pullRequestContext?: GitHubPullRequestContextConfig;readonly route?: string;+ /** Policy for accepted messages that arrive while a turn is active. */+ readonly turnPolicy?: TurnPolicy;/*** Invoked for every `@mention` of the bot in an issue/PR timeline comment or@@ -231,6 +233,7 @@ export function githubChannel(config: GitHubChannelConfig = {}): GitHubChannel {const channel = defineChannel<GitHubChannelState, GitHubChannelContext, GitHubReceiveTarget>({kindHint: "github",+ turnPolicy: config.turnPolicy,state: initialGitHubState(),context(state, session) {diff --git a/packages/eve/src/public/channels/index.ts b/packages/eve/src/public/channels/index.tsindex f1cd65306..9be512ab1 100644--- a/packages/eve/src/public/channels/index.ts+++ b/packages/eve/src/public/channels/index.ts@@ -29,6 +29,7 @@ export {type SessionHandle,type SessionRespondOptions,type SessionSendOptions,+ type TurnPolicy,type RouteDefinition,type RouteHandlerArgs,type HttpRouteDefinition,diff --git a/packages/eve/src/public/channels/linear/linearChannel.ts b/packages/eve/src/public/channels/linear/linearChannel.tsindex 22bd075e0..6a98a3d2d 100644--- a/packages/eve/src/public/channels/linear/linearChannel.ts+++ b/packages/eve/src/public/channels/linear/linearChannel.ts@@ -1,5 +1,5 @@import type { SessionHandle } from "#channel/session.js";-import type { SessionAuthContext } from "#channel/types.js";+import type { SessionAuthContext, TurnPolicy } from "#channel/types.js";import type { ChannelFrom } from "#channel/channel-operations.js";import { createLogger } from "#internal/logging.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";@@ -175,6 +175,8 @@ export interface LinearChannelConfig {/** Max allowed webhook timestamp skew in milliseconds. Defaults to 60 seconds. */readonly maxSkewMs?: number;readonly route?: string;+ /** Policy for accepted messages that arrive while a turn is active. */+ readonly turnPolicy?: TurnPolicy;/** Inbound Agent Session hook. Defaults to dispatching `created` and `prompted` events. */onAgentSession?(@@ -208,6 +210,7 @@ export function linearChannel(config: LinearChannelConfig = {}): LinearChannel {LinearInstrumentationMetadata>({kindHint: "linear",+ turnPolicy: config.turnPolicy,state: initialLinearState(),metadata(state): LinearInstrumentationMetadata {return {diff --git a/packages/eve/src/public/channels/photon/photonIMessageChannel.test.ts b/packages/eve/src/public/channels/photon/photonIMessageChannel.test.tsindex 95b73a637..4c11fea42 100644--- a/packages/eve/src/public/channels/photon/photonIMessageChannel.test.ts+++ b/packages/eve/src/public/channels/photon/photonIMessageChannel.test.ts@@ -34,7 +34,7 @@ describe("photonIMessageChannel", () => {vi.clearAllMocks();});- it("cancels the active eve turn before steering a direct message into its thread", async () => {+ it("inherits the shared steering default for a direct message", async () => {photonIMessageChannel({credentials: async () => ({ projectId: "project-id", projectSecret: "project-secret" }),});@@ -53,7 +53,7 @@ describe("photonIMessageChannel", () => {expect(send).toHaveBeenCalledWith({ context: [], message: "Steer this response" },- { auth: null, thread, turnPolicy: "experimental-steer" },+ { auth: null, thread },);});@@ -99,7 +99,7 @@ describe("photonIMessageChannel", () => {expect(send).toHaveBeenCalledWith({ context: [], message: "Hello group" },- { auth: null, thread, turnPolicy: "experimental-steer" },+ { auth: null, thread },);});});diff --git a/packages/eve/src/public/channels/photon/photonIMessageChannel.ts b/packages/eve/src/public/channels/photon/photonIMessageChannel.tsindex f3f93c3c8..3376b719e 100644--- a/packages/eve/src/public/channels/photon/photonIMessageChannel.ts+++ b/packages/eve/src/public/channels/photon/photonIMessageChannel.ts@@ -1,4 +1,4 @@-import type { SessionAuthContext } from "#channel/types.js";+import type { SessionAuthContext, TurnPolicy } from "#channel/types.js";import { vercelOidc } from "#public/channels/auth.js";import {chatSdkChannel,@@ -47,6 +47,8 @@ export interface PhotonIMessageChannelConfig {) => PhotonInboundResultOrPromise;/** Override the default webhook route (`/eve/v1/photon`). */readonly route?: string;+ /** Policy for accepted messages that arrive while a turn is active. */+ readonly turnPolicy?: TurnPolicy;/** Display name used by the Chat SDK runtime. Defaults to `"eve"`. */readonly userName?: string;/** Photon webhook signing secret. Falls back to `IMESSAGE_WEBHOOK_SECRET`. */@@ -88,6 +90,7 @@ export function photonIMessageChannel(config: PhotonIMessageChannelConfig): Photroutes: { imessage: config.route ?? "/eve/v1/photon" },state: createMemoryState(),streaming: false,+ turnPolicy: config.turnPolicy,userName: config.userName ?? "eve",});const onMessage = config.onMessage ?? defaultOnMessage;@@ -122,7 +125,7 @@ async function dispatchMessage(context: [...(result.context ?? [])],message: content,},- { auth: result.auth, thread, turnPolicy: "experimental-steer" },+ { auth: result.auth, thread },);}diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.tsindex fb6b1bf09..2682f4df8 100644--- a/packages/eve/src/public/channels/slack/slackChannel.ts+++ b/packages/eve/src/public/channels/slack/slackChannel.ts@@ -7,7 +7,7 @@ import type {ChannelSource,} from "#channel/channel-operations.js";import type { Session, SessionHandle } from "#channel/session.js";-import type { SessionAuthContext } from "#channel/types.js";+import type { SessionAuthContext, TurnPolicy } from "#channel/types.js";import type { CardElement } from "#compiled/chat/index.js";import type { SessionContext } from "#public/definitions/callback-context.js";import type { ChannelContinuationOps } from "#public/definitions/channel.js";@@ -483,6 +483,8 @@ export interface SlackChannelConfig {/** Override the default webhook route path (`/eve/v1/slack`). */readonly route?: string;+ /** Policy for accepted messages that arrive while a turn is active. */+ readonly turnPolicy?: TurnPolicy;/*** Inbound upload policy applied to file attachments before they reach@@ -667,6 +669,7 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {SlackInstrumentationMetadata>({kindHint: "slack",+ turnPolicy: config.turnPolicy,state: {channelId: null as string | null,threadTs: null as string | null,diff --git a/packages/eve/src/public/channels/teams/teamsChannel.ts b/packages/eve/src/public/channels/teams/teamsChannel.tsindex fd41f2b17..6595d011b 100644--- a/packages/eve/src/public/channels/teams/teamsChannel.ts+++ b/packages/eve/src/public/channels/teams/teamsChannel.ts@@ -1,7 +1,7 @@import type { TeamsInstrumentationMetadata } from "#public/channels/teams/index.js";import type { ChannelFrom, ChannelResolveSession } from "#channel/channel-operations.js";import type { SessionHandle } from "#channel/session.js";-import type { SessionAuthContext } from "#channel/types.js";+import type { SessionAuthContext, TurnPolicy } from "#channel/types.js";import type { SessionContext } from "#public/definitions/callback-context.js";import type { ChannelContinuationOps } from "#public/definitions/channel.js";@@ -195,6 +195,8 @@ export interface TeamsChannelConfig {readonly files?: TeamsFilesConfig;/** Override the default webhook route path (`/eve/v1/teams`). */readonly route?: string;+ /** Policy for accepted messages that arrive while a turn is active. */+ readonly turnPolicy?: TurnPolicy;/** Inbound message hook. Defaults to user-scoped auth and mention-gated dispatch outside personal chats. */onMessage?(@@ -283,6 +285,7 @@ export function teamsChannel(config: TeamsChannelConfig = {}): TeamsChannel {TeamsInstrumentationMetadata>({kindHint: "teams",+ turnPolicy: config.turnPolicy,state: initialTeamsState(),fetchFile: createTeamsFetchFile(filesPolicy),metadata: (state) => ({diff --git a/packages/eve/src/public/channels/telegram/telegramChannel.ts b/packages/eve/src/public/channels/telegram/telegramChannel.tsindex 7eb1c9774..632c130a5 100644--- a/packages/eve/src/public/channels/telegram/telegramChannel.ts+++ b/packages/eve/src/public/channels/telegram/telegramChannel.ts@@ -2,7 +2,7 @@ import type { TelegramInstrumentationMetadata } from "#public/channels/telegram/import { defaultDeliverResult, type ChannelAdapterContext } from "#channel/adapter.js";import type { ChannelFrom } from "#channel/channel-operations.js";import type { SessionHandle } from "#channel/session.js";-import type { DeliverPayload, SessionAuthContext } from "#channel/types.js";+import type { DeliverPayload, SessionAuthContext, TurnPolicy } from "#channel/types.js";import type { SessionContext } from "#public/definitions/callback-context.js";import type { ChannelContinuationOps } from "#public/definitions/channel.js";import { isCompiledChannel } from "#channel/compiled-channel.js";@@ -166,6 +166,8 @@ export interface TelegramChannelConfig {) => TelegramInboundResultOrPromise;/** Override the default webhook route path (`/eve/v1/telegram`). */readonly route?: string;+ /** Policy for accepted messages that arrive while a turn is active. */+ readonly turnPolicy?: TurnPolicy;/** Inbound upload policy for Telegram photos and documents. */readonly uploadPolicy?: UploadPolicyInput;}@@ -213,6 +215,7 @@ export function telegramChannel(config: TelegramChannelConfig = {}): TelegramChaTelegramInstrumentationMetadata>({kindHint: "telegram",+ turnPolicy: config.turnPolicy,state: initialTelegramState(config.botUsername),metadata: (state) => ({chatId: state.chatId,diff --git a/packages/eve/src/public/channels/twilio/twilioChannel.ts b/packages/eve/src/public/channels/twilio/twilioChannel.tsindex c21892ff7..050babe40 100644--- a/packages/eve/src/public/channels/twilio/twilioChannel.ts+++ b/packages/eve/src/public/channels/twilio/twilioChannel.ts@@ -1,5 +1,5 @@import type { SessionHandle } from "#channel/session.js";-import type { SessionAuthContext } from "#channel/types.js";+import type { SessionAuthContext, TurnPolicy } from "#channel/types.js";import type { RouteHandler } from "#channel/routes.js";import type { ChannelFrom } from "#channel/channel-operations.js";import type { SessionContext } from "#public/definitions/callback-context.js";@@ -210,6 +210,8 @@ export interface TwilioChannelConfig {* mounts `/messages`, `/voice`, and `/voice/transcription` below it.*/readonly route?: string;+ /** Policy for accepted messages that arrive while a turn is active. */+ readonly turnPolicy?: TurnPolicy;/*** Public URL Twilio used for signing. Set this when proxies or local* tunnels make `request.url` differ from the configured webhook URL.@@ -296,6 +298,7 @@ export function twilioChannel(config: TwilioChannelConfig): TwilioChannel {TwilioInstrumentationMetadata>({kindHint: "twilio",+ turnPolicy: config.turnPolicy,state: {from: null as string | null,to: null as string | null,diff --git a/packages/eve/src/public/definitions/channel.ts b/packages/eve/src/public/definitions/channel.tsindex cacb6e276..2e125798b 100644--- a/packages/eve/src/public/definitions/channel.ts+++ b/packages/eve/src/public/definitions/channel.ts@@ -17,7 +17,7 @@ import type {} from "#channel/channel-operations.js";import type { RouteDefinition } from "#channel/routes.js";import type { Session, SessionHandle } from "#channel/session.js";-import type { DeliverPayload } from "#channel/types.js";+import type { DeliverPayload, TurnPolicy } from "#channel/types.js";import { buildCallbackContext } from "#context/build-callback-context.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";import type { SessionContext } from "#public/definitions/callback-context.js";@@ -32,6 +32,7 @@ export type {GetEventStreamOptions,ResetSessionResult,SessionCallback,+ TurnPolicy,} from "#channel/types.js";export type { Session, SessionHandle } from "#channel/session.js";export type { SessionRespondOptions, SessionSendOptions } from "#channel/session.js";@@ -247,6 +248,7 @@ export interface Channel<input: ReceiveInput<TReceiveTarget>,ctx: ChannelReceiveContext<TState>,) => Promise<Session>;+ readonly turnPolicy?: TurnPolicy;}/**@@ -279,6 +281,7 @@ export function defineChannel<adapter,cors,receive: definition.receive,+ turnPolicy: definition.turnPolicy,};return compiled;diff --git a/packages/eve/src/runtime/framework-channels/index.ts b/packages/eve/src/runtime/framework-channels/index.tsindex 2a3531b52..f22c21f31 100644--- a/packages/eve/src/runtime/framework-channels/index.ts+++ b/packages/eve/src/runtime/framework-channels/index.ts@@ -36,6 +36,7 @@ export function getFrameworkChannelDefinitions(): readonly ResolvedChannelDefinifetch: async (req: Request, ctx: any) => route.handler(req, ctx),handler: route.handler,adapter: compiled.adapter,+ turnPolicy: compiled.turnPolicy,logicalPath: `framework://channels/${route.path}`,sourceId: `eve:framework:${route.method.toLowerCase()}-${route.path}`,sourceKind: "module",diff --git a/packages/eve/src/runtime/resolve-channel.ts b/packages/eve/src/runtime/resolve-channel.tsindex 358febf58..75aaef9c8 100644--- a/packages/eve/src/runtime/resolve-channel.ts+++ b/packages/eve/src/runtime/resolve-channel.ts@@ -84,6 +84,7 @@ export async function resolveChannelDefinition(receive: channelDefinition.receive,definition: channelDefinition,adapter,+ turnPolicy: channelDefinition.turnPolicy,...sourceRef,};} catch (error) {diff --git a/packages/eve/src/runtime/types.ts b/packages/eve/src/runtime/types.tsindex 3e58d8394..a7e141040 100644--- a/packages/eve/src/runtime/types.ts+++ b/packages/eve/src/runtime/types.ts@@ -228,6 +228,7 @@ export interface ResolvedChannelDefinition extends ResolvedModuleSourceRef {readonly name: string;readonly method: ChannelRouteMethod;readonly adapter?: ChannelAdapter;+ readonly turnPolicy?: CompiledChannel["turnPolicy"];readonly cors?: NormalizedChannelCorsOptions;readonly urlPath: string;readonly fetch: (req: Request, ctx: RouteContext) => Promise<Response>;diff --git a/packages/eve/src/shared/channel-definition.ts b/packages/eve/src/shared/channel-definition.tsindex 1ffa5cc7b..bb7e0448f 100644--- a/packages/eve/src/shared/channel-definition.ts+++ b/packages/eve/src/shared/channel-definition.ts@@ -3,7 +3,7 @@ import type { UserContent } from "ai";import type { ChannelReceiveContext } from "#channel/channel-operations.js";import type { RouteDefinition } from "#channel/routes.js";import type { Session, SessionHandle } from "#channel/session.js";-import type { SessionAuthContext } from "#channel/types.js";+import type { SessionAuthContext, TurnPolicy } from "#channel/types.js";/*** Enriched return shape from a channel's {@link ChannelAdapter.fetchFile}@@ -50,6 +50,8 @@ export interface GenericChannelDefinition<TReceiveTarget = Record<string, unknown>,TMetadata extends Record<string, unknown> = Record<string, unknown>,> {+ /** Policy used by message sends that do not provide an explicit override. */+ readonly turnPolicy?: TurnPolicy;readonly state?: TState;/*** CORS policy for this channel's HTTP routes. `true` enables H3/Nitro'sdiff --git a/research/channel-turn-steering.md b/research/channel-turn-steering.mddeleted file mode 100644index 072e4a2f2..000000000--- a/research/channel-turn-steering.md+++ /dev/null@@ -1,422 +0,0 @@-----issue: https://github.com/vercel/eve/issues/867-status: proposed-last_updated: "2026-07-16"------# Channel turn steering--## Summary--Chat-style channels often receive corrective or additional input while an-agent is still working. Waiting for the next turn can let the agent finish an-obsolete answer; hard-cancelling the turn throws away useful work and provides-no replacement input.--Expose one input policy to channel authors:--```ts-turnPolicy: "queue" | "steer";-```--`"queue"` is the existing default: hold input for the next turn. `"steer"`-asks eve to apply the input to the active logical turn at its next safe step-boundary. There is no public `"interrupt"` policy. Whether eve can stop an-obsolete provider or tool operation early is an implementation detail of-steering, not a distinct end-user intent.--Turn cancellation remains separate: it stops active work without replacement-input and emits `turn.cancelled`. Steering keeps the same turn alive and does-not emit a cancellation boundary.--## Public authoring API--### Custom channels--```ts-export type TurnPolicy = "queue" | "steer";--export interface SendOptions<TState> {- // Existing fields omitted.- turnPolicy?: TurnPolicy;-}-```--`TurnPolicy` is exported from `eve/channels`. `SendOptions.turnPolicy` is-optional and defaults to `"queue"`.--```ts-export default defineChannel({- routes: [- POST("/threads/:threadId/messages", async (request, { params, send }) => {- const body = await request.json();- const session = await send(body.text, {- auth: await authenticate(request),- continuationToken: params.threadId,- turnPolicy: "steer",- });-- return Response.json({ sessionId: session.id });- }),- ],-});-```--Use the default queue policy when every response should finish in order:--```ts-await send(message, {- auth,- continuationToken: threadId,-});-```--Use cancellation for a stop button with no replacement message:--```ts-await cancel({ continuationToken: threadId, turnId });-```--The continuation-addressed cancellation helper is specified separately in-[Turn cancellation for custom channel routes](./turn-cancellation-channel-ops.md).--### Other channel surfaces--- `ChatSdkSendOptions` exposes the same optional `turnPolicy` and passes it- unchanged through `bridge.send()`.-- Low-level `Agent.deliver()` and runtime `DeliverInput` expose the same policy- so authored filesystem routes do not need to recreate `send()`.-- Built-in channels continue to use `"queue"` unless their documented inbound- behavior explicitly opts into steering. Adding the API must not silently- change Slack, Teams, Telegram, Twilio, Discord, GitHub, or Linear behavior.-- `send()` continues to return `Session`. A successful return means the input- was durably admitted, not that a particular steering step has already run.- The event stream is the observable record of whether it joined the active or- next turn.--No new public steering event or result union is required.--## Observable semantics--### State matrix--| Session state | `queue` | `steer` |-| -------------------------------------------- | --------------------------------- | -------------------------------------------------------------------------- |-| No session owns the continuation token | Start a new turn. | Start a new turn; there is nothing to steer yet. |-| Session is parked and waiting for input | Start the next turn. | Start the next turn; it becomes ordinary input. |-| A steer-capable conversation turn is active | Preserve input for the next turn. | Apply input to the active turn at its next safe boundary. |-| Active pinned turn lacks steering capability | Preserve input for the next turn. | Degrade safely to queue; never drop, fail open, or start a second session. |-| Active turn settles before steering commits | Preserve input for the next turn. | Preserve it in original admission order as queue input for the next turn. |--This feature initially targets resumable conversation sessions. An active-task-mode session cannot promise a next-turn fallback, so `"steer"` must be-rejected with a typed unsupported-policy error until task successors have a-durable design. `send()` must propagate that error and must not interpret it as-permission to start a second session.--### Turn identity and events--Successfully applied steering remains inside the active turn:--- the turn retains its existing `turnId`;-- no second `turn.started` event is emitted;-- the replacement input emits `message.received` under that turn;-- later step, message, tool, and terminal events continue the normal sequence;-- the turn eventually completes, fails, cancels, or parks exactly once.--If the input falls back to the queue, it is observed under the next turn and-that turn emits its own `turn.started` normally.--### Safe boundary--A steering request does not rewrite an executing atomic step. eve applies it-after the current model/tool boundary has settled or has been cooperatively-stopped safely. The implementation may use a soft abort notification to stop-obsolete provider work sooner, but authors cannot depend on whether a specific-provider or tool call finishes or aborts.--The public guarantee is:--1. completed side effects are never rolled back;-2. a steering delivery is applied before the active turn is allowed to settle,- or it remains queued for a later turn;-3. it is never applied twice.--### Ordering--Every admitted delivery receives a durable sequence. Queue fallback preserves-that admission order.--Steering intentionally bypasses older queued input while an active turn can-accept it. For example, queued input A may remain for the next turn while a-later steering input B joins the current turn. If B cannot be applied and also-falls back to the queue, the next turn observes A before B.--Multiple steering deliveries are forwarded single-flight and applied in their-admission order. eve may coalesce adjacent steering deliveries at one safe-boundary as long as payload order and exactly-once behavior are preserved.-Internal acknowledgement timing must never change their fallback order.--### Delivery and continuation races--- Once `send()` resolves a continuation hook to a session, a concurrent- `setContinuationToken()` cannot make that delivery fall through to- `runtime.run()` or create another history.-- `send()` may start a session only after receiving the typed- no-active-session outcome. Hook conflicts, steering failures, unsupported- policy, serialization errors, and other runtime failures propagate.-- A terminal race has two valid outcomes: input is consumed by the active turn- or remains queued. There is no gap in which neither side owns it.-- Retry and replay are idempotent by delivery id. Duplicate hook or step- execution cannot duplicate model input.--### Input requests and descendants--Structured `inputResponses` retain their addressing semantics:--- a response naming an existing request routes to that request's owner;-- input queued before a later request cannot accidentally answer it;-- steering received while a request is open does not close the request unless- it contains the matching response;-- a delivery containing both addressed responses and parent-local content- routes the addressed parts first, then applies `turnPolicy` to the remainder;-- responses for delegated children continue through existing child routing;- any parent-local remainder retains the source delivery id and sequence.--Steering a parent does not cancel delegated children. Existing child results,-authorization state, and runtime-action reads remain pending. Replacement-input may resolve a child request or continue the parent according to the same-routing rules used for ordinary delivery.--### Adapter projection--`turnPolicy` is runtime routing metadata and is not part of the authored-adapter payload. The adapter still projects the delivery into a harness-`StepInput`.--Explicit steering cannot be silently swallowed because an adapter returns-`undefined`: eve falls back to the standard message/input-response projection-for that delivery. Structurally empty steering is normalized consistently with-new-session input. The harness marks the projected replacement input with its-existing internal `steering: true` marker so deferred input, compaction, and-history logic can distinguish it from an ordinary continuation.--Any future adapter contract that distinguishes “no custom projection” from-“handled without model input” should be designed separately. It is not an-additional `turnPolicy` value.--### Cancellation and side effects--Steering and cancellation are independent operations:--| Operation | Replacement input | Turn identity | Terminal boundary |-| --------------------- | ----------------- | ------------- | --------------------------------------- |-| `turnPolicy: "queue"` | Next turn | New turn | Current turn settles normally |-| `turnPolicy: "steer"` | Active turn | Same turn | No cancellation event |-| `cancel(...)` | None | Ends turn | `turn.cancelled` then `session.waiting` |--If cancellation wins before a steering delivery is consumed, that delivery-remains queued for the next conversation turn. If the turn consumes the input-first and cancellation arrives afterward, the input belongs to the cancelled-turn and is not replayed automatically. Durable command ordering, not process-timing, determines which outcome occurred.--Partial model output already emitted remains on the stream. Completed tool,-channel, sandbox, and external effects remain completed. Steering and-cancellation are not rollback mechanisms.--## Clean-slate ownership model--The session driver must be the sole durable owner of admitted input. The active-turn receives a lease; ownership does not move merely because a private inbox-received the payload.--```text-public continuation hook- │- ▼-session driver admission ledger- id + sequence + payload + requested policy- │- ├── queue ─────────────────────────────► next turn- │- └── lease steering delivery by id- │- ▼- per-turn command inbox- │- ▼- active turn- │- └── consumed | released | remainder- │- ▼- update the original ledger entry-```--The ledger preserves position while an entry is leased:--- `consumed` removes the entry after the turn durably incorporates it into a- step or routes it to the addressed child;-- `released` leaves it in place and changes effective policy to `queue`;-- `remainder` replaces the entry payload while retaining its id and sequence;-- terminal settlement releases every unresolved lease before selecting the- next turn.--There are no “return to front/back” operations and no reconstruction with-`push()` or `unshift()`. The session driver is the only component that changes-effective policy from steering to queue.--The turn may expose one neutral, per-turn command inbox for input-bearing-commands such as steering and requested delivery. This does not mean steering-reuses the cancellation hook: hard cancellation and soft steering retain-different controllers, reasons, settlement behavior, and payload types. Share-low-level hook mechanics only where their replay and disposal rules are truly-identical.--### Step notification state--The active step needs to distinguish steering that was already pending when-the step began from steering that arrived while it was running:--```ts-interface TurnSteeringState {- readonly pending: boolean;- readonly signal?: AbortSignal;-}--interface TurnStepInput {- readonly steeringState?: TurnSteeringState;-}-```--`pending` prevents settlement before already-admitted replacement input is-applied. `signal.aborted` wakes settlement checks when input arrives during the-step. Keep `StepInput.steering?: true` as the separate harness marker meaning-“this concrete input is replacement input.” Naming the control object-`steeringState` avoids giving two adjacent layers incompatible fields named-`steering`.--Workflow serializes nested abort signals across step boundaries, but eve must-retain a focused live-signal integration test so an upstream serializer change-cannot silently turn the signal into a plain object.--### Single-flight and terminal authority--- At most one input-bearing lease is outstanding to a turn at a time. The- driver may continue admitting queue entries but does not forward another- command until the current lease has a disposition.-- Receipt is not consumption. The turn reports `consumed` only at the durable- boundary where the input is incorporated or routed.-- A stale disposition id cannot clear a current lease.-- The turn owns its normal result; the driver owns unresolved ledger entries.- A terminal result therefore carries dispositions or remainders, never an- untyped array to splice back into a buffer.-- Turn teardown disposes pending reads without awaiting iterator shutdown that- can remain suspended forever.--### Durable versions and rollout--Separate the durable driver-to-turn seed from runtime-only step input. Abort-signals and `steeringState` are constructed inside the pinned turn workflow;-they do not belong in the durable migration type unless they actually cross-the driver-to-turn wire.--Any change to the durable turn seed or control protocol must update its version-and migration tests. Rollout uses additive capability negotiation:--- a latest driver can identify a steer-capable turn before leasing steering;-- a pinned driver or turn that omits the capability safely treats steering as- queued input;-- no deployment combination interprets a new control payload as authored user- input.--## Implementation sequence--Land this through independently reviewable boundaries.--1. **Workflow spike:** prove one per-turn input command can arrive while- `turnStep` is active, drive the soft notification signal live, replay once,- and settle a terminal race without a late disposition.-2. **Admission ledger:** replace raw driver buffering with id/sequence entries- and lease/disposition operations while preserving existing queue and HITL- behavior. No public steering API yet.-3. **Internal steering:** add the private command, `steeringState`, adapter- projection rule, capability negotiation, and same-turn continuation tests.- Existing cancellation remains unchanged.-4. **Public API:** expose `TurnPolicy`, `SendOptions.turnPolicy`, low-level- delivery plumbing, Chat SDK propagation, custom-channel docs, and a patch- changeset.-5. **E2E:** exercise the feature from a custom channel using only public APIs,- then enable steering selectively in built-in channels only through separate- product decisions.--Each implementation PR must be independently reviewable and leave queue-only-behavior complete.--## Verification--### Public behavior--- default queue behavior is unchanged;-- steering keeps one `turnId`, one `turn.started`, and emits replacement- `message.received` before settlement;-- no-session, parked-session, pinned-old-turn, terminal-race, and task-mode- outcomes match the state matrix;-- cancellation remains a hard stop with no replacement input;-- built-in channels do not opt in accidentally.--### Ownership and ordering--- queue A followed by steering B yields A then B if B falls back, regardless- of whether the turn received B before terminating;-- multiple steering deliveries apply or fall back exactly once in admission- order;-- stale and duplicate dispositions cannot clear or duplicate the active lease;-- continuation rekey, hook disposal, retry, and replay cannot create a second- session or lose an admitted delivery;-- partial child routing preserves the source entry id and sequence.--### Step and harness integration--- nested live steering signal crosses the Workflow step boundary;-- already-pending state prevents park or completion without manufacturing a- pre-aborted signal;-- adapter `undefined` falls back to the original steering input;-- steering during model, tool, authorization, input-request, runtime-action,- and delegated-child waits preserves their pending state;-- structurally empty input follows new-session normalization;-- no late steering acknowledgement or disposition is emitted after terminal- teardown.--### Repository checks--Run focused unit and integration tests for the admission ledger, turn command-receiver, workflow step, turn workflow, tool loop, HITL, cancellation, and-descendant routing. Public exposure also requires typecheck, lint, invariant-guard, docs validation, the full unit tier, and a deterministic hosted e2e-fixture.--## Out of scope--- Whole-session cancellation or `/new`.-- Retraction of streamed output or completed side effects.-- A public `interrupt`, `replace`, `supersede`, or priority enum.-- Multiple concurrent leases to one turn.-- Automatic debounce or latest-message policy in built-in channels.-- Task-mode successor sessions.-- An adapter handled/suppressed result protocol beyond the steering fallback- rule above.--## Success criteria--- Channel authors choose only between standard `queue` and `steer` input- policies and use `cancel()` for a stop action.-- Every successfully admitted delivery is either durably consumed by the- active turn or retained by the driver for a later turn, never both and never- neither.-- Internal acknowledgement timing cannot affect ordering.-- Steering does not require cancellation-hook semantics or expose another- cancellation name.-- Public behavior is documented independently of Workflow hook layout, and- queue-only behavior remains correct after every landing stage.