The Open Framework for Building Agents
feat(eve): add authenticated create-once sessions (#1805)
Ruid8cef1acccec
diff --git a/.changeset/create-once-forwarded-principal.md b/.changeset/create-once-forwarded-principal.mdnew file mode 100644index 000000000..2ae4d3637--- /dev/null+++ b/.changeset/create-once-forwarded-principal.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Scope create-once operations to the effective forwarded principal so two forwarded users behind the same trusted forwarder cannot adopt each other's session.diff --git a/.changeset/session-create-once.md b/.changeset/session-create-once.mdnew file mode 100644index 000000000..4476626c1--- /dev/null+++ b/.changeset/session-create-once.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Add authenticated create-once session requests through `operationId`. Concurrent or retried creates adopt the active session that first claimed the operation without dispatching duplicate input.diff --git a/docs/channels/eve.mdx b/docs/channels/eve.mdxindex 6db539183..b5d19317c 100644--- a/docs/channels/eve.mdx+++ b/docs/channels/eve.mdx@@ -45,6 +45,20 @@ curl -X POST https://<deployment>/eve/v1/session \# {"ok":true,"sessionId":"wrun_A","status":"accepted"}```+Authenticated callers that may retry a create request can pass their own `operationId` for+create-once semantics. The same operation under the same authenticated principal returns the+active session it already created instead of dispatching the input again. The first accepted+payload wins; retries with different input still return that first session. Anonymous callers+cannot use `operationId`, and operation ownership expires when the session is no longer resumable.++```bash+curl -X POST https://<deployment>/eve/v1/session \+ -H "Authorization: Bearer <token>" \+ -H "Content-Type: application/json" \+ -d '{"message":"What is the weather in Paris?","operationId":"order-4213-research"}'+# {"ok":true,"sessionId":"wrun_A","status":"accepted"} — retries return the same sessionId+```+The first request requires `message`. A follow-up request accepts exactly one of`message` or `inputResponses`; use the latter to answer a pending HITL request:diff --git a/e2e/fixtures/agent-basic-runtime/agent/channels/eve.ts b/e2e/fixtures/agent-basic-runtime/agent/channels/eve.tsnew file mode 100644index 000000000..983152c79--- /dev/null+++ b/e2e/fixtures/agent-basic-runtime/agent/channels/eve.ts@@ -0,0 +1,25 @@+import type { AuthFn } from "eve/channels/auth";+import { eveChannel } from "eve/channels/eve";+import type { SessionAuthContext } from "eve/context";++const PRINCIPAL_A = "Bearer e2e-create-once-a";+const PRINCIPAL_B = "Bearer e2e-create-once-b";++function principal(issuer: string): SessionAuthContext {+ return {+ attributes: {},+ authenticator: "e2e-create-once",+ issuer,+ principalId: "shared-principal-id",+ principalType: "user",+ subject: "shared-subject",+ };+}++const authenticateA: AuthFn<Request> = (request) =>+ request.headers.get("authorization") === PRINCIPAL_A ? principal("issuer-a") : null;+const authenticateB: AuthFn<Request> = (request) =>+ request.headers.get("authorization") === PRINCIPAL_B ? principal("issuer-b") : null;+const authenticateEvalDriver: AuthFn<Request> = () => principal("eval-driver");++export default eveChannel({ auth: [authenticateA, authenticateB, authenticateEvalDriver] });diff --git a/e2e/fixtures/agent-basic-runtime/evals/runtime/session-create-idempotency.eval.ts b/e2e/fixtures/agent-basic-runtime/evals/runtime/session-create-idempotency.eval.tsnew file mode 100644index 000000000..6e3faad9e--- /dev/null+++ b/e2e/fixtures/agent-basic-runtime/evals/runtime/session-create-idempotency.eval.ts@@ -0,0 +1,88 @@+import { defineEval, type EveEvalTargetHandle } from "eve/evals";+import { equals, satisfies } from "eve/evals/expect";++interface CreateSessionResponse {+ readonly ok: true;+ readonly sessionId: string;+ readonly status: "accepted";+}++const PRINCIPAL_A = "Bearer e2e-create-once-a";+const PRINCIPAL_B = "Bearer e2e-create-once-b";++export default defineEval({+ description:+ "Concurrent and serial create retries dispatch once and remain isolated across issuers.",+ async test(t) {+ const operationId = `session-create-idempotency-${crypto.randomUUID()}`;+ const message = `CREATE-ONCE-INITIAL-${crypto.randomUUID()}`;+ const [first, concurrent] = await Promise.all([+ createSession(t.target, PRINCIPAL_A, operationId, message),+ createSession(t.target, PRINCIPAL_A, operationId, message),+ ]);+ const replay = await createSession(t.target, PRINCIPAL_A, operationId, message);+ const otherIssuer = await createSession(t.target, PRINCIPAL_B, operationId, message);++ for (const retry of [concurrent, replay]) {+ await t.require(retry.sessionId, equals(first.sessionId));+ }+ await t.require(+ otherIssuer,+ satisfies(+ (value: CreateSessionResponse) => value.sessionId !== first.sessionId,+ "the same operation under another issuer owns a distinct session",+ ),+ );++ const [firstTurn, issuerTurn] = await Promise.all([+ t.target.watchTurn(first.sessionId).result(),+ t.target.watchTurn(otherIssuer.sessionId).result(),+ ]);+ firstTurn.expectOk();+ firstTurn.event("message.received", { count: 1, data: { message } });+ firstTurn.event("step.started", { count: 1 });+ issuerTurn.expectOk();+ issuerTurn.event("message.received", { count: 1, data: { message } });+ issuerTurn.event("step.started", { count: 1 });++ const probe = `CREATE-ONCE-PROBE-${crypto.randomUUID()}`;+ const liveProbe = t.target.watchTurn(first.sessionId, { startIndex: firstTurn.events.length });+ await continueSession(t.target, PRINCIPAL_A, first.sessionId, probe);+ const probeTurn = await liveProbe.result();+ probeTurn.expectOk();+ probeTurn.event("message.received", { count: 1, data: { message: probe } });+ probeTurn.event("step.started", { count: 1 });+ },+});++async function createSession(+ target: EveEvalTargetHandle,+ authorization: string,+ operationId: string,+ message: string,+): Promise<CreateSessionResponse> {+ const response = await target.fetch("/eve/v1/session", {+ body: JSON.stringify({ message, operationId }),+ headers: { authorization, "content-type": "application/json" },+ method: "POST",+ });+ const text = await response.text();+ if (!response.ok) throw new Error(`POST /eve/v1/session failed (${response.status}): ${text}`);+ return JSON.parse(text) as CreateSessionResponse;+}++async function continueSession(+ target: EveEvalTargetHandle,+ authorization: string,+ sessionId: string,+ message: string,+): Promise<void> {+ const response = await target.fetch(`/eve/v1/session/${encodeURIComponent(sessionId)}`, {+ body: JSON.stringify({ message }),+ headers: { authorization, "content-type": "application/json" },+ method: "POST",+ });+ if (!response.ok) {+ throw new Error(`POST continuation failed (${response.status}): ${await response.text()}`);+ }+}diff --git a/packages/eve/src/execution/workflow-entry.integration.test.ts b/packages/eve/src/execution/workflow-entry.integration.test.tsindex b1d633bd1..2263585f9 100644--- a/packages/eve/src/execution/workflow-entry.integration.test.ts+++ b/packages/eve/src/execution/workflow-entry.integration.test.ts@@ -967,7 +967,7 @@ describe("workflowEntry integration", () => {});});- it("fails a competing continuation owner before its first turn", async () => {+ it("exits a competing continuation owner before its first turn", async () => {const runtime = createTestRuntime({ agent: { name: "workflow-entry-hook-owner" } });const continuationToken = "http:workflow-entry-hook-owner";@@ -998,20 +998,8 @@ describe("workflowEntry integration", () => {}),},]);- const contenderStream = captureTurnEvents(contender);-try {- const contenderEvents = await contenderStream.nextTurn();-- expect(contenderEvents.at(-1)?.type).toBe("session.failed");- expect(- contenderEvents.some(- (event) => event.type === "message.completed" || event.type === "turn.started",- ),- ).toBe(false);- await expect(contender.returnValue).rejects.toThrow(- /Agent workflow failed\. Inspect the private session trace for details\./,- );+ await expect(contender.returnValue).resolves.toEqual({ output: "" });await resumeHook(continuationToken, {kind: "send",@@ -1028,7 +1016,6 @@ describe("workflowEntry integration", () => {),).toBe(true);} finally {- contenderStream.dispose();ownerStream.dispose();await owner.cancel();}diff --git a/packages/eve/src/execution/workflow-entry.test.ts b/packages/eve/src/execution/workflow-entry.test.tsindex 3c8fb0f07..e126ea25f 100644--- a/packages/eve/src/execution/workflow-entry.test.ts+++ b/packages/eve/src/execution/workflow-entry.test.ts@@ -199,7 +199,7 @@ describe("workflowEntry", () => {expect(terminateChildSessionsStep).toHaveBeenCalledWith({ sessionState });});- it("fails a conflicting delivery hook before dispatching the first turn", async () => {+ it("exits a conflicting initial continuation before dispatching the first turn", async () => {const sessionState = createBaseSessionState();const dispose = vi.fn();vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));@@ -219,25 +219,14 @@ describe("workflowEntry", () => {input: { message: "duplicate" },serializedContext: createSerializedContext(),}),- ).rejects.toMatchObject({- message: "Agent workflow failed. Inspect the private session trace for details.",- name: "EveWorkflowFailure",- });+ ).resolves.toEqual({ output: "" });- expect(emitTerminalSessionFailureStep).toHaveBeenCalledWith(- expect.objectContaining({- error: expect.objectContaining({- conflictingRunId: "wrun_owner",- name: "HookConflictError",- token: "http:test",- }),- }),- );+ expect(emitTerminalSessionFailureStep).not.toHaveBeenCalled();expect(dispatchTurnStep).not.toHaveBeenCalled();expect(dispose).toHaveBeenCalledOnce();});- it("normalizes the getConflict fallback error before dispatching the first turn", async () => {+ it("also exits when a legacy world reports the initial continuation conflict", async () => {const sessionState = createBaseSessionState();const dispose = vi.fn();const fallbackError = Object.assign(new Error("legacy hook conflict"), {@@ -263,20 +252,9 @@ describe("workflowEntry", () => {input: { message: "duplicate" },serializedContext: createSerializedContext(),}),- ).rejects.toMatchObject({- message: "Agent workflow failed. Inspect the private session trace for details.",- name: "EveWorkflowFailure",- });+ ).resolves.toEqual({ output: "" });- expect(emitTerminalSessionFailureStep).toHaveBeenCalledWith(- expect.objectContaining({- error: expect.objectContaining({- message: 'Hook token "http:test" is already in use',- name: "HookConflictError",- token: "http:test",- }),- }),- );+ expect(emitTerminalSessionFailureStep).not.toHaveBeenCalled();expect(dispatchTurnStep).not.toHaveBeenCalled();expect(dispose).toHaveBeenCalledOnce();});diff --git a/packages/eve/src/execution/workflow-entry.ts b/packages/eve/src/execution/workflow-entry.tsindex 2fca9711b..ae1a8d5dd 100644--- a/packages/eve/src/execution/workflow-entry.ts+++ b/packages/eve/src/execution/workflow-entry.ts@@ -31,6 +31,7 @@ import { createSessionStep } from "#execution/create-session-step.js";import { settleCancelledTurnStep } from "#execution/settle-cancelled-turn-step.js";import { emitTerminalSessionFailureStep } from "#execution/terminal-session-failure-step.js";import { fireSessionCallbackStep } from "#execution/session-callback-step.js";+import { isHookConflictError } from "#execution/hook-ownership.js";import { createSessionCommandInbox } from "#execution/session-command-inbox.js";import { sessionCommandHookToken } from "#execution/session-command-token.js";import { DEFAULT_SESSION_TIMEOUT_MS } from "#execution/session-timeout.js";@@ -426,7 +427,14 @@ async function runDriverLoop(input: {try {if (input.sessionState.continuationToken) {- await commandInbox.rekeyContinuation(input.sessionState.continuationToken);+ try {+ await commandInbox.rekeyContinuation(input.sessionState.continuationToken);+ } catch (error) {+ // A concurrent create may start multiple candidates before one owns+ // the shared alias. The loser exits before dispatching its first turn.+ if (!isHookConflictError(error)) throw error;+ return { kind: "result", result: { output: "" } };+ }}await sessionTimeout?.start();diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.tsindex ba03b8e5f..9720ebbf2 100644--- a/packages/eve/src/execution/workflow-runtime.ts+++ b/packages/eve/src/execution/workflow-runtime.ts@@ -187,7 +187,6 @@ export function createWorkflowRuntime(config: {throw error;}- await waitForOwnedCommandHook(sessionCommandHookToken(run.runId), run.runId);if (input.continuationToken) {const owner = await waitForCommandHookOwner(input.continuationToken);if (owner.runId !== run.runId) {@@ -198,6 +197,7 @@ export function createWorkflowRuntime(config: {});}}+ await waitForOwnedCommandHook(sessionCommandHookToken(run.runId), run.runId);let events: ReadableStream<MessageStreamEvent> | undefined;const getEvents = () => {diff --git a/packages/eve/src/internal/invocation/workflow-execution.test.ts b/packages/eve/src/internal/invocation/workflow-execution.test.tsindex 7df19ea14..71c961087 100644--- a/packages/eve/src/internal/invocation/workflow-execution.test.ts+++ b/packages/eve/src/internal/invocation/workflow-execution.test.ts@@ -1,6 +1,6 @@import { beforeEach, describe, expect, it, vi } from "vitest";-import type { RunHandle, SessionAuthContext } from "#channel/types.js";+import type { SessionAuthContext } from "#channel/types.js";import { INTERNAL_CHANNEL_DELIVER } from "#channel/channel-operations.js";import {buildInvocationAttributes,@@ -9,6 +9,7 @@ import {invocationOwnerKey,} from "#internal/invocation/metadata.js";import { WorkflowAgentInvocationExecution } from "#internal/invocation/workflow-execution.js";+import type { RouteSessionCreator } from "#internal/nitro/routes/channel-route-context.js";import type { HandleMessageStreamEvent } from "#protocol/message.js";import { normalizeEveAttributes } from "#runtime/attributes/normalize.js";@@ -35,7 +36,7 @@ const auth: SessionAuthContext = {principalType: "user",};-const createSession = vi.fn<() => Promise<RunHandle>>();+const createSession = vi.fn<RouteSessionCreator>();const deliver = vi.fn();const from = vi.fn(() => ({ [INTERNAL_CHANNEL_DELIVER]: deliver }) as never);@@ -59,10 +60,13 @@ describe("WorkflowAgentInvocationExecution", () => {expect(createSession).toHaveBeenCalledWith(expect.objectContaining({capabilities: { requestInput: true },+ continuationToken: expect.stringMatching(/^invocation:/),externalInvocation: expect.objectContaining({ continuationToken: expect.any(String) }),mode: "task",}),);+ const createInput = createSession.mock.calls[0]?.[0];+ expect(createInput?.externalInvocation?.continuationToken).toBe(createInput?.continuationToken);expect(invocation).toMatchObject({createdAt: "2026-07-20T00:00:00.000Z",invocationId: "wrun_invocation",@@ -431,7 +435,7 @@ describe("WorkflowAgentInvocationExecution", () => {});function execution(): WorkflowAgentInvocationExecution {- return new WorkflowAgentInvocationExecution({ channelName: "mcp", createSession, from });+ return new WorkflowAgentInvocationExecution({ createSession, from });}function run(input: { ownerKey?: string; status: string }) {diff --git a/packages/eve/src/internal/invocation/workflow-execution.ts b/packages/eve/src/internal/invocation/workflow-execution.tsindex 80ae687d2..02fe1b94d 100644--- a/packages/eve/src/internal/invocation/workflow-execution.ts+++ b/packages/eve/src/internal/invocation/workflow-execution.ts@@ -28,16 +28,10 @@ import type { JsonObject, JsonValue } from "#shared/json.js";import { parseJsonValue } from "#shared/json.js";export class WorkflowAgentInvocationExecution {- readonly #channelName: string;readonly #createSession: RouteSessionCreator;readonly #from: ChannelFrom;- constructor(input: {- readonly channelName: string;- readonly createSession: RouteSessionCreator;- readonly from: ChannelFrom;- }) {- this.#channelName = input.channelName;+ constructor(input: { readonly createSession: RouteSessionCreator; readonly from: ChannelFrom }) {this.#createSession = input.createSession;this.#from = input.from;}@@ -51,7 +45,7 @@ export class WorkflowAgentInvocationExecution {const handle = await this.#createSession({auth: input.auth,capabilities: { requestInput: true },- continuationToken: `${this.#channelName}:${continuationToken}`,+ continuationToken,externalInvocation: {continuationToken,ownerKey: invocationOwnerKey(input.auth),diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.tsindex 05acbd2e9..da6f7f242 100644--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.ts@@ -271,6 +271,10 @@ function buildRouteArgs(...input,adapter,channelName,+ continuationToken:+ input.continuationToken === undefined+ ? undefined+ : `${channelName}:${input.continuationToken}`,delivery: createChannelDeliveryMetadata(deliverySource),requestId,}),diff --git a/packages/eve/src/internal/nitro/routes/channel-route-context.ts b/packages/eve/src/internal/nitro/routes/channel-route-context.tsindex d018e3064..7a085f226 100644--- a/packages/eve/src/internal/nitro/routes/channel-route-context.ts+++ b/packages/eve/src/internal/nitro/routes/channel-route-context.ts@@ -2,6 +2,11 @@ import type { RouteHandlerArgs } from "#channel/routes.js";import type { RunHandle, RunInput } from "#channel/types.js";type AgentInfoRouteResponse = () => Promise<Response>;+/**+ * Creates one session from a route handler. `continuationToken` is+ * channel-local (the dispatcher prepends the channel name), so ownership+ * established here is visible to `resolveSession` on the same channel.+ */export type RouteSessionCreator = (input: Omit<RunInput, "adapter" | "channelName" | "requestId">,) => Promise<RunHandle>;diff --git a/packages/eve/src/public/channels/eve.test.ts b/packages/eve/src/public/channels/eve.test.tsindex 18ff6ca23..287c6286e 100644--- a/packages/eve/src/public/channels/eve.test.ts+++ b/packages/eve/src/public/channels/eve.test.ts@@ -4,6 +4,7 @@ import { describe, expect, it, vi } from "vitest";import { buildAdapterContext } from "#channel/adapter-context.js";import { callAdapterEventHandler, type ChannelAdapter } from "#channel/adapter.js";import { isCompiledChannel } from "#channel/compiled-channel.js";+import { RuntimeSessionOwnershipConflictError } from "#execution/runtime-errors.js";import { attachRouteSessionCreator } from "#internal/nitro/routes/channel-route-context.js";import { mockChannelContext } from "#internal/testing/mocks/mock-channel-operations.js";import { type AuthFn, none } from "#public/channels/auth.js";@@ -48,7 +49,7 @@ const OVERRIDE_AUTH: SessionAuthContext = {type MockSendOptions = Pick<RunInput,- "auth" | "callback" | "capabilities" | "initiatorAuth" | "mode" | "title"+ "auth" | "callback" | "capabilities" | "continuationToken" | "initiatorAuth" | "mode" | "title">;function createJsonMessageRequest(body: unknown): Request {@@ -97,12 +98,22 @@ function createRouteArgs(): RouteHandlerArgs {* Returns a `fetch(req)` function and a `send` mock so tests can inspect* what the handler passed through.*/-function createEveCreateHandler(input: EveChannelInput) {+function createEveCreateHandler(+ input: EveChannelInput,+ options: { readonly activeSessionId?: string } = {},+) {const channel = eveChannel(input);const createRoute = channel.routes.find((r) => r.method === "POST" && r.path === "/eve/v1/session",);if (!createRoute) throw new Error("No create POST route found");+ const resolveSession = vi+ .fn<RouteHandlerArgs["resolveSession"]>()+ .mockResolvedValue(+ options.activeSessionId === undefined+ ? undefined+ : createMockSession({ id: options.activeSessionId }),+ );const mockSend = vi.fn().mockResolvedValue(createMockSession());const createSession = vi.fn(async (runInput: RunInput) => {@@ -114,6 +125,7 @@ function createEveCreateHandler(input: EveChannelInput) {auth: runInput.auth,callback: runInput.callback,capabilities: runInput.capabilities,+ continuationToken: runInput.continuationToken,initiatorAuth: runInput.initiatorAuth,mode: runInput.mode,title: runInput.title,@@ -125,9 +137,14 @@ function createEveCreateHandler(input: EveChannelInput) {});return {+ createSession,+ resolveSession,send: mockSend,async fetch(req: Request) {- const args = attachRouteSessionCreator(createRouteArgs(), createSession as never);+ const args = attachRouteSessionCreator(+ { ...createRouteArgs(), resolveSession },+ createSession as never,+ );return (createRoute as any).handler(req, args);},};@@ -792,6 +809,123 @@ describe("eveChannel — onMessage", () => {});});+describe("eveChannel — create session idempotency", () => {+ it("creates once for an operation id and uses it as the continuation token", async () => {+ const handler = createEveCreateHandler({ auth: () => ACCEPTED_AUTH });++ const response = await handler.fetch(+ createJsonMessageRequest({ message: "hi", operationId: "operation-1" }),+ );++ expect(response.status).toBe(202);+ const token = handler.send.mock.calls[0]?.[1]?.continuationToken;+ expect(token).toMatch(/^eve:op:[0-9a-f]{32}$/);+ expect(handler.resolveSession).toHaveBeenCalledWith(token);+ });++ it("returns the existing child for a replayed operation without dispatching again", async () => {+ const handler = createEveCreateHandler(+ { auth: () => ACCEPTED_AUTH },+ { activeSessionId: "child-1" },+ );++ const response = await handler.fetch(+ createJsonMessageRequest({ message: "hi", operationId: "operation-1" }),+ );++ expect(response.status).toBe(202);+ await expect(response.json()).resolves.toMatchObject({ ok: true, sessionId: "child-1" });+ expect(handler.send).not.toHaveBeenCalled();+ });++ it("adopts the winner when a concurrent create claims the operation token first", async () => {+ const handler = createEveCreateHandler({ auth: () => ACCEPTED_AUTH });+ handler.createSession.mockRejectedValueOnce(+ new RuntimeSessionOwnershipConflictError({+ continuationToken: "eve:eve:op:test",+ ownerSessionId: "child-2",+ sessionId: "loser",+ }),+ );++ const response = await handler.fetch(+ createJsonMessageRequest({ message: "hi", operationId: "operation-1" }),+ );++ expect(response.status).toBe(202);+ await expect(response.json()).resolves.toMatchObject({ ok: true, sessionId: "child-2" });+ });++ it("scopes the operation token to the complete authenticated principal", async () => {+ const tokenFor = async (identity: {+ issuer?: string;+ principalId?: string;+ principalType?: string;+ subject?: string;+ }): Promise<unknown> => {+ const handler = createEveCreateHandler({+ auth: () => {+ const context: {+ attributes: Record<string, string>;+ authenticator: string;+ issuer?: string;+ principalId: string;+ principalType: string;+ subject?: string;+ } = {+ attributes: {},+ authenticator: "test",+ principalId: identity.principalId ?? "caller",+ principalType: identity.principalType ?? "service",+ };+ if (identity.issuer !== undefined) context.issuer = identity.issuer;+ if (identity.subject !== undefined) context.subject = identity.subject;+ return context;+ },+ });+ await handler.fetch(createJsonMessageRequest({ message: "hi", operationId: "operation-1" }));+ return handler.send.mock.calls[0]?.[1]?.continuationToken;+ };++ const original = await tokenFor({ issuer: "issuer-a" });+ expect(await tokenFor({ issuer: "issuer-b" })).not.toBe(original);+ expect(await tokenFor({ issuer: "issuer-a", principalType: "user" })).not.toBe(original);+ expect(await tokenFor({ issuer: "issuer-a", principalId: "other" })).not.toBe(original);+ expect(await tokenFor({ issuer: "issuer-a", subject: "different-provenance" })).toBe(original);+ });++ it("rejects operation ids for anonymous callers", async () => {+ const handler = createEveCreateHandler({ auth: none() });++ const response = await handler.fetch(+ createJsonMessageRequest({ message: "hi", operationId: "operation-1" }),+ );++ expect(response.status).toBe(400);+ expect(handler.send).not.toHaveBeenCalled();+ });++ it("rejects a non-string operation id", async () => {+ const handler = createEveCreateHandler({ auth: none() });++ const response = await handler.fetch(+ createJsonMessageRequest({ message: "hi", operationId: 42 }),+ );++ expect(response.status).toBe(400);+ expect(handler.send).not.toHaveBeenCalled();+ });++ it("passes no continuation token when no operation id is supplied", async () => {+ const handler = createEveCreateHandler({ auth: none() });++ await handler.fetch(createJsonMessageRequest({ message: "hi" }));++ expect(handler.send.mock.calls[0]?.[1]?.continuationToken).toBeUndefined();+ expect(handler.resolveSession).not.toHaveBeenCalled();+ });+});+describe("eveChannel — create session (text)", () => {it("returns a structured 500 when session creation fails", async () => {const handler = createEveCreateHandler({ auth: none() });@@ -1888,6 +2022,77 @@ describe("eveChannel — forwarded principal", () => {expect(options.mode).toBe("task");});+ it("scopes create-once operations to the forwarded principal", async () => {+ const otherUser: SessionAuthContext = {+ ...FORWARDED_CURRENT,+ attributes: { user_id: "U456" },+ principalId: "slack:U456",+ subject: "U456",+ };+ const first = createEveCreateHandler({+ trustedForwarders: () => true,+ auth: () => ROUTER_CALLER,+ });+ const second = createEveCreateHandler({+ trustedForwarders: () => true,+ auth: () => ROUTER_CALLER,+ });++ const firstResponse = await first.fetch(+ createJsonMessageRequest({+ forwardedPrincipal: { current: FORWARDED_CURRENT },+ message: "hi",+ operationId: "shared-operation",+ }),+ );+ const secondResponse = await second.fetch(+ createJsonMessageRequest({+ forwardedPrincipal: { current: otherUser },+ message: "hi",+ operationId: "shared-operation",+ }),+ );++ expect(firstResponse.status).toBe(202);+ expect(secondResponse.status).toBe(202);+ const firstToken = first.send.mock.calls[0]?.[1]?.continuationToken;+ const secondToken = second.send.mock.calls[0]?.[1]?.continuationToken;+ expect(firstToken).toMatch(/^eve:op:[0-9a-f]{32}$/);+ expect(secondToken).toMatch(/^eve:op:[0-9a-f]{32}$/);+ expect(secondToken).not.toBe(firstToken);+ await expect(secondResponse.json()).resolves.toMatchObject({+ sessionId: "test-session-id",+ });+ expect(second.resolveSession).toHaveBeenCalledWith(secondToken);+ expect(second.resolveSession).not.toHaveBeenCalledWith(firstToken);+ });++ it("rejects create-once operations for a forwarded anonymous principal", async () => {+ const handler = createEveCreateHandler({+ trustedForwarders: () => true,+ auth: () => ROUTER_CALLER,+ });++ const response = await handler.fetch(+ createJsonMessageRequest({+ forwardedPrincipal: {+ current: {+ attributes: {},+ authenticator: "none",+ principalId: "anonymous",+ principalType: "anonymous",+ },+ },+ message: "hi",+ operationId: "shared-operation",+ }),+ );++ expect(response.status).toBe(400);+ expect(handler.resolveSession).not.toHaveBeenCalled();+ expect(handler.send).not.toHaveBeenCalled();+ });+it("defaults the initiator to the forwarded current principal", async () => {const handler = createEveCreateHandler({trustedForwarders: () => true,diff --git a/packages/eve/src/public/channels/eve.ts b/packages/eve/src/public/channels/eve.tsindex 6ee754b44..cb03d9c27 100644--- a/packages/eve/src/public/channels/eve.ts+++ b/packages/eve/src/public/channels/eve.ts@@ -13,6 +13,7 @@ import type { ResetResponse } from "#protocol/reset-session.js";import type { Session } from "#channel/session.js";import { resolveForwardedPrincipal, type TrustedForwarders } from "#channel/forwarded-principal.js";import { parseSessionCallback } from "#channel/session-callback.js";+import { isRuntimeSessionOwnershipConflictError } from "#execution/runtime-errors.js";import { hasInternalRefScheme } from "#internal/attachments/url-refs.js";import { createLogger, logError } from "#internal/logging.js";import {@@ -252,6 +253,35 @@ export function eveChannel(input: EveChannelInput): EveChannel {const policyRejection = checkUploadPolicy(body, uploadPolicy);if (policyRejection !== null) return policyRejection;+ if (body.operationId !== undefined && forwarded.auth.principalType === "anonymous") {+ return Response.json(+ { error: "operationId requires an authenticated principal.", ok: false },+ { status: 400 },+ );+ }+ const operationToken =+ body.operationId === undefined+ ? undefined+ : await deriveOperationContinuationToken({+ auth: forwarded.auth,+ operationId: body.operationId,+ });+ if (operationToken !== undefined) {+ const owner = await args.resolveSession(operationToken);+ if (owner !== undefined) {+ return Response.json(+ { ok: true, sessionId: owner.id, status: "accepted" },+ {+ headers: {+ "cache-control": "no-store",+ [EVE_SESSION_ID_HEADER]: owner.id,+ },+ status: 202,+ },+ );+ }+ }+const messageResult = await resolveOnMessage({auth: forwarded.auth,config: input,@@ -274,6 +304,7 @@ export function eveChannel(input: EveChannelInput): EveChannel {capabilities:body.capabilities ?? (body.mode === "task" ? undefined : { requestInput: true }),callback: body.callback,+ continuationToken: operationToken,initiatorAuth: forwarded.accepted ? forwarded.initiatorAuth : undefined,input: {message: body.message,@@ -284,6 +315,20 @@ export function eveChannel(input: EveChannelInput): EveChannel {parentTraceContext,});} catch (error) {+ // A concurrent create-once request won the token: adopt its session+ // without delivering this duplicate input.+ if (operationToken !== undefined && isRuntimeSessionOwnershipConflictError(error)) {+ return Response.json(+ { ok: true, sessionId: error.ownerSessionId, status: "accepted" },+ {+ headers: {+ "cache-control": "no-store",+ [EVE_SESSION_ID_HEADER]: error.ownerSessionId,+ },+ status: 202,+ },+ );+ }const errorId = logError(log, "session-create request failed", error);return Response.json({ error: "Failed to create the session.", errorId, ok: false },@@ -621,9 +666,30 @@ interface ParsedCreateBody {message: string | UserContent;mode?: RunMode;context?: readonly string[];+ operationId?: string;outputSchema?: JsonObject;}+/** Replay-stable identity for one authenticated create operation. */+async function deriveOperationContinuationToken(input: {+ readonly auth: SessionAuthContext;+ readonly operationId: string;+}): Promise<string> {+ const identity = JSON.stringify([+ "eve:create-session:v1",+ input.auth.authenticator,+ input.auth.issuer ?? null,+ input.auth.principalType,+ input.auth.principalId,+ input.operationId,+ ]);+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(identity));+ const hex = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(+ "",+ );+ return `eve:op:${hex.slice(0, 32)}`;+}+function parseCreateBody(payload: Record<string, unknown>): ParsedCreateBody | Response {if (payload.inputResponses !== undefined) {return Response.json(@@ -656,7 +722,24 @@ function parseCreateBody(payload: Record<string, unknown>): ParsedCreateBody | R);}- return { callback, capabilities, message, mode, context, outputSchema };+ const rawOperationId = payload.operationId;+ if (rawOperationId !== undefined && (typeof rawOperationId !== "string" || !rawOperationId)) {+ return Response.json(+ { error: "Expected 'operationId' to be a non-empty string.", ok: false },+ { status: 400 },+ );+ }++ const result: ParsedCreateBody = {+ callback,+ capabilities,+ message,+ mode,+ context,+ outputSchema,+ };+ if (typeof rawOperationId === "string") result.operationId = rawOperationId;+ return result;}interface ParsedSessionMessageBody {diff --git a/packages/eve/src/public/channels/mcp.ts b/packages/eve/src/public/channels/mcp.tsindex 72b7e4410..184ed54b4 100644--- a/packages/eve/src/public/channels/mcp.ts+++ b/packages/eve/src/public/channels/mcp.ts@@ -350,7 +350,6 @@ async function handleMcpRequest(const description =typeof agentInfo.agent.description === "string" ? agentInfo.agent.description : undefined;const execution = new WorkflowAgentInvocationExecution({- channelName,createSession,from: args.from,});