Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): channels - remove session-start hook polling (#2859)

Andrew Barba1ee8fa95a6ca
diff --git a/.changeset/tidy-rivers-return.md b/.changeset/tidy-rivers-return.md
new file mode 100644
index 000000000..724829d5d
--- /dev/null
+++ b/.changeset/tidy-rivers-return.md
@@ -0,0 +1,5 @@
+---
+"eve": minor
+---
+
+Session creation on eve, MCP, and authored channels now returns as soon as Workflow accepts the run. Concurrent first messages on one channel address are settled inside the workflow, racing `operationId` requests may return different candidate IDs that callers resolve after startup, and Workflow starts target known deployment IDs without resolving a latest-deployment sentinel.
diff --git a/docs/channels/custom.mdx b/docs/channels/custom.mdx
index 28f4655a2..990ad7734 100644
--- a/docs/channels/custom.mdx
+++ b/docs/channels/custom.mdx
@@ -82,6 +82,10 @@ part of the authored channel API.
Channel operations are dynamic: every call targets whichever session currently
owns the address. Only `send()` can create a session when the address is unowned.
+Cold-start sends return their accepted candidate without waiting for address
+ownership. If simultaneous sends race, eve forwards the losing candidate's
+message to the winner; resolve the address after startup when you need a fixed
+handle to the canonical owner.
```ts
const source = from(threadId);
diff --git a/docs/channels/eve.mdx b/docs/channels/eve.mdx
index a94c05dfc..c6867589e 100644
--- a/docs/channels/eve.mdx
+++ b/docs/channels/eve.mdx
@@ -47,22 +47,26 @@ curl -X POST https://<deployment>/eve/v1/session \
# {"ok":true,"sessionId":"wrun_A","status":"accepted"}
```
-The `202` response means Workflow accepted the durable run. The command inbox may still be
-starting, so an immediate follow-up or control request can report that the session is not active.
-The event-stream client retries the brief window before the new run becomes readable.
+The `202` response means Workflow accepted the durable run. The route does not wait for command
+inbox or continuation-token ownership. The inbox may still be starting, so an immediate follow-up
+or control request can report that the session is not active. The event-stream client retries the
+brief window before the new run becomes readable.
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.
+create-once semantics. Once the operation owner is active, the same operation under the same
+authenticated principal returns that session instead of dispatching the input again. The create
+route does not wait for a concurrently starting request to publish ownership: simultaneous
+requests can receive different accepted candidate IDs, while only the candidate that claims the
+operation runs its first turn. Retry the operation after startup when you need its canonical
+session ID. 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
+# {"ok":true,"sessionId":"wrun_A","status":"accepted"}
```
The first request requires `message`. A follow-up request accepts exactly one of
diff --git a/docs/channels/mcp.mdx b/docs/channels/mcp.mdx
index 7b4f98669..d7f93a294 100644
--- a/docs/channels/mcp.mdx
+++ b/docs/channels/mcp.mdx
@@ -171,7 +171,10 @@ MCP clients receive four tools:
| `agent_update` | `{ invocationId, responses }` | Answer the complete pending human-input batch. |
| `agent_cancel` | `{ invocationId }` | Request cooperative cancellation of non-terminal work. |
-`agent_start` creates one task-mode eve session and returns after durable acceptance. Keep its `invocationId`, then call `agent_get` until the invocation reaches a terminal state. While the status is `working`, wait at least `pollAfterMs` before polling again.
+`agent_start` creates one task-mode eve session and returns after durable acceptance without
+waiting for the session continuation hook to become readable. Keep its `invocationId`, then call
+`agent_get` until the invocation reaches a terminal state. While the status is `working`, wait at
+least `pollAfterMs` before polling again.
The invocation response is discriminated by `status`:
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.ts
index 6e3faad9e..07ff794c9 100644
--- 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.ts
@@ -1,5 +1,5 @@
import { defineEval, type EveEvalTargetHandle } from "eve/evals";
-import { equals, satisfies } from "eve/evals/expect";
+import { satisfies } from "eve/evals/expect";
interface CreateSessionResponse {
readonly ok: true;
@@ -12,7 +12,7 @@ const PRINCIPAL_B = "Bearer e2e-create-once-b";
export default defineEval({
description:
- "Concurrent and serial create retries dispatch once and remain isolated across issuers.",
+ "Concurrent create candidates converge on one owner, serial retries resolve it, and issuers remain isolated.",
async test(t) {
const operationId = `session-create-idempotency-${crypto.randomUUID()}`;
const message = `CREATE-ONCE-INITIAL-${crypto.randomUUID()}`;
@@ -20,22 +20,33 @@ export default defineEval({
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));
+ const acceptedCandidates = new Set([first.sessionId, concurrent.sessionId]);
+ let replay: CreateSessionResponse | undefined;
+ for (const delayMs of [100, 200, 400, 800, 1_600]) {
+ await t.sleep(delayMs);
+ const retry = await createSession(t.target, PRINCIPAL_A, operationId, message);
+ if (acceptedCandidates.has(retry.sessionId)) {
+ replay = retry;
+ break;
+ }
+ acceptedCandidates.add(retry.sessionId);
+ }
+ if (replay === undefined) {
+ throw new Error("The operation owner was not resolvable after startup.");
}
+
+ const otherIssuer = await createSession(t.target, PRINCIPAL_B, operationId, message);
await t.require(
otherIssuer,
satisfies(
- (value: CreateSessionResponse) => value.sessionId !== first.sessionId,
+ (value: CreateSessionResponse) => value.sessionId !== replay.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(replay.sessionId).result(),
t.target.watchTurn(otherIssuer.sessionId).result(),
]);
firstTurn.expectOk();
@@ -46,8 +57,10 @@ export default defineEval({
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 liveProbe = t.target.watchTurn(firstTurn.sessionId, {
+ startIndex: firstTurn.events.length,
+ });
+ await continueSession(t.target, PRINCIPAL_A, firstTurn.sessionId, probe);
const probeTurn = await liveProbe.result();
probeTurn.expectOk();
probeTurn.event("message.received", { count: 1, data: { message: probe } });
diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/redeploy.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/redeploy.eval.ts
index e9300aec3..9a1e8cd89 100644
--- a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/redeploy.eval.ts
+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/redeploy.eval.ts
@@ -13,15 +13,9 @@ import type { EveEvalContext } from "eve/evals";
// each redeploy repoints the alias, so the runner's client — and the durable
// session it drives — lands on the new deployment without any URL swap.
//
-// Deployment adoption is dispatch-dependent. Turn dispatch routes parked
-// sessions' turns to the latest deployment only where the workflow world can
-// resolve "latest" (production; branch-carrying previews). Branch-less CLI
-// preview deploys — which is what this eval pushes — pin turn execution to
-// the deployment that created the session (see shouldRouteToLatestDeployment
-// in execution/workflow-runtime.ts). The timeline below asserts exactly the
-// preview contract; the pinned-turn gate at t3 is a deliberate tripwire that
-// must be flipped when dispatch gains preview latest-routing
-// (https://github.com/vercel/eve/issues/582).
+// Each inbound request stamps the exact deployment that accepted it. The
+// parked driver dispatches that request's turn to the stamped deployment, so
+// repointing the alias adopts new code without resolving a "latest" sentinel.
//
// Timeline under test:
// t0 session A writes a file into its sandbox workspace
@@ -32,9 +26,8 @@ import type { EveEvalContext } from "eve/evals";
// t1' push a deployment update that adds a skill — skills materialize into
// the sandbox workspace resources, so the sandbox version hash rotates
// for anything executing the new code
-// t3 session A still sees the file: its turns are pinned to the original
-// deployment on preview, so neither the new manifest nor the rotated
-// sandbox key applies to it
+// t3 session A no longer sees the file: its next request runs on the new
+// deployment, whose changed sandbox resources rotate the sandbox key
// t4 a NEW session B adopts the new deployment: the added skill loads and
// shapes the reply
//
@@ -43,6 +36,7 @@ import type { EveEvalContext } from "eve/evals";
// everywhere else.
const ALIAS_ENV = "EVE_E2E_REDEPLOY_ALIAS";
+const ALIAS_SETTLE_MATCHES = 5;
const FILE_PATH = "/workspace/redeploy-note.txt";
const FILE_TOKEN = "sandbox-redeploy-ok-K4W";
@@ -72,7 +66,7 @@ const EXEC_OPTIONS = { maxBuffer: 64 * 1024 * 1024 } as const;
export default defineEval({
description:
- "Sandbox: a parked session survives redeploys with its workspace intact (pinned on preview), and new sessions adopt the new deployment.",
+ "Sandbox: a parked session adopts request-serving deployments, preserving or rotating its workspace according to the sandbox version.",
tags: ["redeploy"],
timeoutMs: 20 * 60_000,
async test(t) {
@@ -119,18 +113,15 @@ export default defineEval({
await deployToAlias(t, alias, "skill");
await waitForAliasToServe(t, `"${SKILL_NAME}"`);
- // t3: TRIPWIRE — on preview, session A's turns stay pinned to the
- // deployment that created it, so its sandbox key never rotates and the
- // file is still present. When turn dispatch gains preview
- // latest-routing (issue #582), this gate flips to /absent/ (and the
- // skill becomes loadable in session A too).
+ // t3: the next request is accepted by the new deployment. Its changed
+ // sandbox resources rotate the versioned key, so the old file is absent.
const probe = await t.send(
`Run the bash command \`test -f ${FILE_PATH} && echo present || echo absent\` ` +
"and reply with the command output verbatim.",
);
probe.expectOk();
- probe.calledTool("bash", { output: /present/ });
- probe.messageIncludes("present");
+ probe.calledTool("bash", { output: /absent/ });
+ probe.messageIncludes("absent");
// t4: a fresh session adopts the new deployment — the added skill is
// advertised and usable.
@@ -191,15 +182,22 @@ async function deployToAlias(t: EveEvalContext, alias: string, phase: string): P
}
/**
- * Polls `/eve/v1/info` until the alias serves a deployment whose manifest
- * contains `marker`, so post-redeploy turns cannot hit a stale deployment.
+ * Polls `/eve/v1/info` until the alias repeatedly serves a deployment whose
+ * manifest contains `marker`. One matching response is insufficient while an
+ * alias update is propagating and could race the next request.
*/
async function waitForAliasToServe(t: EveEvalContext, marker: string): Promise<void> {
const deadline = Date.now() + 120_000;
+ let consecutiveMatches = 0;
while (Date.now() < deadline) {
- const response = await t.target.fetch("/eve/v1/info");
+ const response = await t.target.fetch("/eve/v1/info", { cache: "no-store" });
if (response.ok && JSON.stringify(await response.json()).includes(marker)) {
- return;
+ consecutiveMatches += 1;
+ if (consecutiveMatches >= ALIAS_SETTLE_MATCHES) {
+ return;
+ }
+ } else {
+ consecutiveMatches = 0;
}
await t.sleep(1_000);
}
diff --git a/packages/eve/src/channel/channel-address.test.ts b/packages/eve/src/channel/channel-address.test.ts
index af8336d72..a8cc3808d 100644
--- a/packages/eve/src/channel/channel-address.test.ts
+++ b/packages/eve/src/channel/channel-address.test.ts
@@ -148,6 +148,10 @@ describe("createChannelAddress", () => {
expect.objectContaining({
adapter: expect.objectContaining({ state: { channelId: "C1", threadTs: "T1" } }),
capabilities: { requestInput: true },
+ continuationConflictCommand: expect.objectContaining({
+ kind: "send",
+ payload: { message: "hello" },
+ }),
}),
);
const created = vi.mocked(runtime.createSession).mock.calls[0]?.[0].adapter;
diff --git a/packages/eve/src/channel/channel-address.ts b/packages/eve/src/channel/channel-address.ts
index 17cbc2b7c..4e9df5d57 100644
--- a/packages/eve/src/channel/channel-address.ts
+++ b/packages/eve/src/channel/channel-address.ts
@@ -22,7 +22,6 @@ import type {
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";
@@ -145,6 +144,7 @@ export function createChannelAddress<TState = undefined>(input: {
capabilities,
callback: options.callback,
channelName: input.channelName,
+ continuationConflictCommand: command,
continuationToken: namespacedToken,
delivery,
initiatorAuth: options.initiatorAuth,
@@ -157,18 +157,11 @@ export function createChannelAddress<TState = undefined>(input: {
requestId: metadata.requestId,
title: options.title,
};
- try {
- const handle = await input.runtime.createSession(runInput);
- return createSession(handle.sessionId, input.runtime, {
- ...metadata,
- turnPolicy: input.turnPolicy,
- });
- } catch (error) {
- if (!isRuntimeSessionOwnershipConflictError(error)) throw error;
- const winner = await dispatch();
- if (winner !== undefined) return winner;
- throw error;
- }
+ const handle = await input.runtime.createSession(runInput);
+ return createSession(handle.sessionId, input.runtime, {
+ ...metadata,
+ turnPolicy: input.turnPolicy,
+ });
},
async send(message, options) {
return await this.deliver({ message }, options);
diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.ts
index 80ef1d95e..b33fea57a 100644
--- a/packages/eve/src/channel/types.ts
+++ b/packages/eve/src/channel/types.ts
@@ -483,6 +483,14 @@ export interface RunInput {
* transports omit this field.
*/
readonly continuationToken?: string;
+ /**
+ * Framework-owned delivery to forward when another run wins the initial
+ * continuation-token claim. Channel addresses set this so concurrent cold
+ * starts preserve every distinct inbound message inside durable execution.
+ * Create-once and replay-idempotent starts omit it so losing inputs are
+ * discarded.
+ */
+ readonly continuationConflictCommand?: Extract<SessionCommand, { readonly kind: "send" }>;
/**
* The original (top-level) caller's auth, forwarded down the delegation
* chain so the child's `session.auth.initiator` always resolves back to
diff --git a/packages/eve/src/eve-channel/index.ts b/packages/eve/src/eve-channel/index.ts
index d89a90f8e..77e8ff88d 100644
--- a/packages/eve/src/eve-channel/index.ts
+++ b/packages/eve/src/eve-channel/index.ts
@@ -1,7 +1,6 @@
import type { SessionAuthContext, SessionTraceContext } from "#channel/types.js";
import type { Session } from "#channel/session.js";
import { resolveForwardedPrincipal } from "#channel/forwarded-principal.js";
-import { isRuntimeSessionOwnershipConflictError } from "#execution/runtime-errors.js";
import {
handleConnectionCallbackRequest,
handleLegacyConnectionCallbackRequest,
@@ -268,20 +267,6 @@ export function eveChannel(input: EveChannelInput): EveChannel {
title: messageResult.title,
});
} 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 },
diff --git a/packages/eve/src/execution/continuation-conflict-step.test.ts b/packages/eve/src/execution/continuation-conflict-step.test.ts
new file mode 100644
index 000000000..52d5d8309
--- /dev/null
+++ b/packages/eve/src/execution/continuation-conflict-step.test.ts
@@ -0,0 +1,103 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";
+import { settleContinuationConflictStep } from "#execution/continuation-conflict-step.js";
+import { sessionCommandHookToken } from "#execution/session-command-token.js";
+
+const cancelRunMock = vi.fn();
+const getHookByTokenMock = vi.fn();
+const getWorldMock = vi.fn();
+const resumeSessionInboxMock = vi.fn();
+
+vi.mock("#execution/wire/session-inbox-resume.js", () => ({
+ resumeSessionInbox: (...args: unknown[]) => resumeSessionInboxMock(...args),
+}));
+
+vi.mock("#internal/workflow/runtime.js", () => ({
+ cancelRun: (...args: unknown[]) => cancelRunMock(...args),
+ getHookByToken: (...args: unknown[]) => getHookByTokenMock(...args),
+ getWorld: (...args: unknown[]) => getWorldMock(...args),
+}));
+
+const command = {
+ auth: null,
+ kind: "send" as const,
+ payload: { message: "preserve me" },
+ requestId: "request-1",
+};
+
+describe("settleContinuationConflictStep", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getWorldMock.mockResolvedValue("world");
+ resumeSessionInboxMock.mockResolvedValue({ runId: "wrun_owner" });
+ cancelRunMock.mockResolvedValue(undefined);
+ });
+
+ it("forwards a losing channel delivery and retires its activity collector", async () => {
+ await settleContinuationConflictStep({
+ activityCollectorRunId: "wrun_collector",
+ command,
+ continuationToken: "slack:C1:T1",
+ ownerSessionId: "wrun_owner",
+ });
+
+ expect(resumeSessionInboxMock).toHaveBeenCalledWith("slack:C1:T1", command);
+ expect(cancelRunMock).toHaveBeenCalledWith("world", "wrun_collector", {
+ cancelReason: "Session candidate did not acquire continuation ownership",
+ });
+ });
+
+ it("falls back to the winner's stable inbox after the alias is re-keyed", async () => {
+ resumeSessionInboxMock
+ .mockRejectedValueOnce(new HookNotFoundError("slack:C1:T1"))
+ .mockResolvedValueOnce({ runId: "wrun_owner" });
+
+ await settleContinuationConflictStep({
+ command,
+ continuationToken: "slack:C1:T1",
+ ownerSessionId: "wrun_owner",
+ });
+
+ expect(resumeSessionInboxMock).toHaveBeenNthCalledWith(1, "slack:C1:T1", command);
+ expect(resumeSessionInboxMock).toHaveBeenNthCalledWith(
+ 2,
+ sessionCommandHookToken("wrun_owner"),
+ command,
+ );
+ });
+
+ it("resolves a legacy conflict's owner once before using its stable inbox", async () => {
+ resumeSessionInboxMock
+ .mockRejectedValueOnce(new HookNotFoundError("slack:C1:T1"))
+ .mockResolvedValueOnce({ runId: "wrun_owner" });
+ getHookByTokenMock.mockResolvedValue({ runId: "wrun_owner" });
+
+ await settleContinuationConflictStep({
+ command,
+ continuationToken: "slack:C1:T1",
+ });
+
+ expect(getHookByTokenMock).toHaveBeenCalledOnce();
+ expect(getHookByTokenMock).toHaveBeenCalledWith("slack:C1:T1");
+ expect(resumeSessionInboxMock).toHaveBeenNthCalledWith(
+ 2,
+ sessionCommandHookToken("wrun_owner"),
+ command,
+ );
+ });
+
+ it("identifies a legacy delivery whose owner can no longer be resolved", async () => {
+ resumeSessionInboxMock.mockRejectedValue(new HookNotFoundError("slack:C1:T1"));
+ getHookByTokenMock.mockRejectedValue(new HookNotFoundError("slack:C1:T1"));
+
+ await expect(
+ settleContinuationConflictStep({
+ command,
+ continuationToken: "slack:C1:T1",
+ }),
+ ).rejects.toThrow(
+ 'Unable to forward losing candidate delivery "request-1": continuation owner could not be resolved.',
+ );
+ });
+});
diff --git a/packages/eve/src/execution/continuation-conflict-step.ts b/packages/eve/src/execution/continuation-conflict-step.ts
new file mode 100644
index 000000000..2751fbd23
--- /dev/null
+++ b/packages/eve/src/execution/continuation-conflict-step.ts
@@ -0,0 +1,94 @@
+import {
+ EntityConflictError,
+ HookNotFoundError,
+ RunExpiredError,
+ WorkflowRunNotFoundError,
+} from "#compiled/@workflow/errors/index.js";
+
+import type { SessionCommand } from "#channel/types.js";
+import { sessionCommandHookToken } from "#execution/session-command-token.js";
+import { resumeSessionInbox } from "#execution/wire/session-inbox-resume.js";
+import { cancelRun, getHookByToken, getWorld } from "#internal/workflow/runtime.js";
+import { walkCauseChain } from "#shared/errors.js";
+
+/** Settles side effects owned by a session candidate that lost its continuation claim. */
+export async function settleContinuationConflictStep(input: {
+ readonly activityCollectorRunId?: string;
+ readonly command?: Extract<SessionCommand, { readonly kind: "send" }>;
+ readonly continuationToken: string;
+ readonly ownerSessionId?: string;
+}): Promise<void> {
+ "use step";
+
+ try {
+ if (input.command !== undefined) {
+ await forwardCommand({
+ command: input.command,
+ continuationToken: input.continuationToken,
+ ownerSessionId: input.ownerSessionId,
+ });
+ }
+ } finally {
+ if (input.activityCollectorRunId !== undefined) {
+ await cancelCollector(input.activityCollectorRunId);
+ }
+ }
+}
+
+async function forwardCommand(input: {
+ readonly command: Extract<SessionCommand, { readonly kind: "send" }>;
+ readonly continuationToken: string;
+ readonly ownerSessionId?: string;
+}): Promise<void> {
+ try {
+ await resumeSessionInbox(input.continuationToken, input.command);
+ } catch (error) {
+ if (!HookNotFoundError.is(error)) throw error;
+ const ownerSessionId = await resolveOwnerSessionId(input);
+ await resumeSessionInbox(sessionCommandHookToken(ownerSessionId), input.command);
+ }
+}
+
+async function resolveOwnerSessionId(input: {
+ readonly command: Extract<SessionCommand, { readonly kind: "send" }>;
+ readonly continuationToken: string;
+ readonly ownerSessionId?: string;
+}): Promise<string> {
+ if (input.ownerSessionId !== undefined) return input.ownerSessionId;
+
+ try {
+ const hook = await getHookByToken(input.continuationToken);
+ if (typeof hook.runId === "string" && hook.runId.length > 0) return hook.runId;
+ } catch (error) {
+ if (!HookNotFoundError.is(error)) throw error;
+ }
+
+ const delivery =
+ input.command.requestId === undefined ? "" : ` ${JSON.stringify(input.command.requestId)}`;
+ throw new Error(
+ `Unable to forward losing candidate delivery${delivery}: continuation owner could not be resolved.`,
+ );
+}
+
+async function cancelCollector(runId: string): Promise<void> {
+ try {
+ await cancelRun(await getWorld(), runId, {
+ cancelReason: "Session candidate did not acquire continuation ownership",
+ });
+ } catch (error) {
+ if (!isInactiveRun(error)) throw error;
+ }
+}
+
+function isInactiveRun(error: unknown): boolean {
+ for (const candidate of walkCauseChain(error)) {
+ if (
+ WorkflowRunNotFoundError.is(candidate) ||
+ RunExpiredError.is(candidate) ||
+ EntityConflictError.is(candidate)
+ ) {
+ return true;
+ }
+ }
+ return false;
+}
diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts
index 24f46663b..19c47e1c3 100644
--- a/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts
+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts
@@ -5,7 +5,6 @@ import type { SessionAuthContext } from "#channel/types.js";
import type { ChannelAudience } from "#shared/channel-audience.js";
import { ContextContainer, loadContext } from "#context/container.js";
import { RemoteAgentContinueRequestError } from "#execution/remote-agent-dispatch.js";
-import { RuntimeSessionOwnershipConflictError } from "#execution/runtime-errors.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
import { dispatchRuntimeActionsStep } from "#execution/dispatch-runtime-actions-step.js";
import { prepareAgentActionDispatch } from "#execution/dispatch-runtime-actions-shared.js";
@@ -58,7 +57,8 @@ const mocks = vi.hoisted(() => ({
resumeHook: vi.fn(),
createSession: vi.fn(),
startRemoteAgentSession: vi.fn(),
- startWorkflowPreferLatest: vi.fn(),
+ startWorkflowOnCurrentDeployment: vi.fn(),
+ waitForCommandHookOwner: vi.fn(),
}));
vi.mock("#context/serialize.js", () => ({
@@ -86,9 +86,9 @@ vi.mock("#execution/workflow-runtime.js", () => ({
dispatchSession: mocks.dispatchSession,
}),
workflowEntryReference: { workflowId: "workflow//eve//workflowEntry" },
- startWorkflowPreferLatest: mocks.startWorkflowPreferLatest,
+ startWorkflowOnCurrentDeployment: mocks.startWorkflowOnCurrentDeployment,
taskRunWorkflowReference: { workflowId: "workflow//eve//taskRun" },
- waitForCommandHookOwner: vi.fn().mockResolvedValue({ runId: "task-run-1" }),
+ waitForCommandHookOwner: mocks.waitForCommandHookOwner,
}));
// Only the network calls are mocked; error classification and registry
@@ -169,12 +169,15 @@ const REMOTE_REGISTRY_DEFINITION = {
beforeEach(() => {
vi.clearAllMocks();
mocks.createSession.mockResolvedValue({ sessionId: CHILD_SESSION_ID });
+ mocks.waitForCommandHookOwner.mockImplementation(async (token: string) => ({
+ runId: token.startsWith("subagent:") ? CHILD_SESSION_ID : "task-run-1",
+ }));
mocks.dispatchSession.mockResolvedValue({ sessionId: CHILD_SESSION_ID, status: "accepted" });
mocks.continueRemoteAgentSession.mockResolvedValue(undefined);
mocks.startRemoteAgentSession.mockResolvedValue({
sessionId: "remote-session-123456789012",
});
- mocks.startWorkflowPreferLatest.mockResolvedValue({ runId: "task-run-1" });
+ mocks.startWorkflowOnCurrentDeployment.mockResolvedValue({ runId: "task-run-1" });
mocks.resumeHook.mockResolvedValue({ runId: "task-run-1" });
mocks.hydrateDurableSession.mockImplementation(({ durable }) => durable);
mocks.createDurableSessionState.mockImplementation(({ session }) => ({
@@ -642,13 +645,7 @@ describe("dispatchRuntimeActionsStep child starts", () => {
});
// A retried dispatch step re-derives the same deterministic child
// continuation token, so the first attempt's child owns it.
- mocks.createSession.mockRejectedValue(
- new RuntimeSessionOwnershipConflictError({
- continuationToken: "subagent:parent-session:call-1",
- ownerSessionId: CHILD_SESSION_ID,
- sessionId: "duplicate-child",
- }),
- );
+ mocks.createSession.mockResolvedValue({ sessionId: "duplicate-child" });
const result = await dispatchRuntimeActionsStep({
parentContinuationToken: "turn-inbox",
@@ -697,13 +694,7 @@ describe("dispatchRuntimeActionsStep child starts", () => {
});
// A retried dispatch step re-derives the same deterministic child
// continuation token, so the first attempt's child owns it.
- mocks.createSession.mockRejectedValue(
- new RuntimeSessionOwnershipConflictError({
- continuationToken: "subagent:parent-session:call-1",
- ownerSessionId: CHILD_SESSION_ID,
- sessionId: "duplicate-child",
- }),
- );
+ mocks.createSession.mockResolvedValue({ sessionId: "duplicate-child" });
const result = await dispatchRuntimeActionsStep({
parentContinuationToken: "turn-inbox",
@@ -963,7 +954,7 @@ describe("dispatchRuntimeActionsStep agent delivery", () => {
output: { code: "AGENT_BUSY", message: expect.stringContaining("task_active") },
});
expect(mocks.dispatchSession).not.toHaveBeenCalled();
- expect(mocks.startWorkflowPreferLatest).not.toHaveBeenCalled();
+ expect(mocks.startWorkflowOnCurrentDeployment).not.toHaveBeenCalled();
});
it("passes the active turn principal to a tasks-mode continuation", async () => {
diff --git a/packages/eve/src/execution/dispatch-turn-step.ts b/packages/eve/src/execution/dispatch-turn-step.ts
index 520386436..2f0ed8a8c 100644
--- a/packages/eve/src/execution/dispatch-turn-step.ts
+++ b/packages/eve/src/execution/dispatch-turn-step.ts
@@ -5,7 +5,7 @@ import {
import { readAcceptedDeploymentId } from "#execution/accepted-delivery-deployment.js";
import { buildTurnAttributes, readRootSessionId } from "#execution/eve-workflow-attributes.js";
import {
- startWorkflowPreferAcceptedDeployment,
+ startWorkflowOnAcceptedDeployment,
turnWorkflowReference,
} from "#execution/workflow-runtime.js";
import { normalizeEveAttributes } from "#runtime/attributes/normalize.js";
@@ -16,7 +16,7 @@ export async function dispatchTurnStep(
): Promise<{ readonly runId: string }> {
"use step";
- const run = await startWorkflowPreferAcceptedDeployment(
+ const run = await startWorkflowOnAcceptedDeployment(
turnWorkflowReference,
[createTurnWorkflowInput(input)],
readAcceptedDeploymentId(input.delivery),
diff --git a/packages/eve/src/execution/next-driver-action.ts b/packages/eve/src/execution/next-driver-action.ts
index 5b339a3dc..62c2010d7 100644
--- a/packages/eve/src/execution/next-driver-action.ts
+++ b/packages/eve/src/execution/next-driver-action.ts
@@ -1,7 +1,8 @@
/**
- * Closed-contract dispatch surface between session-mutating step
- * bodies (latest deployment) and the durable driver workflow (pinned
- * to whichever deployment called `start()`).
+ * Closed-contract dispatch surface between session-mutating step bodies
+ * (the accepting deployment when stamped, otherwise the driver's deployment)
+ * and the durable driver workflow (pinned to whichever deployment called
+ * `start()`).
*
* The driver matches on `kind` and follows a fixed playbook per arm.
* Adding a new arm is breaking (pinned drivers can't dispatch an
@@ -24,7 +25,7 @@ interface DurableStepResultFields {
readonly sessionState: DurableSessionState;
}
-/** Result returned by the latest turn step to its durable driver workflow. */
+/** Result returned by a turn step to its durable driver workflow. */
export type DurableStepResult = (
| {
readonly action: "continue" | "done";
diff --git a/packages/eve/src/execution/runtime-errors.ts b/packages/eve/src/execution/runtime-errors.ts
index e5026bdaa..37a8decc0 100644
--- a/packages/eve/src/execution/runtime-errors.ts
+++ b/packages/eve/src/execution/runtime-errors.ts
@@ -21,31 +21,3 @@ export function isRuntimeNoActiveSessionError(
): error is RuntimeNoActiveSessionError {
return error instanceof RuntimeNoActiveSessionError;
}
-
-/** Signals that another session won a concurrent channel-address claim. */
-export class RuntimeSessionOwnershipConflictError extends Error {
- readonly continuationToken: string;
- readonly ownerSessionId: string;
- readonly sessionId: string;
-
- constructor(input: {
- readonly continuationToken: string;
- readonly ownerSessionId: string;
- readonly sessionId: string;
- }) {
- super(
- `Session "${input.sessionId}" lost continuationToken "${input.continuationToken}" ` +
- `to session "${input.ownerSessionId}".`,
- );
- this.name = "RuntimeSessionOwnershipConflictError";
- this.continuationToken = input.continuationToken;
- this.ownerSessionId = input.ownerSessionId;
- this.sessionId = input.sessionId;
- }
-}
-
-export function isRuntimeSessionOwnershipConflictError(
- error: unknown,
-): error is RuntimeSessionOwnershipConflictError {
- return error instanceof RuntimeSessionOwnershipConflictError;
-}
diff --git a/packages/eve/src/execution/session-timeout-steps.ts b/packages/eve/src/execution/session-timeout-steps.ts
index a923b3f5b..3bcc951bb 100644
--- a/packages/eve/src/execution/session-timeout-steps.ts
+++ b/packages/eve/src/execution/session-timeout-steps.ts
@@ -6,7 +6,7 @@ import {
} from "#compiled/@workflow/errors/index.js";
import {
- startWorkflowPreferLatest,
+ startWorkflowOnCurrentDeployment,
sessionTimeoutWorkflowReference,
} from "#execution/workflow-runtime.js";
import type { SessionTimeoutWorkflowInput } from "#execution/session-timeout-workflow.js";
@@ -20,7 +20,7 @@ export async function startSessionTimeoutStep(
): Promise<{ readonly runId: string }> {
"use step";
- const run = await startWorkflowPreferLatest(sessionTimeoutWorkflowReference, [input]);
+ const run = await startWorkflowOnCurrentDeployment(sessionTimeoutWorkflowReference, [input]);
return { runId: run.runId };
}
diff --git a/packages/eve/src/execution/stable-workflow-names.ts b/packages/eve/src/execution/stable-workflow-names.ts
index eb74c46e7..c8bad2d60 100644
--- a/packages/eve/src/execution/stable-workflow-names.ts
+++ b/packages/eve/src/execution/stable-workflow-names.ts
@@ -1,7 +1,7 @@
/**
* eve workflow functions whose bundled id carries no `@<version>` stamp, so
- * `start(ref, args, { deploymentId: "latest" })` finds them on a newer
- * deployment. Dependency-free so the bundler can import it.
+ * an explicitly stamped deployment can find them across eve versions.
+ * Dependency-free so the bundler can import it.
*/
export const WORKFLOW_ENTRY_NAME = "workflowEntry";
export const TURN_WORKFLOW_NAME = "turnWorkflow";
diff --git a/packages/eve/src/execution/subagent-start-local.ts b/packages/eve/src/execution/subagent-start-local.ts
index 797601201..cf0403e33 100644
--- a/packages/eve/src/execution/subagent-start-local.ts
+++ b/packages/eve/src/execution/subagent-start-local.ts
@@ -3,9 +3,8 @@ import { ContextContainer, contextStorage } from "#context/container.js";
import type { LocalDevRequestProvenance } from "#context/keys.js";
import { deriveChildActivityObserverConfig } from "#execution/activity-work.js";
import { mintStartOperation } from "#execution/dispatch-start-operation.js";
-import { isRuntimeSessionOwnershipConflictError } from "#execution/runtime-errors.js";
import { buildSubagentRunInput, type SubagentInputSource } from "#execution/subagent-tool.js";
-import { createWorkflowRuntime } from "#execution/workflow-runtime.js";
+import { createWorkflowRuntime, waitForCommandHookOwner } from "#execution/workflow-runtime.js";
import { SUBAGENT_START_FAILED } from "#harness/agent-handle-errors.js";
import {
confirmAgentStarted,
@@ -99,42 +98,36 @@ export async function startLocalSubagent(input: {
let childSessionId: string;
try {
- const handle = await contextStorage.run(
- new ContextContainer({ localDevRequest: input.localDevRequest }),
- () => childRuntime.createSession(runInput),
+ await contextStorage.run(new ContextContainer({ localDevRequest: input.localDevRequest }), () =>
+ childRuntime.createSession(runInput),
);
- childSessionId = handle.sessionId;
+ // This runs inside the replayed dispatch step, which must persist the
+ // canonical child rather than the candidate accepted by start().
+ childSessionId = (await waitForCommandHookOwner(childContinuationToken)).runId;
} catch (error) {
- if (!isRuntimeSessionOwnershipConflictError(error)) {
- logError(log, "local subagent start failed", error, {
+ logError(log, "local subagent start failed", error, {
+ callId: action.callId,
+ nodeId: action.nodeId,
+ subagentName: action.subagentName,
+ });
+ return {
+ kind: "error",
+ result: {
callId: action.callId,
- nodeId: action.nodeId,
- subagentName: action.subagentName,
- });
- return {
- kind: "error",
- result: {
- callId: action.callId,
- isError: true,
- kind: "subagent-result",
- origin: "dispatch",
- output: {
- code: SUBAGENT_START_FAILED,
- message: toErrorMessage(error),
- },
- subagentName: action.subagentName,
+ isError: true,
+ kind: "subagent-result",
+ origin: "dispatch",
+ output: {
+ code: SUBAGENT_START_FAILED,
+ message: toErrorMessage(error),
},
- session: rejectAgentEffect(preparedSession, {
- disposition: "dead",
- operationId: operation.id,
- }),
- };
- }
- // A replayed step re-derives the same deterministic child continuation
- // token, so the run holding it is the child this operation already
- // started. Adopt it instead of failing live work and starting a second
- // child on the next attempt.
- childSessionId = error.ownerSessionId;
+ subagentName: action.subagentName,
+ },
+ session: rejectAgentEffect(preparedSession, {
+ disposition: "dead",
+ operationId: operation.id,
+ }),
+ };
}
const address = {
diff --git a/packages/eve/src/execution/tasks/parent/run-parent.ts b/packages/eve/src/execution/tasks/parent/run-parent.ts
index 690f35a0c..1130e6379 100644
--- a/packages/eve/src/execution/tasks/parent/run-parent.ts
+++ b/packages/eve/src/execution/tasks/parent/run-parent.ts
@@ -1,7 +1,7 @@
import type { TaskRunWorkflowInput } from "#execution/tasks/child/workflow.js";
import { isTaskWorkflowTargetGone } from "#execution/tasks/workflow-target.js";
import {
- startWorkflowPreferLatest,
+ startWorkflowOnCurrentDeployment,
taskRunWorkflowReference,
waitForCommandHookOwner,
} from "#execution/workflow-runtime.js";
@@ -29,7 +29,7 @@ const TASK_VIEW_READ_TIMEOUT_MS = 10_000;
/** Starts the durable run owning one task's lifecycle. */
export async function startTaskRun(input: TaskRunWorkflowInput): Promise<void> {
- await startWorkflowPreferLatest(taskRunWorkflowReference, [input]);
+ await startWorkflowOnCurrentDeployment(taskRunWorkflowReference, [input]);
}
/** Resolves the task run that won ownership of one replay-stable command token. */
diff --git a/packages/eve/src/execution/tool-run/start.ts b/packages/eve/src/execution/tool-run/start.ts
index b58c055bc..4caea61c1 100644
--- a/packages/eve/src/execution/tool-run/start.ts
+++ b/packages/eve/src/execution/tool-run/start.ts
@@ -1,6 +1,6 @@
import type { ToolRunWorkflowInput } from "#execution/tool-run/types.js";
import {
- startWorkflowPreferLatest,
+ startWorkflowOnCurrentDeployment,
toolRunWorkflowReference,
waitForCommandHookOwner,
} from "#execution/workflow-runtime.js";
@@ -26,7 +26,7 @@ export async function startToolRun(
parentTurnId: input.session.turn.id,
});
const workflowInput: ToolRunWorkflowInput = { ...input, hookToken };
- await startWorkflowPreferLatest(toolRunWorkflowReference, [workflowInput]);
+ await startWorkflowOnCurrentDeployment(toolRunWorkflowReference, [workflowInput]);
const owner = await waitForCommandHookOwner(hookToken);
return { hookToken, runId: owner.runId };
}
diff --git a/packages/eve/src/execution/workflow-entry.integration.test.ts b/packages/eve/src/execution/workflow-entry.integration.test.ts
index ebae01607..97094d1f1 100644
--- a/packages/eve/src/execution/workflow-entry.integration.test.ts
+++ b/packages/eve/src/execution/workflow-entry.integration.test.ts
@@ -1052,6 +1052,11 @@ describe("workflowEntry integration", () => {
const contender = await start(workflowEntry, [
{
+ continuationConflictCommand: {
+ auth: null,
+ kind: "send",
+ payload: { message: "contending message" },
+ },
input: { message: "contending message" },
serializedContext: buildSerializedContext({
channelKind: "http",
@@ -1062,11 +1067,6 @@ describe("workflowEntry integration", () => {
]);
try {
await expect(contender.returnValue).resolves.toEqual({ output: "" });
-
- await resumeHook(continuationToken, {
- kind: "send",
- payload: { message: "owner follow up" },
- });
const ownerFollowUp = await ownerStream.nextTurn();
expect(ownerFollowUp.at(-1)?.type).toBe("session.waiting");
@@ -1074,7 +1074,7 @@ describe("workflowEntry integration", () => {
ownerFollowUp.some(
(event) =>
event.type === "message.completed" &&
- event.data.message?.includes("owner follow up") === true,
+ event.data.message?.includes("contending message") === true,
),
).toBe(true);
} finally {
diff --git a/packages/eve/src/execution/workflow-entry.test.ts b/packages/eve/src/execution/workflow-entry.test.ts
index a395fe24d..a53757e12 100644
--- a/packages/eve/src/execution/workflow-entry.test.ts
+++ b/packages/eve/src/execution/workflow-entry.test.ts
@@ -29,6 +29,7 @@ import { settleCancelledTurnStep } from "#execution/settle-cancelled-turn-step.j
import { emitTerminalSessionFailureStep } from "#execution/terminal-session-failure-step.js";
import type { SessionInboxPayload } from "#execution/session-command-inbox.js";
import { sessionCommandHookToken } from "#execution/session-command-token.js";
+import { settleContinuationConflictStep } from "#execution/continuation-conflict-step.js";
vi.mock("#compiled/@workflow/core/index.js", () => ({
createHook: vi.fn(),
@@ -115,6 +116,10 @@ vi.mock("./session-timeout-control.js", () => ({
createSessionTimeoutControl: vi.fn(),
}));
+vi.mock("./continuation-conflict-step.js", () => ({
+ settleContinuationConflictStep: vi.fn().mockResolvedValue(undefined),
+}));
+
function createSessionStateForMock(
overrides: Partial<DurableSessionState> = {},
): DurableSessionState {
@@ -439,6 +444,12 @@ describe("workflowEntry", () => {
await expect(
workflowEntry({
+ activityCollectorRunId: "wrun_collector",
+ continuationConflictCommand: {
+ auth: null,
+ kind: "send",
+ payload: { message: "duplicate" },
+ },
input: { message: "duplicate" },
serializedContext: createSerializedContext(),
}),
@@ -447,6 +458,16 @@ describe("workflowEntry", () => {
expect(emitTerminalSessionFailureStep).not.toHaveBeenCalled();
expect(dispatchTurnStep).not.toHaveBeenCalled();
expect(dispose).toHaveBeenCalledOnce();
+ expect(settleContinuationConflictStep).toHaveBeenCalledWith({
+ activityCollectorRunId: "wrun_collector",
+ command: {
+ auth: null,
+ kind: "send",
+ payload: { message: "duplicate" },
+ },
+ continuationToken: "http:test",
+ ownerSessionId: "wrun_owner",
+ });
});
it("also exits when a legacy world reports the initial continuation conflict", async () => {
diff --git a/packages/eve/src/execution/workflow-entry.ts b/packages/eve/src/execution/workflow-entry.ts
index 44837a259..b3bcc757e 100644
--- a/packages/eve/src/execution/workflow-entry.ts
+++ b/packages/eve/src/execution/workflow-entry.ts
@@ -5,6 +5,7 @@ import type {
DeliverPayload,
HookPayload,
RunInput,
+ SessionCommand,
SessionCapabilities,
TurnCaller,
} from "#channel/types.js";
@@ -49,6 +50,7 @@ import { isTaskOwnedSerializedContext } from "#execution/tasks/child/instruction
import { attachClientContext, readClientContext } from "#internal/client-context.js";
import { CHANNEL_CONTEXT_KEY_NAME, SESSION_CALLBACK_CONTEXT_KEY_NAME } from "#context/key-names.js";
import { SUBAGENT_ADAPTER_KIND } from "#execution/subagent-adapter-state.js";
+import { settleContinuationConflictStep } from "#execution/continuation-conflict-step.js";
const SAFE_OUTER_WORKFLOW_FAILURE_MESSAGE =
"Agent workflow failed. Inspect the private session trace for details.";
@@ -63,6 +65,8 @@ const SAFE_OUTER_WORKFLOW_FAILURE_MESSAGE =
* and deserialized at each `"use step"` boundary.
*/
export interface WorkflowEntryInput {
+ readonly activityCollectorRunId?: string;
+ readonly continuationConflictCommand?: Extract<SessionCommand, { readonly kind: "send" }>;
readonly input: RunInput["input"];
readonly limits?: RunInput["limits"];
readonly sessionTimeoutMs?: number | false;
@@ -215,10 +219,25 @@ export async function workflowEntry(input: WorkflowEntryInput): Promise<Workflow
if (stableClaim.status === "rejected") throw stableClaim.reason;
if (authorizationClaim.status === "rejected") throw authorizationClaim.reason;
if (continuationClaim.status === "rejected") {
- // A concurrent create can start two candidate runs before either
- // publishes the shared continuation alias. The runtime adopts the
- // alias owner; the losing candidate exits before its first turn.
- if (isHookConflictError(continuationClaim.reason)) return { output: "" };
+ // Only the durable alias owner runs a first turn; a losing candidate
+ // hands its address delivery to that owner before exiting.
+ if (isHookConflictError(continuationClaim.reason)) {
+ if (
+ input.activityCollectorRunId !== undefined ||
+ input.continuationConflictCommand !== undefined
+ ) {
+ await settleContinuationConflictStep({
+ activityCollectorRunId: input.activityCollectorRunId,
+ command: input.continuationConflictCommand,
+ continuationToken,
+ ownerSessionId:
+ typeof continuationClaim.reason.conflictingRunId === "string"
+ ? continuationClaim.reason.conflictingRunId
+ : undefined,
+ });
+ }
+ return { output: "" };
+ }
throw continuationClaim.reason;
}
diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.ts
index 6292ac650..88ba76034 100644
--- a/packages/eve/src/execution/workflow-runtime.test.ts
+++ b/packages/eve/src/execution/workflow-runtime.test.ts
@@ -13,14 +13,12 @@ import { ChannelRequestIdKey, ActivityObserverKey } from "#context/keys.js";
import { resolveInstalledPackageInfo } from "#internal/application/package.js";
import {
createWorkflowRuntime,
- LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE,
activityCollectorWorkflowReference,
sessionTimeoutWorkflowReference,
- startWorkflowPreferLatest,
+ startWorkflowOnCurrentDeployment,
turnWorkflowReference,
workflowEntryReference,
} from "#execution/workflow-runtime.js";
-import { RuntimeSessionOwnershipConflictError } from "#execution/runtime-errors.js";
import { sessionCommandHookToken } from "#execution/session-command-token.js";
import { registerInstrumentationRuntime } from "#instrumentation/runtime.js";
import { AgentSpanIdGenerator } from "#tracing/agent-span-id-generator.js";
@@ -69,10 +67,9 @@ describe("workflowEntryReference", () => {
it("uses the installed eve package identity for the runtime workflow id", () => {
const packageInfo = resolveInstalledPackageInfo();
- // The runtime references intentionally omit the `@<pkg.version>`
- // stamp so cross-deployment routing (`start(ref, args, {
- // deploymentId: "latest" })`) finds the same workflow on a newer
- // deployment even when eve itself has been upgraded.
+ // The runtime references intentionally omit the `@<pkg.version>` stamp
+ // so an explicitly targeted deployment finds the same workflow even when
+ // eve itself has been upgraded.
expect(workflowEntryReference.workflowId).toBe(`workflow//${packageInfo.name}//workflowEntry`);
expect(workflowEntryReference.workflowId).not.toContain("/src/execution/");
expect(workflowEntryReference.workflowId).not.toContain("@");
@@ -90,7 +87,7 @@ describe("workflowEntryReference", () => {
});
});
-describe("startWorkflowPreferLatest", () => {
+describe("startWorkflowOnCurrentDeployment", () => {
it("detaches Workflow telemetry only from marked agent contexts", async () => {
const contextManager = new AsyncLocalStorageContextManager().enable();
apiContext.setGlobalContextManager(contextManager);
@@ -110,12 +107,12 @@ describe("startWorkflowPreferLatest", () => {
try {
await otelContext.with(callerContext, async () => {
expect(otelTrace.getSpan(otelContext.active())).toBe(caller);
- await startWorkflowPreferLatest(workflowEntryReference, []);
+ await startWorkflowOnCurrentDeployment(workflowEntryReference, []);
expect(otelTrace.getSpan(otelContext.active())).toBe(caller);
});
await otelContext.with(markAgentTraceContext(callerContext), async () => {
expect(otelTrace.getSpan(otelContext.active())).toBe(caller);
- await startWorkflowPreferLatest(workflowEntryReference, []);
+ await startWorkflowOnCurrentDeployment(workflowEntryReference, []);
expect(otelTrace.getSpan(otelContext.active())).toBe(caller);
});
} finally {
@@ -395,8 +392,8 @@ describe("createWorkflowRuntime#createSession", () => {
});
}
- it("starts workflowEntry on the latest deployment in Vercel production", async () => {
- vi.stubEnv("VERCEL_ENV", "production");
+ it("starts workflowEntry on the deployment accepting the request", async () => {
+ vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_current");
const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;
mockBundleAndRun(compiledArtifactsSource);
startMock.mockResolvedValue({ runId: "driver-run" });
@@ -430,7 +427,7 @@ describe("createWorkflowRuntime#createSession", () => {
"$eve.trigger": "http",
"$eve.type": "session",
},
- deploymentId: "latest",
+ deploymentId: "dpl_current",
},
);
});
@@ -452,24 +449,50 @@ describe("createWorkflowRuntime#createSession", () => {
expect(getHookByTokenMock).not.toHaveBeenCalled();
});
- it("waits only for continuation ownership when a token is supplied", async () => {
+ it("returns an MCP invocation without checking continuation ownership", async () => {
const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;
mockBundleAndRun(compiledArtifactsSource);
startMock.mockResolvedValue({ runId: "driver-run" });
- getHookByTokenMock.mockResolvedValue({ runId: "driver-run" });
await expect(
buildRuntime(compiledArtifactsSource).createSession({
adapter,
auth: null,
- continuationToken: "slack:thread",
+ continuationToken: "invocation:token",
+ externalInvocation: {
+ continuationToken: "invocation:token",
+ ownerKey: "owner",
+ },
input: { message: "hello" },
- mode: "conversation",
+ mode: "task",
}),
).resolves.toMatchObject({ sessionId: "driver-run" });
- expect(getHookByTokenMock).toHaveBeenCalledOnce();
- expect(getHookByTokenMock).toHaveBeenCalledWith("slack:thread");
+ expect(getHookByTokenMock).not.toHaveBeenCalled();
+ });
+
+ it("passes a channel's losing-candidate delivery to the workflow", async () => {
+ const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;
+ mockBundleAndRun(compiledArtifactsSource);
+ startMock.mockResolvedValue({ runId: "driver-run" });
+ const continuationConflictCommand = {
+ auth: null,
+ kind: "send" as const,
+ payload: { message: "hello" },
+ };
+
+ await buildRuntime(compiledArtifactsSource).createSession({
+ adapter,
+ auth: null,
+ continuationConflictCommand,
+ continuationToken: "slack:thread",
+ input: { message: "hello" },
+ mode: "conversation",
+ });
+
+ expect(startMock.mock.calls[0]?.[1][0]).toMatchObject({
+ continuationConflictCommand,
+ });
});
it("stores an explicit title alongside the trace-content policy", async () => {
@@ -535,6 +558,7 @@ describe("createWorkflowRuntime#createSession", () => {
});
expect(collectorInput.token).toHaveLength(43);
const workflowInput = startMock.mock.calls[1]?.[1][0];
+ expect(workflowInput.activityCollectorRunId).toBe("collector-run");
expect(workflowInput.serializedContext[ActivityObserverKey.name]).toEqual({
sink: {
url: `https://agent.example.com/eve/v1/activity/${collectorInput.token}`,
@@ -608,14 +632,12 @@ describe("createWorkflowRuntime#createSession", () => {
});
});
- it("cancels the collector when continuation ownership rejects the root candidate", async () => {
+ it("does not inspect continuation ownership after accepting a root candidate", async () => {
const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;
mockBundleAndRun(compiledArtifactsSource);
startMock
.mockResolvedValueOnce({ runId: "collector-run" })
.mockResolvedValueOnce({ runId: "driver-run" });
- getHookByTokenMock.mockResolvedValue({ runId: "other-run" });
-
await expect(
buildRuntime(compiledArtifactsSource).createSession({
adapter: activityAdapter(),
@@ -624,11 +646,10 @@ describe("createWorkflowRuntime#createSession", () => {
input: { message: "hello" },
mode: "conversation",
}),
- ).rejects.toBeInstanceOf(RuntimeSessionOwnershipConflictError);
+ ).resolves.toMatchObject({ sessionId: "driver-run" });
- expect(cancelRunMock).toHaveBeenCalledWith("world", "collector-run", {
- cancelReason: "Root session creation did not complete",
- });
+ expect(getHookByTokenMock).not.toHaveBeenCalled();
+ expect(cancelRunMock).not.toHaveBeenCalled();
});
it("serializes the selected dynamic subagent config for the child workflow", async () => {
@@ -665,7 +686,7 @@ describe("createWorkflowRuntime#createSession", () => {
});
it("serializes the channel request id into workflow context", async () => {
- vi.stubEnv("VERCEL_ENV", "production");
+ vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_current");
const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;
mockBundleAndRun(compiledArtifactsSource);
startMock.mockResolvedValue({ runId: "driver-run" });
@@ -698,7 +719,7 @@ describe("createWorkflowRuntime#createSession", () => {
"$eve.trigger": "http",
"$eve.type": "session",
},
- deploymentId: "latest",
+ deploymentId: "dpl_current",
},
);
});
@@ -747,13 +768,10 @@ describe("createWorkflowRuntime#createSession", () => {
});
});
- it("falls back to the current deployment when latest is unsupported", async () => {
- vi.stubEnv("VERCEL_ENV", "production");
+ it("lets the Workflow world provide its current deployment when Vercel has no id", async () => {
const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;
mockBundleAndRun(compiledArtifactsSource);
- startMock
- .mockRejectedValueOnce(new Error(LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE))
- .mockResolvedValueOnce({ runId: "driver-run" });
+ startMock.mockResolvedValue({ runId: "driver-run" });
await buildRuntime(compiledArtifactsSource).createSession({
adapter,
@@ -762,18 +780,8 @@ describe("createWorkflowRuntime#createSession", () => {
mode: "task",
});
- expect(startMock).toHaveBeenNthCalledWith(1, workflowEntryReference, expect.any(Array), {
- allowReservedAttributes: true,
- attributes: {
- "$eve.is_otel_trace_enabled": "false",
- "$eve.is_trace_content_visible": "false",
- "$eve.title": "hello",
- "$eve.trigger": "http",
- "$eve.type": "session",
- },
- deploymentId: "latest",
- });
- expect(startMock).toHaveBeenNthCalledWith(2, workflowEntryReference, expect.any(Array), {
+ expect(startMock).toHaveBeenCalledTimes(1);
+ expect(startMock).toHaveBeenCalledWith(workflowEntryReference, expect.any(Array), {
allowReservedAttributes: true,
attributes: {
"$eve.is_otel_trace_enabled": "false",
@@ -785,43 +793,6 @@ describe("createWorkflowRuntime#createSession", () => {
});
});
- it.each(["preview", "development", undefined])(
- "pins workflowEntry to the current deployment when VERCEL_ENV is %s",
- async (vercelEnv) => {
- // Preview and CLI deployments carry no git branch reference, so the
- // platform cannot resolve "latest" for them (HTTP 400). They must pin
- // to their own immutable deployment.
- if (vercelEnv === undefined) {
- vi.stubEnv("VERCEL_ENV", "");
- delete process.env.VERCEL_ENV;
- } else {
- vi.stubEnv("VERCEL_ENV", vercelEnv);
- }
- const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;
- mockBundleAndRun(compiledArtifactsSource);
- startMock.mockResolvedValue({ runId: "driver-run" });
-
- await buildRuntime(compiledArtifactsSource).createSession({
- adapter,
- auth: null,
- input: { message: "hello" },
- mode: "task",
- });
-
- expect(startMock).toHaveBeenCalledTimes(1);
- expect(startMock).toHaveBeenCalledWith(workflowEntryReference, expect.any(Array), {
- allowReservedAttributes: true,
- attributes: {
- "$eve.is_otel_trace_enabled": "false",
- "$eve.is_trace_content_visible": "false",
- "$eve.title": "hello",
- "$eve.trigger": "http",
- "$eve.type": "session",
- },
- });
- },
- );
-
it("does not open the workflow event stream until the events stream is read", async () => {
const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;
vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({
diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.ts
index a283cd15c..a83d56705 100644
--- a/packages/eve/src/execution/workflow-runtime.ts
+++ b/packages/eve/src/execution/workflow-runtime.ts
@@ -29,7 +29,6 @@ import {
readParentLineage,
} from "#execution/eve-workflow-attributes.js";
import { resolveInstalledPackageInfo } from "#internal/application/package.js";
-import { isEveDevEnvironment } from "#internal/application/dev-environment.js";
import { createLogger, logError } from "#internal/logging.js";
import {
cancelRun,
@@ -50,7 +49,6 @@ import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-
import { buildRunContext } from "#execution/runtime-context.js";
import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";
import { parseNdjsonStream } from "#execution/ndjson-stream.js";
-import { RuntimeSessionOwnershipConflictError } from "#execution/runtime-errors.js";
import type { WorkflowEntryInput } from "#execution/workflow-entry.js";
import type { ActivityCollectorInput } from "#execution/activity-collector.js";
import { createEveActivityRoutePath } from "#protocol/routes.js";
@@ -77,9 +75,6 @@ const EVE_PACKAGE_INFO = resolveInstalledPackageInfo();
const COMMAND_HOOK_READY_TIMEOUT_MS = 30_000;
const DEFAULT_ACTIVITY_COLLECTOR_RETENTION_MS = 24 * 60 * 60 * 1_000;
-export const LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE =
- "deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()";
-
const STABLE_ID_BASE = EVE_PACKAGE_INFO.name;
const log = createLogger("execution.workflow-runtime");
@@ -100,10 +95,9 @@ export const workflowEntryReference = {
/**
* Stable workflow reference used by the driver to dispatch per-turn
- * child workflow runs. The id omits the package version stamp so
- * `start(turnWorkflowReference, args, { deploymentId: "latest" })`
- * routes to the latest deployment's turn workflow even when the eve
- * version differs from the caller's deployment.
+ * child workflow runs. The id omits the package version stamp so an
+ * explicitly stamped accepting deployment can resolve the workflow even
+ * when its eve version differs from the driver's deployment.
*/
export const turnWorkflowReference = {
workflowId: `workflow//${STABLE_ID_BASE}//${TURN_WORKFLOW_NAME}`,
@@ -176,9 +170,10 @@ export function createWorkflowRuntime(config: {
token,
};
try {
- const collector = await startWorkflowPreferLatest(activityCollectorWorkflowReference, [
- collectorInput,
- ]);
+ const collector = await startWorkflowOnCurrentDeployment(
+ activityCollectorWorkflowReference,
+ [collectorInput],
+ );
collectorRunId = collector.runId;
const fallbackOrigin = process.env.VERCEL_URL
? `https://${process.env.VERCEL_URL}`
@@ -206,6 +201,12 @@ export function createWorkflowRuntime(config: {
limits: input.limits,
serializedContext,
};
+ if (collectorRunId !== undefined) {
+ workflowInput.activityCollectorRunId = collectorRunId;
+ }
+ if (input.continuationConflictCommand !== undefined) {
+ workflowInput.continuationConflictCommand = input.continuationConflictCommand;
+ }
if (sessionTimeoutMs !== undefined) {
workflowInput.sessionTimeoutMs = sessionTimeoutMs;
}
@@ -230,9 +231,9 @@ export function createWorkflowRuntime(config: {
: buildInvocationAttributes(input.externalInvocation)),
};
- let run: Awaited<ReturnType<typeof startWorkflowPreferLatest>>;
+ let run: Awaited<ReturnType<typeof startWorkflowOnCurrentDeployment>>;
try {
- run = await startWorkflowPreferLatest(workflowEntryReference, [workflowInput], {
+ run = await startWorkflowOnCurrentDeployment(workflowEntryReference, [workflowInput], {
allowReservedAttributes: true,
attributes: normalizeEveAttributes(attributes),
});
@@ -244,22 +245,6 @@ export function createWorkflowRuntime(config: {
throw error;
}
- if (input.continuationToken) {
- try {
- const owner = await waitForCommandHookOwner(input.continuationToken);
- if (owner.runId !== run.runId) {
- throw new RuntimeSessionOwnershipConflictError({
- continuationToken: input.continuationToken,
- ownerSessionId: owner.runId,
- sessionId: run.runId,
- });
- }
- } catch (error) {
- await cancelActivityCollector(collectorRunId);
- throw error;
- }
- }
-
let events: ReadableStream<MessageStreamEvent> | undefined;
const getEvents = () => {
events ??= parseNdjsonStream<MessageStreamEvent>(() => getRun(run.runId).getReadable());
@@ -411,6 +396,11 @@ function isInactiveCommandTarget(error: unknown): boolean {
return false;
}
+/**
+ * Resolves hook ownership for replay-idempotent work already running inside a
+ * durable step. Request handlers must return from start/resume acceptance and
+ * leave ownership arbitration to the workflow.
+ */
export async function waitForCommandHookOwner(token: string): Promise<WorkflowHookRecord> {
const deadline = Date.now() + COMMAND_HOOK_READY_TIMEOUT_MS;
while (true) {
@@ -441,58 +431,51 @@ async function waitForCommandHookRelease(token: string, sessionId: string): Prom
}
}
-/**
- * Starts a workflow on the latest deployment when latest routing applies,
- * while preserving local/dev worlds that do not implement latest routing.
- */
-export async function startWorkflowPreferLatest<TArgs extends unknown[], TResult>(
+/** Starts a workflow on the deployment executing this call. */
+export async function startWorkflowOnCurrentDeployment<TArgs extends unknown[], TResult>(
workflow: WorkflowFunction<TArgs, TResult> | WorkflowMetadata,
args: TArgs,
options?: StartOptionsWithoutDeploymentId,
): Promise<Run<unknown> | Run<TResult>> {
- return await withWorkflowStartContext(async () => {
- if (!shouldRouteToLatestDeployment()) {
- return options === undefined
- ? await start(workflow, args)
- : await start(workflow, args, options);
- }
-
- try {
- return await start(workflow, args, { ...options, deploymentId: "latest" });
- } catch (error) {
- if (!isLatestDeploymentUnsupportedError(error)) {
- throw error;
- }
-
- return options === undefined
- ? await start(workflow, args)
- : await start(workflow, args, options);
- }
- });
+ return await startWorkflowOnDeployment(
+ workflow,
+ args,
+ process.env.VERCEL_DEPLOYMENT_ID?.trim() || undefined,
+ options,
+ );
}
/**
- * Starts on the deployment that accepted a delivery when this step is running
- * there, otherwise preserves latest-deployment routing.
+ * Starts on the deployment that accepted a delivery when one was stamped,
+ * otherwise stays on the deployment executing this call.
*/
-export async function startWorkflowPreferAcceptedDeployment<TArgs extends unknown[], TResult>(
+export async function startWorkflowOnAcceptedDeployment<TArgs extends unknown[], TResult>(
workflow: WorkflowFunction<TArgs, TResult> | WorkflowMetadata,
args: TArgs,
acceptedDeploymentId: string | undefined,
options?: StartOptionsWithoutDeploymentId,
): Promise<Run<unknown> | Run<TResult>> {
- const currentDeploymentId = process.env.VERCEL_DEPLOYMENT_ID?.trim();
- if (
- acceptedDeploymentId === undefined ||
- currentDeploymentId === undefined ||
- acceptedDeploymentId !== currentDeploymentId
- ) {
- return await startWorkflowPreferLatest(workflow, args, options);
+ if (acceptedDeploymentId === undefined) {
+ return await startWorkflowOnCurrentDeployment(workflow, args, options);
}
- return await withWorkflowStartContext(
- async () => await start(workflow, args, { ...options, deploymentId: acceptedDeploymentId }),
- );
+ return await startWorkflowOnDeployment(workflow, args, acceptedDeploymentId, options);
+}
+
+async function startWorkflowOnDeployment<TArgs extends unknown[], TResult>(
+ workflow: WorkflowFunction<TArgs, TResult> | WorkflowMetadata,
+ args: TArgs,
+ deploymentId: string | undefined,
+ options?: StartOptionsWithoutDeploymentId,
+): Promise<Run<unknown> | Run<TResult>> {
+ return await withWorkflowStartContext(async () => {
+ if (deploymentId !== undefined) {
+ return await start(workflow, args, { ...options, deploymentId });
+ }
+ return options === undefined
+ ? await start(workflow, args)
+ : await start(workflow, args, options);
+ });
}
async function withWorkflowStartContext<TResult>(callback: () => Promise<TResult>) {
@@ -506,19 +489,6 @@ async function withWorkflowStartContext<TResult>(callback: () => Promise<TResult
return await context.with(workflowContext, callback);
}
-/**
- * Local development resolves "latest" to the active promoted generation.
- * Vercel resolves it only for production deployments; previews and CLI
- * deployments have no branch reference and remain pinned to themselves.
- */
-function shouldRouteToLatestDeployment(): boolean {
- return process.env.VERCEL_ENV === "production" || isEveDevEnvironment();
-}
-
-function isLatestDeploymentUnsupportedError(error: unknown): boolean {
- return error instanceof Error && error.message.includes(LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE);
-}
-
function normalizeWorkflowHook(value: unknown): WorkflowHookRecord {
if (value === null || typeof value !== "object" || !("runId" in value)) {
throw new Error("Workflow hook did not include a run id.");
diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.ts
index 7e0fc3c59..05b5cebb2 100644
--- a/packages/eve/src/execution/workflow-steps.test.ts
+++ b/packages/eve/src/execution/workflow-steps.test.ts
@@ -64,11 +64,7 @@ import { registerInstrumentationRuntime } from "#instrumentation/runtime.js";
import { resolveEffectiveOutputSchema } from "#execution/effective-output-schema.js";
import { turnStep } from "#execution/workflow-steps.js";
import { routeProxiedDeliverStep } from "#execution/proxied-deliver-step.js";
-import {
- LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE,
- turnWorkflowReference,
- workflowEntryReference,
-} from "#execution/workflow-runtime.js";
+import { turnWorkflowReference, workflowEntryReference } from "#execution/workflow-runtime.js";
const bindSessionInstrumentationSpy = vi.hoisted(() => vi.fn());
vi.mock("#instrumentation/runtime.js", async (importOriginal) => {
@@ -684,8 +680,8 @@ describe("dispatchTurnStep", () => {
};
}
- it("starts turn workflows on the latest deployment in Vercel production", async () => {
- vi.stubEnv("VERCEL_ENV", "production");
+ it("starts turn workflows on the current driver deployment without an ingress stamp", async () => {
+ vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_driver");
const input = createTurnInput();
startMock.mockResolvedValue({ runId: "turn-run" });
@@ -704,13 +700,12 @@ describe("dispatchTurnStep", () => {
"$eve.is_trace_content_visible": "false",
"$eve.type": "turn",
},
- deploymentId: "latest",
+ deploymentId: "dpl_driver",
},
);
});
it("starts on the accepted deployment when the dispatch step runs there", async () => {
- vi.stubEnv("VERCEL_ENV", "production");
vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_current");
const baseInput = createTurnInput();
const input = {
@@ -739,8 +734,7 @@ describe("dispatchTurnStep", () => {
);
});
- it("keeps latest routing for mixed accepted deployments", async () => {
- vi.stubEnv("VERCEL_ENV", "production");
+ it("stays on the driver deployment for mixed accepted deployments", async () => {
vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_current");
const baseInput = createTurnInput();
const input = {
@@ -772,11 +766,11 @@ describe("dispatchTurnStep", () => {
expect(startMock).toHaveBeenCalledWith(
turnWorkflowReference,
[createTurnWorkflowInput(input)],
- expect.objectContaining({ deploymentId: "latest" }),
+ expect.objectContaining({ deploymentId: "dpl_current" }),
);
});
- it("starts turn workflows on the latest promoted generation in local development", async () => {
+ it("lets the development world retain its stamped generation", async () => {
vi.stubEnv("EVE_DEV", "1");
const input = createTurnInput();
startMock.mockResolvedValue({ runId: "turn-run" });
@@ -786,7 +780,17 @@ describe("dispatchTurnStep", () => {
expect(startMock).toHaveBeenCalledWith(
turnWorkflowReference,
[createTurnWorkflowInput(input)],
- expect.objectContaining({ deploymentId: "latest" }),
+ {
+ allowReservedAttributes: true,
+ attributes: {
+ "$eve.channel_request_id": "req_turn",
+ "$eve.is_otel_trace_enabled": "false",
+ "$eve.parent": "sess-test",
+ "$eve.root": "sess-test",
+ "$eve.is_trace_content_visible": "true",
+ "$eve.type": "turn",
+ },
+ },
);
});
@@ -815,45 +819,50 @@ describe("dispatchTurnStep", () => {
);
});
- it("falls back to the current deployment when latest is unsupported", async () => {
- vi.stubEnv("VERCEL_ENV", "production");
- const input = createTurnInput();
- startMock
- .mockRejectedValueOnce(new Error(LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE))
- .mockResolvedValueOnce({ runId: "turn-run" });
+ it("targets a stamped accepting deployment even when the driver is older", async () => {
+ vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_driver");
+ const baseInput = createTurnInput();
+ const input = {
+ ...baseInput,
+ delivery: {
+ ...baseInput.delivery,
+ deliveryMetadata: [
+ {
+ acceptedDeploymentId: "dpl_ingress",
+ channelKind: "channel:webhook",
+ channelName: "webhook",
+ deliveryId: "delivery-1",
+ payloadIndex: 0,
+ },
+ ],
+ },
+ };
+ startMock.mockResolvedValue({ runId: "turn-run" });
await expect(dispatchTurnStep(input)).resolves.toEqual({ runId: "turn-run" });
- const wireInput = createTurnWorkflowInput(input);
- expect(startMock).toHaveBeenNthCalledWith(1, turnWorkflowReference, [wireInput], {
- allowReservedAttributes: true,
- attributes: {
- "$eve.channel_request_id": "req_turn",
- "$eve.is_otel_trace_enabled": "false",
- "$eve.parent": "sess-test",
- "$eve.root": "sess-test",
- "$eve.is_trace_content_visible": "false",
- "$eve.type": "turn",
- },
- deploymentId: "latest",
- });
- expect(startMock).toHaveBeenNthCalledWith(2, turnWorkflowReference, [wireInput], {
- allowReservedAttributes: true,
- attributes: {
- "$eve.channel_request_id": "req_turn",
- "$eve.is_otel_trace_enabled": "false",
- "$eve.parent": "sess-test",
- "$eve.root": "sess-test",
- "$eve.is_trace_content_visible": "false",
- "$eve.type": "turn",
+ expect(startMock).toHaveBeenCalledWith(
+ turnWorkflowReference,
+ [createTurnWorkflowInput(input)],
+ {
+ allowReservedAttributes: true,
+ attributes: {
+ "$eve.channel_request_id": "req_turn",
+ "$eve.is_otel_trace_enabled": "false",
+ "$eve.parent": "sess-test",
+ "$eve.root": "sess-test",
+ "$eve.is_trace_content_visible": "false",
+ "$eve.type": "turn",
+ },
+ deploymentId: "dpl_ingress",
},
- });
+ );
});
});
describe("dispatchRuntimeActionsStep", () => {
it("preserves a started local child when a later start fails", async () => {
- vi.stubEnv("VERCEL_ENV", "production");
+ vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_driver");
const compiledArtifactsSource = {} as never;
const compiledBundle = {
adapterRegistry: {
@@ -998,7 +1007,7 @@ describe("dispatchRuntimeActionsStep", () => {
"$eve.root": "root-session",
"$eve.type": "subagent",
}),
- deploymentId: "latest",
+ deploymentId: "dpl_driver",
},
);
expect(startMock).toHaveBeenCalledWith(
diff --git a/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts b/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts
index 06834035f..2535eef29 100644
--- a/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts
+++ b/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts
@@ -160,9 +160,8 @@ describe("applyWorkflowTransform", () => {
});
it("strips the @<version> stamp for stable workflow names but not for steps", async () => {
- // Stable workflow ids must match across deployments so
- // `start(ref, args, { deploymentId: "latest" })` lands on the
- // same registry key on a newer deployment. Step ids stay
+ // Stable workflow ids must match across deployments so an explicit
+ // deployment target lands on the same registry key. Step ids stay
// version-stamped because they are per-deployment internal
// identifiers, not cross-deployment routing keys.
const transformed = await transformWorkflowDirectives({
diff --git a/packages/eve/src/public/channels/eve.test.ts b/packages/eve/src/public/channels/eve.test.ts
index 0c540a7ed..35cfa0f36 100644
--- a/packages/eve/src/public/channels/eve.test.ts
+++ b/packages/eve/src/public/channels/eve.test.ts
@@ -4,7 +4,6 @@ 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 { readClientContext } from "#internal/client-context.js";
import { attachRouteSessionCreator } from "#internal/nitro/routes/channel-route-context.js";
import { mockChannelContext } from "#internal/testing/mocks/mock-channel-operations.js";
@@ -920,24 +919,6 @@ describe("eveChannel — create session idempotency", () => {
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;