The Open Framework for Building Agents
feat(eve): tag workflows with channel request ids (#215)
Ruic6b2da879b7a
diff --git a/.changeset/tidy-rings-trace.md b/.changeset/tidy-rings-trace.mdnew file mode 100644index 000000000..6547cc767--- /dev/null+++ b/.changeset/tidy-rings-trace.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Add `$eve.channel_request_id` workflow attributes from Vercel's `x-vercel-id` header so session and turn workflow runs can be joined back to the inbound request that started or resumed them.diff --git a/packages/eve/src/channel/send.test.ts b/packages/eve/src/channel/send.test.tsindex 95be07309..f826da885 100644--- a/packages/eve/src/channel/send.test.ts+++ b/packages/eve/src/channel/send.test.ts@@ -113,6 +113,27 @@ describe("createSendFn", () => {});});+ it("adds channel request ids to deliver and run inputs when provided", async () => {+ const deliverRuntime: Runtime = {+ deliver: vi.fn().mockResolvedValue({ sessionId: "existing-session-id" }),+ run: vi.fn().mockResolvedValue(createMockRunHandle()),+ getEventStream: vi.fn().mockResolvedValue(new ReadableStream<HandleMessageStreamEvent>()),+ };++ const deliverSend = createSendFn(deliverRuntime, ADAPTER, "test", {+ requestId: "req_send",+ });+ await deliverSend("hello", { auth: null, continuationToken: "token" });++ expect(vi.mocked(deliverRuntime.deliver).mock.calls[0]?.[0].requestId).toBe("req_send");++ const runRuntime = createRuntime(new RuntimeNoActiveSessionError("test:token"));+ const runSend = createSendFn(runRuntime, ADAPTER, "test", { requestId: "req_send" });+ await runSend("hello", { auth: null, continuationToken: "token" });++ expect(vi.mocked(runRuntime.run).mock.calls[0]?.[0].requestId).toBe("req_send");+ });+it("forwards outputSchema through deliver and run payloads", async () => {const outputSchema = {properties: { title: { type: "string" } },diff --git a/packages/eve/src/channel/send.ts b/packages/eve/src/channel/send.tsindex b93a67584..0504b4a53 100644--- a/packages/eve/src/channel/send.ts+++ b/packages/eve/src/channel/send.ts@@ -1,7 +1,7 @@import type { FilePart, UserContent } from "ai";import type { ChannelAdapter } from "#channel/adapter.js";-import type { Runtime, SessionAuthContext } from "#channel/types.js";+import type { DeliverInput, RunInput, Runtime, SessionAuthContext } from "#channel/types.js";import { createSession, type Session } from "#channel/session.js";import type { SendFn, SendOptions, SendPayload } from "#channel/routes.js";import { isRuntimeNoActiveSessionError } from "#execution/runtime-errors.js";@@ -14,6 +14,7 @@ export function createSendFn<TState = undefined>(runtime: Runtime,adapter: ChannelAdapter<any>,channelName: string,+ metadata: { readonly requestId?: string } = {},): SendFn<TState> {return async (input: string | UserContent | SendPayload,@@ -35,11 +36,13 @@ export function createSendFn<TState = undefined>(const message = serializeUrlFilePartsInMessage(rawMessage);try {- const { sessionId } = await runtime.deliver({+ const deliverInput: DeliverInput = {auth,continuationToken,+ requestId: metadata.requestId,payload: { inputResponses, message, context, outputSchema },- });+ };+ const { sessionId } = await runtime.deliver(deliverInput);return createSession(sessionId, rawToken, runtime);} catch (error) {@@ -62,7 +65,7 @@ export function createSendFn<TState = undefined>(? { ...adapter, state: { ...adapter.state, ...(state as Record<string, unknown>) } }: adapter;- const handle = await runtime.run({+ const runInput: RunInput = {adapter: sessionAdapter,auth,capabilities: mode === "conversation" ? { requestInput: true } : undefined,@@ -71,7 +74,9 @@ export function createSendFn<TState = undefined>(continuationToken,input: { message: message ?? "", context, outputSchema },mode,- });+ requestId: metadata.requestId,+ };+ const handle = await runtime.run(runInput);return createSession(handle.sessionId, rawToken, runtime);};diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.tsindex 0fbd89d51..b68d803b7 100644--- a/packages/eve/src/channel/types.ts+++ b/packages/eve/src/channel/types.ts@@ -112,6 +112,8 @@ export interface DeliverPayload {*/export interface DeliverHookPayload {readonly auth?: SessionAuthContext | null;+ /** Inbound channel request id used only for workflow attributes. */+ readonly requestId?: string;readonly kind: "deliver";readonly payloads: readonly DeliverPayload[];}@@ -236,6 +238,8 @@ export interface RunInput {* leave this undefined.*/readonly capabilities?: SessionCapabilities;+ /** Inbound channel request id used to correlate workflow attributes. */+ readonly requestId?: string;/*** Optional terminal callback. When present, the runtime posts a single* callback when the session completes or fails.@@ -273,6 +277,8 @@ export interface DeliverInput {* this field before calling the adapter's hooks.*/readonly auth?: SessionAuthContext | null;+ /** Inbound channel request id used to correlate workflow attributes. */+ readonly requestId?: string;readonly continuationToken: string;readonly payload: DeliverPayload;}diff --git a/packages/eve/src/context/keys.ts b/packages/eve/src/context/keys.tsindex 2fdb33ba2..788a0bc18 100644--- a/packages/eve/src/context/keys.ts+++ b/packages/eve/src/context/keys.ts@@ -60,6 +60,7 @@ export const AuthKey = new ContextKey<SessionAuthContext | null>("eve.auth");export const InitiatorAuthKey = new ContextKey<SessionAuthContext | null>("eve.initiatorAuth");export const SessionIdKey = new ContextKey<string>("eve.sessionId");export const ContinuationTokenKey = new ContextKey<string>("eve.continuationToken");+export const ChannelRequestIdKey = new ContextKey<string>("eve.channelRequestId");export const ChannelInstrumentationKey = new ContextKey<ChannelInstrumentationProjection>("eve.channelInstrumentation",);diff --git a/packages/eve/src/execution/eve-workflow-attributes.test.ts b/packages/eve/src/execution/eve-workflow-attributes.test.tsindex 5bc7b3fd8..4a91b4d49 100644--- a/packages/eve/src/execution/eve-workflow-attributes.test.ts+++ b/packages/eve/src/execution/eve-workflow-attributes.test.ts@@ -7,10 +7,12 @@ import {deriveSessionTitle,EVE_SESSION_TITLE_MAX_CHARS,readChannelKind,+ readChannelRequestId,readParentLineage,readParentSessionId,readRootSessionId,} from "#execution/eve-workflow-attributes.js";+import { ChannelRequestIdKey } from "#context/keys.js";const slackChannelCtx = {"eve.channel": { kind: "slack", state: { team: "T1" } },@@ -84,6 +86,22 @@ describe("readRootSessionId", () => {});});+describe("readChannelRequestId", () => {+ it("returns the channel request id when the context slot is well-formed", () => {+ expect(+ readChannelRequestId({+ [ChannelRequestIdKey.name]: "req_123",+ }),+ ).toBe("req_123");+ });++ it("returns undefined when the slot is missing or malformed", () => {+ expect(readChannelRequestId({})).toBeUndefined();+ expect(readChannelRequestId({ [ChannelRequestIdKey.name]: "" })).toBeUndefined();+ expect(readChannelRequestId({ [ChannelRequestIdKey.name]: 42 })).toBeUndefined();+ });+});+describe("deriveSessionTitle", () => {it("collapses whitespace and trims plain string messages", () => {expect(deriveSessionTitle(" hello\n\nworld ")).toBe("hello world");@@ -127,6 +145,7 @@ describe("buildSessionAttributes", () => {});expect(attrs).toEqual({+ "$eve.channel_request_id": undefined,"$eve.type": "session","$eve.trigger": "slack","$eve.title": "ship the thing please",@@ -142,6 +161,18 @@ describe("buildSessionAttributes", () => {expect(attrs["$eve.trigger"]).toBeUndefined();expect(attrs["$eve.title"]).toBe("hi");});++ it("emits the channel request id when present", () => {+ const attrs = buildSessionAttributes({+ inputMessage: "hi",+ serializedContext: {+ ...slackChannelCtx,+ [ChannelRequestIdKey.name]: "req_session",+ },+ });++ expect(attrs["$eve.channel_request_id"]).toBe("req_session");+ });});describe("buildSubagentRootAttributes", () => {@@ -156,6 +187,7 @@ describe("buildSubagentRootAttributes", () => {});expect(attrs).toEqual({+ "$eve.channel_request_id": undefined,"$eve.type": "subagent","$eve.parent": "wrun_parent_subagent","$eve.parent_call": "call_subagent_0",@@ -165,6 +197,20 @@ describe("buildSubagentRootAttributes", () => {"$eve.trigger": "slack",});});++ it("emits the channel request id when present", () => {+ const attrs = buildSubagentRootAttributes({+ identity: { nodeId: "subagents/linear" },+ parentSessionId: "wrun_parent_subagent",+ rootSessionId: "wrun_top_level_session",+ serializedContext: {+ ...subagentChainCtx,+ [ChannelRequestIdKey.name]: "req_subagent",+ },+ });++ expect(attrs["$eve.channel_request_id"]).toBe("req_subagent");+ });});describe("buildTurnAttributes", () => {@@ -175,9 +221,20 @@ describe("buildTurnAttributes", () => {});expect(attrs).toEqual({+ "$eve.channel_request_id": undefined,"$eve.type": "turn","$eve.parent": "wrun_session_123","$eve.root": "wrun_session_123",});});++ it("emits the channel request id when present", () => {+ const attrs = buildTurnAttributes({+ parentSessionId: "wrun_session_123",+ requestId: "req_turn",+ rootSessionId: "wrun_session_123",+ });++ expect(attrs["$eve.channel_request_id"]).toBe("req_turn");+ });});diff --git a/packages/eve/src/execution/eve-workflow-attributes.ts b/packages/eve/src/execution/eve-workflow-attributes.tsindex cad0b4c48..e34ba00bf 100644--- a/packages/eve/src/execution/eve-workflow-attributes.ts+++ b/packages/eve/src/execution/eve-workflow-attributes.ts@@ -22,8 +22,10 @@* - `$eve.subagent` — active compiled graph node id (subagent rows only)* - `$eve.trigger` — channel adapter kind (session/subagent rows)* - `$eve.title` — truncated session title from the first user message+ * - `$eve.channel_request_id` — inbound channel request id*/+import { ChannelRequestIdKey } from "#context/keys.js";import type { EveAttributeValue } from "#runtime/attributes/emit.js";import { isNonEmptyString } from "#shared/guards.js";@@ -118,6 +120,18 @@ export function readRootSessionId(serializedContext: Record<string, unknown>): sreturn readParentLineage(serializedContext).rootSessionId;}+/**+ * Reads the channel request id minted by an inbound channel route.+ * Returns `undefined` when the active run was not started from an+ * inbound route, such as a schedule.+ */+export function readChannelRequestId(+ serializedContext: Record<string, unknown>,+): string | undefined {+ const channelRequestId = serializedContext[ChannelRequestIdKey.name];+ return isNonEmptyString(channelRequestId) ? channelRequestId : undefined;+}+/*** Maximum visible length (in code points) of a derived `$eve.title`.*@@ -194,6 +208,7 @@ export function buildSessionAttributes(input: {readonly serializedContext: Record<string, unknown>;}): Record<string, EveAttributeValue> {return {+ "$eve.channel_request_id": readChannelRequestId(input.serializedContext),"$eve.type": "session","$eve.trigger": readChannelKind(input.serializedContext),"$eve.title": deriveSessionTitle(input.inputMessage),@@ -218,6 +233,7 @@ export function buildSubagentRootAttributes(input: {readonly serializedContext: Record<string, unknown>;}): Record<string, EveAttributeValue> {return {+ "$eve.channel_request_id": readChannelRequestId(input.serializedContext),"$eve.type": "subagent","$eve.parent": input.parentSessionId,"$eve.parent_call": input.parentCallId,@@ -240,9 +256,11 @@ export function buildSubagentRootAttributes(input: {*/export function buildTurnAttributes(input: {readonly parentSessionId: string;+ readonly requestId?: string;readonly rootSessionId: string;}): Record<string, EveAttributeValue> {return {+ "$eve.channel_request_id": input.requestId,"$eve.type": "turn","$eve.parent": input.parentSessionId,"$eve.root": input.rootSessionId,diff --git a/packages/eve/src/execution/runtime-context.ts b/packages/eve/src/execution/runtime-context.tsindex 2fbe211c6..78f645db0 100644--- a/packages/eve/src/execution/runtime-context.ts+++ b/packages/eve/src/execution/runtime-context.ts@@ -5,6 +5,7 @@ import {AuthKey,CapabilitiesKey,ChannelInstrumentationKey,+ ChannelRequestIdKey,ContinuationTokenKey,InitiatorAuthKey,ModeKey,@@ -44,6 +45,10 @@ export function buildRunContext(input: {ctx.set(CapabilitiesKey, run.capabilities);}+ if (run.requestId !== undefined) {+ ctx.set(ChannelRequestIdKey, run.requestId);+ }+if (run.callback !== undefined) {ctx.set(SessionCallbackKey, run.callback);}diff --git a/packages/eve/src/execution/workflow-entry.test.ts b/packages/eve/src/execution/workflow-entry.test.tsindex 7e307a33a..69a41434c 100644--- a/packages/eve/src/execution/workflow-entry.test.ts+++ b/packages/eve/src/execution/workflow-entry.test.ts@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { createHook } from "#compiled/@workflow/core/index.js";import type { HookPayload } from "#channel/types.js";+import { ChannelRequestIdKey } from "#context/keys.js";import { getRuntimeActionRequestKey } from "#runtime/actions/keys.js";import type { RuntimeSubagentResultActionResult } from "#runtime/actions/types.js";import { createSessionStep } from "#execution/create-session-step.js";@@ -231,6 +232,62 @@ describe("workflowEntry", () => {expect(dispose).toHaveBeenCalledOnce();});+ it("passes the run channel request id to the first turn", async () => {+ const sessionState = createBaseSessionState();+ vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));+ installHookMocks({+ turnCompletions: [turnResult({ action: "done", output: "ok", sessionState })],+ });++ await workflowEntry({+ input: { message: "hello there" },+ serializedContext: createSerializedContext({+ [ChannelRequestIdKey.name]: "req_initial",+ }),+ });++ expect(vi.mocked(dispatchTurnStep).mock.calls[0]?.[0].delivery).toEqual({+ requestId: "req_initial",+ kind: "deliver",+ payloads: [{ message: "hello there", context: undefined }],+ });+ });++ it("passes the resumed channel request id to the next turn", async () => {+ const sessionState = createBaseSessionState();+ vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));+ installHookMocks({+ parkHooks: [+ {+ token: "http:test",+ values: [+ {+ requestId: "req_followup",+ kind: "deliver",+ payloads: [{ message: "follow up" }],+ },+ ],+ },+ ],+ turnCompletions: [+ turnResult({ action: "park", sessionState }),+ turnResult({ action: "done", output: "ok", sessionState }),+ ],+ });++ await workflowEntry({+ input: { message: "hello there" },+ serializedContext: createSerializedContext(),+ });++ expect(vi.mocked(dispatchTurnStep).mock.calls[1]?.[0].delivery).toEqual({+ auth: undefined,+ requestId: "req_followup",+ kind: "deliver",+ payloads: [{ message: "follow up" }],+ });+ });+it("buffers follow-up user input until a pending subagent batch resolves", async () => {const baseSessionState = createBaseSessionState();const pendingSessionState = createPendingSubagentSessionState("forecast_delegate");diff --git a/packages/eve/src/execution/workflow-entry.ts b/packages/eve/src/execution/workflow-entry.tsindex 31586b13c..d2796d707 100644--- a/packages/eve/src/execution/workflow-entry.ts+++ b/packages/eve/src/execution/workflow-entry.ts@@ -13,7 +13,7 @@ import type {SessionCapabilities,} from "#channel/types.js";import { coalesceDeliveries } from "#harness/messages.js";-import { readRootSessionId } from "#execution/eve-workflow-attributes.js";+import { readChannelRequestId, readRootSessionId } from "#execution/eve-workflow-attributes.js";import { accumulateRuntimeActionResults } from "#harness/runtime-actions.js";import type { RunMode } from "#shared/run-mode.js";import type { RuntimeSubagentResultActionResult } from "#runtime/actions/types.js";@@ -125,6 +125,7 @@ export async function workflowEntry(input: WorkflowEntryInput): Promise<WorkflowoutputSchema: input.input.outputSchema,},],+ requestId: readChannelRequestId(input.serializedContext),},mode,serializedContext: input.serializedContext,@@ -399,6 +400,7 @@ async function runDriverLoop(input: {auth: nextDeliver.auth,kind: "deliver",payloads: [remainder],+ requestId: nextDeliver.requestId,},mode: input.mode,parentWritable: input.driverWritable,diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.tsindex b98491b07..a46429f99 100644--- a/packages/eve/src/execution/workflow-runtime.test.ts+++ b/packages/eve/src/execution/workflow-runtime.test.ts@@ -1,6 +1,7 @@import { afterEach, describe, expect, it, vi } from "vitest";import type { ChannelAdapter } from "#channel/adapter.js";+import { ChannelRequestIdKey } from "#context/keys.js";import { resolveInstalledPackageInfo } from "#internal/application/package.js";import {createWorkflowRuntime,@@ -89,6 +90,26 @@ describe("createWorkflowRuntime#deliver", () => {).rejects.toBe(failure);});+ it("resumes hooks with the channel request id", async () => {+ resumeHookMock.mockResolvedValue({ runId: "driver-run" });++ await expect(+ buildRuntime().deliver({+ auth: null,+ continuationToken: "test:token",+ payload: { message: "hello" },+ requestId: "req_deliver",+ }),+ ).resolves.toEqual({ sessionId: "driver-run" });++ expect(resumeHookMock).toHaveBeenCalledWith("test:token", {+ auth: null,+ kind: "deliver",+ payloads: [{ message: "hello" }],+ requestId: "req_deliver",+ });+ });+it("returns the owner from the hook resumed by the delivery", async () => {resumeHookMock.mockResolvedValue({ runId: "owner-session" });@@ -160,6 +181,34 @@ describe("createWorkflowRuntime#run", () => {);});+ it("serializes the channel request id into workflow context", async () => {+ vi.stubEnv("VERCEL_ENV", "production");+ const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;+ mockBundleAndRun(compiledArtifactsSource);+ startMock.mockResolvedValue({ runId: "driver-run" });++ await buildRuntime(compiledArtifactsSource).run({+ adapter,+ auth: null,+ input: { message: "hello" },+ mode: "task",+ requestId: "req_run",+ });++ expect(startMock).toHaveBeenCalledWith(+ workflowEntryReference,+ [+ {+ input: { message: "hello" },+ serializedContext: expect.objectContaining({+ [ChannelRequestIdKey.name]: "req_run",+ }),+ },+ ],+ { deploymentId: "latest" },+ );+ });+it("falls back to the current deployment when latest is unsupported", async () => {vi.stubEnv("VERCEL_ENV", "production");const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.tsindex 9018aa724..aff4b77a4 100644--- a/packages/eve/src/execution/workflow-runtime.ts+++ b/packages/eve/src/execution/workflow-runtime.ts@@ -123,10 +123,11 @@ export function createWorkflowRuntime(config: {async deliver(input: DeliverInput): Promise<{ sessionId: string }> {applyEveWorkflowQueueNamespace();- const hookPayload: HookPayload = {+ const hookPayload: Extract<HookPayload, { kind: "deliver" }> = {auth: input.auth,kind: "deliver",payloads: [input.payload],+ requestId: input.requestId,};try {const hook = normalizeWorkflowHook(await resumeHook(input.continuationToken, hookPayload));diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.tsindex 61cc92b83..9db9389cb 100644--- a/packages/eve/src/execution/workflow-steps.ts+++ b/packages/eve/src/execution/workflow-steps.ts@@ -116,6 +116,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResuawait setEveAttributes(buildTurnAttributes({parentSessionId: input.sessionState.sessionId,+ requestId: input.input?.kind === "deliver" ? input.input.requestId : undefined,rootSessionId: readRootSessionId(input.serializedContext) ?? input.sessionState.sessionId,}),);diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.test.tsindex bc830ec34..c31d7264d 100644--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts@@ -3,7 +3,8 @@ import { describe, expect, it, vi } from "vitest";import { CHANNEL_SENTINEL, type CompiledChannel } from "#channel/compiled-channel.js";import type { RouteHandlerArgs } from "#channel/routes.js";-import type { Runtime } from "#channel/types.js";+import type { DeliverInput, RunInput, Runtime } from "#channel/types.js";+import type { RouteContext } from "#public/definitions/channel.js";import type { ResolvedChannelDefinition } from "#runtime/types.js";import {dispatchChannelRequest,@@ -34,10 +35,11 @@ function createDeferred<T>() {}function createEvent(input?: {+ readonly headers?: Record<string, string>;readonly requestIp?: string;readonly waitUntil?: (task: Promise<unknown>) => void;}): H3Event {- const request = new Request("https://eve.test/slack");+ const request = new Request("https://eve.test/slack", { headers: input?.headers });Object.assign(request, {ip: input?.requestIp ?? "127.0.0.1",});@@ -172,6 +174,152 @@ describe("dispatchChannelRequest", () => {expect(typeof ctx.send).toBe("function");});+ it("tags route sends with Vercel's request id", async () => {+ const runtimeForTest: Runtime = {+ deliver: vi.fn().mockResolvedValue({ sessionId: "sess_route" }),+ getEventStream: vi.fn().mockResolvedValue(new ReadableStream()),+ run: vi.fn(),+ };++ mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({+ channels: [+ {+ handler: async (_req, args) => {+ await args.send("hello", {+ auth: null,+ continuationToken: "route-token",+ });+ return new Response("ok");+ },+ fetch: async () => new Response("ok"),+ adapter: { kind: "channel:webhook" },+ logicalPath: "agent/channels/webhook.ts",+ method: "POST",+ name: "webhook",+ sourceId: "channel-webhook",+ sourceKind: "module",+ urlPath: "/webhook",+ } satisfies ResolvedChannelDefinition,+ ],+ runtime: runtimeForTest,+ });++ const response = await dispatchChannelRequest(+ createEvent({+ headers: { "x-vercel-id": "iad1::abc123-1710000000000-deadbeef" },+ waitUntil: vi.fn(),+ }),+ "POST /webhook",+ {} as never,+ );++ expect(response.status).toBe(200);+ expect(vi.mocked(runtimeForTest.deliver).mock.calls[0]?.[0].requestId).toBe(+ "iad1::abc123-1710000000000-deadbeef",+ );+ });++ it("does not invent a channel request id when Vercel did not send one", async () => {+ const runtimeForTest: Runtime = {+ deliver: vi.fn().mockResolvedValue({ sessionId: "sess_route" }),+ getEventStream: vi.fn().mockResolvedValue(new ReadableStream()),+ run: vi.fn(),+ };++ mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({+ channels: [+ {+ handler: async (_req, args) => {+ await args.send("hello", {+ auth: null,+ continuationToken: "route-token",+ });+ return new Response("ok");+ },+ fetch: async () => new Response("ok"),+ adapter: { kind: "channel:webhook" },+ logicalPath: "agent/channels/webhook.ts",+ method: "POST",+ name: "webhook",+ sourceId: "channel-webhook",+ sourceKind: "module",+ urlPath: "/webhook",+ } satisfies ResolvedChannelDefinition,+ ],+ runtime: runtimeForTest,+ });++ const response = await dispatchChannelRequest(+ createEvent({ waitUntil: vi.fn() }),+ "POST /webhook",+ {} as never,+ );++ expect(response.status).toBe(200);+ expect(vi.mocked(runtimeForTest.deliver).mock.calls[0]?.[0].requestId).toBeUndefined();+ });++ it("does not mutate route-owned run and deliver inputs", async () => {+ const runtimeForTest: Runtime = {+ deliver: vi.fn().mockResolvedValue({ sessionId: "sess_deliver" }),+ getEventStream: vi.fn().mockResolvedValue(new ReadableStream()),+ run: vi.fn().mockResolvedValue({+ continuationToken: "route-token",+ events: new ReadableStream(),+ sessionId: "sess_run",+ }),+ };+ const deliverInput = Object.freeze({+ auth: null,+ continuationToken: "route-token",+ payload: { message: "follow up" },+ } satisfies DeliverInput);+ const runInput = Object.freeze({+ adapter: { kind: "channel:test" },+ auth: null,+ input: { message: "start" },+ mode: "conversation",+ } satisfies RunInput);++ mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({+ channels: [+ {+ fetch: async (_request: Request, ctx: RouteContext) => {+ await ctx.agent.deliver(deliverInput);+ await ctx.agent.run(runInput);+ return new Response("ok");+ },+ logicalPath: "agent/channels/internal.ts",+ method: "POST",+ name: "internal",+ sourceId: "channel-internal",+ sourceKind: "module",+ urlPath: "/internal",+ } satisfies ResolvedChannelDefinition,+ ],+ runtime: runtimeForTest,+ });++ const response = await dispatchChannelRequest(+ createEvent({+ headers: { "x-vercel-id": "iad1::abc123-1710000000000-deadbeef" },+ waitUntil: vi.fn(),+ }),+ "POST /internal",+ {} as never,+ );++ expect(response.status).toBe(200);+ const deliveredInput = vi.mocked(runtimeForTest.deliver).mock.calls[0]?.[0];+ const startedInput = vi.mocked(runtimeForTest.run).mock.calls[0]?.[0];+ expect(deliveredInput).not.toBe(deliverInput);+ expect(startedInput).not.toBe(runInput);+ expect(deliveredInput?.requestId).toBe("iad1::abc123-1710000000000-deadbeef");+ expect(startedInput?.requestId).toBe("iad1::abc123-1710000000000-deadbeef");+ expect(deliverInput).not.toHaveProperty("requestId");+ expect(runInput).not.toHaveProperty("requestId");+ });+it("hands websocket route handlers the same route args", async () => {const waitUntil = vi.fn<(task: Promise<unknown>) => void>();let capturedArgs: RouteHandlerArgs | undefined;diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.tsindex 0d1f100fa..0a48f3d05 100644--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.ts@@ -1,9 +1,10 @@import type { H3Event } from "nitro";-import type { RouteContext } from "#public/definitions/channel.js";+import type { Agent, RouteContext } from "#public/definitions/channel.js";import {createCrossChannelReceiveFn,toCrossChannelTargets,} from "#channel/cross-channel-receive.js";+import type { DeliverInput, RunInput, Runtime } from "#channel/types.js";import type { RouteHandlerArgs, WebSocketRouteHooks } from "#channel/routes.js";import { createSendFn } from "#channel/send.js";import { createGetSessionFn } from "#channel/session.js";@@ -13,6 +14,12 @@ import { resolveNitroChannelRuntimeBundle } from "#internal/nitro/routes/runtimeconst log = createLogger("channel.dispatch");+interface BuiltRouteArgs {+ readonly agent: Agent;+ readonly args: RouteHandlerArgs;+ readonly backgroundTasks: Promise<unknown>[];+}+/*** Dispatches one channel request identified by `routeKey`.*@@ -60,7 +67,7 @@ export async function dispatchChannelRequest(// Framework-internal fetch-only channel (e.g. the connection// callback route). Build a RouteContext with the agent handle.const ctx: RouteContext = {- agent: bundle.runtime,+ agent: routeArgs.agent,waitUntil: routeArgs.args.waitUntil,params: routeArgs.args.params,requestIp: routeArgs.args.requestIp,@@ -124,7 +131,8 @@ function buildRouteArgs(event: H3Event,bundle: Awaited<ReturnType<typeof resolveNitroChannelRuntimeBundle>>,channelName: string,-): { args: RouteHandlerArgs; backgroundTasks: Promise<unknown>[] } {+): BuiltRouteArgs {+ const requestId = readVercelRequestId(event.req.headers);const requestIp = extractSocketIp(event);const backgroundTasks: Promise<unknown>[] = [];const rawParams = (event.context.params as Record<string, string>) ?? {};@@ -138,7 +146,8 @@ function buildRouteArgs(};const channel = bundle.channels.find((candidate) => candidate.name === channelName);const adapter = channel?.adapter ?? { kind: "channel" };- const send = createSendFn(bundle.runtime, adapter, channelName);+ const agent = createRouteAgent(bundle.runtime, requestId);+ const send = createSendFn(bundle.runtime, adapter, channelName, { requestId });const getSession = createGetSessionFn(bundle.runtime);const receive = createCrossChannelReceiveFn(bundle.runtime,@@ -146,6 +155,7 @@ function buildRouteArgs();return {+ agent,args: {send,getSession,@@ -158,6 +168,27 @@ function buildRouteArgs(};}+function createRouteAgent(runtime: Runtime, requestId: string | undefined): Agent {+ return {+ async deliver(input) {+ const deliverInput: DeliverInput = { ...input, requestId }; // Avoid mutating a frozen caller input.+ return await runtime.deliver(deliverInput);+ },+ async getEventStream(sessionId, options) {+ return await runtime.getEventStream(sessionId, options);+ },+ async run(input) {+ const runInput: RunInput = { ...input, requestId }; // Avoid mutating a frozen caller input.+ return await runtime.run(runInput);+ },+ };+}++function readVercelRequestId(headers: Headers): string | undefined {+ const requestId = headers.get("x-vercel-id")?.trim();+ return requestId === "" ? undefined : requestId;+}+function rejectWebSocketUpgrade(body: Record<string, unknown>,status: number,