Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): workflow hooks - adopt ownership checks (#232)

Andrew Barbac927ecd3480a
diff --git a/.changeset/calm-hooks-own.md b/.changeset/calm-hooks-own.md
new file mode 100644
index 000000000..fd70f7fc7
--- /dev/null
+++ b/.changeset/calm-hooks-own.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Confirm continuation-token ownership before an agent turn starts or a session re-keys. Competing sessions now fail before processing input, and successful delivery reports the hook owner atomically.
diff --git a/docs/channels/custom.mdx b/docs/channels/custom.mdx
index a0c0d40c9..76526a575 100644
--- a/docs/channels/custom.mdx
+++ b/docs/channels/custom.mdx
@@ -225,7 +225,7 @@ defineChannel<{ ref: string | null }>({
});
```
-The workflow runtime disposes the current park hook at the next step boundary and registers a new one at the new token. Inbound deliveries already addressed to the old token are dropped, so coordinate with your senders to use the new token.
+At the next workflow boundary, the runtime claims the new park hook before releasing the old token. If another active session already owns the new token, the re-keying session fails instead of taking it over. After a successful re-key, inbound deliveries still addressed to the old token are dropped, so coordinate with your senders to use the new token.
## File uploads
diff --git a/docs/concepts/execution-model-and-durability.md b/docs/concepts/execution-model-and-durability.md
index 7d6ae111d..6680ed840 100644
--- a/docs/concepts/execution-model-and-durability.md
+++ b/docs/concepts/execution-model-and-durability.md
@@ -54,6 +54,8 @@ Some work has to wait, including a human approving a [tool](../tools), an intera
eve does not maintain a durable FIFO queue of user messages for a session. The `continuationToken` is a resume handle for the session's current workflow hook, not a general message-queue address.
+Only one active session can own a continuation token. When a session starts with a token, eve commits the park hook before processing its first turn and fails a competing session if another run already owns that token. A tokenless session claims its token after the first turn establishes one. Competing input is not forwarded to the owner.
+
When a session is waiting, a delivery to the current continuation token wakes the session and starts the next turn. When a turn is already active, the hook may accept additional deliveries, but the runtime only drains them at specific workflow boundaries. If more than one delivery is ready when the driver checks, eve may fold them into the next turn; that drain is best-effort and depends on workflow and transport timing.
So don't rely on concurrent sends to the same session behaving like a typical ordered chat queue. For deterministic behavior, send one user turn at a time and wait for `session.waiting` before sending the next message to the same session. If your channel can receive bursts while the agent is working, keep your own per-session queue in the channel or app layer, then deliver the next message after the session parks again. Separate sessions still run independently.
diff --git a/packages/eve/src/execution/hook-ownership.ts b/packages/eve/src/execution/hook-ownership.ts
new file mode 100644
index 000000000..089cc0fee
--- /dev/null
+++ b/packages/eve/src/execution/hook-ownership.ts
@@ -0,0 +1,78 @@
+import type { Hook } from "#compiled/@workflow/core/index.js";
+
+export async function claimHookOwnership<T>(hook: Hook<T>): Promise<void> {
+ let conflict: Awaited<ReturnType<Hook<T>["getConflict"]>>;
+ try {
+ conflict = await hook.getConflict();
+ } catch (error) {
+ return await disposeAndThrow(hook, normalizeHookClaimError(error, hook.token));
+ }
+
+ if (conflict !== null) {
+ return await disposeAndThrow(hook, createHookConflictError(hook.token, conflict.runId));
+ }
+}
+
+export async function closeHookIterator<T>(iterator: AsyncIterator<T>): Promise<void> {
+ if (typeof iterator.return === "function") {
+ await iterator.return(undefined);
+ }
+}
+
+export async function disposeHook(hook: {
+ dispose?: () => unknown;
+ [Symbol.dispose]?: () => unknown;
+}): Promise<void> {
+ const explicitDispose = hook.dispose;
+ if (typeof explicitDispose === "function") {
+ await explicitDispose.call(hook);
+ return;
+ }
+
+ const symbolDispose = hook[Symbol.dispose];
+ if (typeof symbolDispose === "function") {
+ await symbolDispose.call(hook);
+ }
+}
+
+async function disposeAndThrow(hook: Hook<unknown>, error: unknown): Promise<never> {
+ try {
+ await disposeHook(hook);
+ } catch {
+ // The claim failure is authoritative; cleanup must not replace it.
+ }
+ throw error;
+}
+
+function normalizeHookClaimError(error: unknown, token: string): unknown {
+ if (!isHookConflictError(error)) {
+ return error;
+ }
+
+ // Legacy worlds reject here when they cannot identify the owning run.
+ return createHookConflictError(
+ typeof error.token === "string" ? error.token : token,
+ typeof error.conflictingRunId === "string" ? error.conflictingRunId : undefined,
+ );
+}
+
+function isHookConflictError(
+ error: unknown,
+): error is Error & { readonly conflictingRunId?: unknown; readonly token?: unknown } {
+ return error instanceof Error && error.name === "HookConflictError";
+}
+
+function createHookConflictError(
+ token: string,
+ conflictingRunId?: string,
+): Error & {
+ readonly conflictingRunId?: string;
+ readonly token: string;
+} {
+ const owner = conflictingRunId === undefined ? "" : ` (run "${conflictingRunId}")`;
+ return Object.assign(new Error(`Hook token "${token}" is already in use${owner}`), {
+ conflictingRunId,
+ name: "HookConflictError",
+ token,
+ });
+}
diff --git a/packages/eve/src/execution/workflow-entry.integration.test.ts b/packages/eve/src/execution/workflow-entry.integration.test.ts
index a7087642f..f018824c2 100644
--- a/packages/eve/src/execution/workflow-entry.integration.test.ts
+++ b/packages/eve/src/execution/workflow-entry.integration.test.ts
@@ -6,6 +6,7 @@ import { createTestRuntime } from "#internal/testing/app-harness.js";
import { waitForHook } from "#internal/testing/workflow-test-helpers.js";
import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
import { workflowEntry } from "#execution/workflow-entry.js";
+import { createWorkflowRuntime } from "#execution/workflow-runtime.js";
function buildSerializedContext(overrides: {
channelKind: string;
@@ -35,7 +36,7 @@ function buildSerializedContext(overrides: {
}
describe("workflowEntry integration", () => {
- it("parks in conversation mode and resumes via the workflow hook", async () => {
+ it("parks in conversation mode and resumes via runtime delivery", async () => {
const runtime = createTestRuntime({ agent: { name: "workflow-entry-conversation" } });
const continuationToken = "http:workflow-entry-conversation";
@@ -73,10 +74,16 @@ describe("workflowEntry integration", () => {
),
).toBe(true);
- await resumeHook(continuationToken, {
- kind: "deliver",
- payloads: [{ message: "follow up" }],
+ const workflowRuntime = createWorkflowRuntime({
+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
});
+ await expect(
+ workflowRuntime.deliver({
+ auth: null,
+ continuationToken,
+ payload: { message: "follow up" },
+ }),
+ ).resolves.toEqual({ sessionId: run.runId });
const secondTurn = await stream.nextTurn();
@@ -96,6 +103,72 @@ describe("workflowEntry integration", () => {
});
});
+ it("fails 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";
+
+ await runtime.run(async () => {
+ const owner = await start(workflowEntry, [
+ {
+ input: { message: "owner message" },
+ serializedContext: buildSerializedContext({
+ channelKind: "http",
+ continuationToken,
+ mode: "conversation",
+ }),
+ },
+ ]);
+ const ownerStream = captureTurnEvents(owner);
+ await waitForHook({ runId: owner.runId }, { token: continuationToken });
+
+ const firstTurn = await ownerStream.nextTurn();
+ expect(firstTurn.at(-1)?.type).toBe("session.waiting");
+
+ const contender = await start(workflowEntry, [
+ {
+ input: { message: "contending message" },
+ serializedContext: buildSerializedContext({
+ channelKind: "http",
+ continuationToken,
+ mode: "conversation",
+ }),
+ },
+ ]);
+ 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(/Hook token/);
+
+ await resumeHook(continuationToken, {
+ kind: "deliver",
+ payloads: [{ message: "owner follow up" }],
+ });
+ const ownerFollowUp = await ownerStream.nextTurn();
+
+ expect(ownerFollowUp.at(-1)?.type).toBe("session.waiting");
+ expect(
+ ownerFollowUp.some(
+ (event) =>
+ event.type === "message.completed" &&
+ event.data.message?.includes("owner follow up") === true,
+ ),
+ ).toBe(true);
+ } finally {
+ contenderStream.dispose();
+ ownerStream.dispose();
+ await owner.cancel();
+ }
+ });
+ });
+
it("emits completed structured results for a conversation turn outputSchema", async () => {
const runtime = createTestRuntime({ agent: { name: "workflow-entry-output-schema" } });
const continuationToken = "http:workflow-entry-output-schema";
diff --git a/packages/eve/src/execution/workflow-entry.test.ts b/packages/eve/src/execution/workflow-entry.test.ts
index 2de008a87..7e307a33a 100644
--- a/packages/eve/src/execution/workflow-entry.test.ts
+++ b/packages/eve/src/execution/workflow-entry.test.ts
@@ -93,6 +93,7 @@ vi.mock("./session-callback-step.js", () => ({
interface ParkHookConfig {
readonly dispose?: () => void;
+ readonly getConflict?: () => Promise<{ readonly runId: string } | null>;
readonly return?: () => Promise<IteratorResult<HookPayload>>;
readonly token: string;
readonly values?: readonly HookPayload[];
@@ -111,8 +112,10 @@ describe("workflowEntry", () => {
it("injects the workflow run id as the canonical session id before the first turn", async () => {
const sessionState = createBaseSessionState();
+ const getConflict = vi.fn(async () => null);
vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));
installHookMocks({
+ parkHooks: [{ getConflict, token: "http:test" }],
turnCompletions: [
turnResult({
action: "done",
@@ -155,6 +158,77 @@ describe("workflowEntry", () => {
sessionState,
}),
);
+ expect(getConflict).toHaveBeenCalledOnce();
+ expect(getConflict.mock.invocationCallOrder[0]).toBeLessThan(
+ vi.mocked(dispatchTurnStep).mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
+ );
+ });
+
+ it("fails a conflicting park hook before dispatching the first turn", async () => {
+ const sessionState = createBaseSessionState();
+ const dispose = vi.fn();
+ vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));
+ installHookMocks({
+ parkHooks: [
+ {
+ dispose,
+ getConflict: vi.fn(async () => ({ runId: "wrun_owner" })),
+ token: "http:test",
+ },
+ ],
+ turnCompletions: [],
+ });
+
+ await expect(
+ workflowEntry({
+ input: { message: "duplicate" },
+ serializedContext: createSerializedContext(),
+ }),
+ ).rejects.toMatchObject({
+ conflictingRunId: "wrun_owner",
+ name: "HookConflictError",
+ token: "http:test",
+ });
+
+ expect(dispatchTurnStep).not.toHaveBeenCalled();
+ expect(dispose).toHaveBeenCalledOnce();
+ });
+
+ it("normalizes the getConflict fallback error before dispatching the first turn", async () => {
+ const sessionState = createBaseSessionState();
+ const dispose = vi.fn();
+ const fallbackError = Object.assign(new Error("legacy hook conflict"), {
+ name: "HookConflictError",
+ token: "http:test",
+ });
+ vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));
+ installHookMocks({
+ parkHooks: [
+ {
+ dispose,
+ getConflict: vi.fn(async () => {
+ throw fallbackError;
+ }),
+ token: "http:test",
+ },
+ ],
+ turnCompletions: [],
+ });
+
+ await expect(
+ workflowEntry({
+ input: { message: "duplicate" },
+ serializedContext: createSerializedContext(),
+ }),
+ ).rejects.toMatchObject({
+ conflictingRunId: undefined,
+ message: 'Hook token "http:test" is already in use',
+ name: "HookConflictError",
+ token: "http:test",
+ });
+
+ expect(dispatchTurnStep).not.toHaveBeenCalled();
+ expect(dispose).toHaveBeenCalledOnce();
});
it("buffers follow-up user input until a pending subagent batch resolves", async () => {
@@ -677,12 +751,15 @@ describe("workflowEntry", () => {
const oldReturn = createIteratorReturn();
const oldDispose = vi.fn();
+ const oldGetConflict = vi.fn(async () => null);
const newReturn = createIteratorReturn();
const newDispose = vi.fn();
+ const newGetConflict = vi.fn(async () => null);
installHookMocks({
parkHooks: [
{
dispose: oldDispose,
+ getConflict: oldGetConflict,
return: oldReturn,
token: "slack:C01:",
values: [
@@ -694,6 +771,7 @@ describe("workflowEntry", () => {
},
{
dispose: newDispose,
+ getConflict: newGetConflict,
return: newReturn,
token: "slack:C01:1800000000.123456",
values: [],
@@ -723,6 +801,142 @@ describe("workflowEntry", () => {
expect(oldDispose).toHaveBeenCalledTimes(1);
expect(newReturn).toHaveBeenCalledTimes(1);
expect(newDispose).toHaveBeenCalledTimes(1);
+ expect(oldGetConflict).toHaveBeenCalledOnce();
+ expect(newGetConflict).toHaveBeenCalledOnce();
+ expect(newGetConflict.mock.invocationCallOrder[0]).toBeLessThan(
+ vi.mocked(oldReturn).mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
+ );
+ expect(newGetConflict.mock.invocationCallOrder[0]).toBeLessThan(
+ oldDispose.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
+ );
+ });
+
+ it.each(["iterator", "hook"] as const)(
+ "cleans both hooks once when the old %s fails during rekey",
+ async (failurePoint) => {
+ const baseSessionState = createBaseSessionState({ continuationToken: "slack:C01:" });
+ const rekeyedSessionState: DurableSessionState = {
+ ...baseSessionState,
+ continuationToken: "slack:C01:1800000000.123456",
+ };
+ const releaseError = new Error(`${failurePoint} release failed`);
+ const oldReturn = vi.fn(async (): Promise<IteratorResult<HookPayload>> => {
+ if (failurePoint === "iterator") throw releaseError;
+ return { done: true, value: undefined };
+ });
+ const oldDispose = vi.fn(() => {
+ if (failurePoint === "hook") throw releaseError;
+ });
+ const candidateDispose = vi.fn();
+ const candidateGetConflict = vi.fn(async () => null);
+ vi.mocked(createSessionStep).mockResolvedValue(
+ createSessionStepResultForMock(baseSessionState),
+ );
+ installHookMocks({
+ parkHooks: [
+ {
+ dispose: oldDispose,
+ return: oldReturn,
+ token: "slack:C01:",
+ values: [
+ {
+ kind: "deliver",
+ payloads: [{ message: "follow up" }],
+ },
+ ],
+ },
+ {
+ dispose: candidateDispose,
+ getConflict: candidateGetConflict,
+ token: "slack:C01:1800000000.123456",
+ },
+ ],
+ turnCompletions: [
+ turnResult({ action: "park", sessionState: baseSessionState }),
+ turnResult({ action: "park", sessionState: rekeyedSessionState }),
+ ],
+ });
+
+ await expect(
+ workflowEntry({
+ input: { message: "hello" },
+ serializedContext: createSerializedContext({
+ "eve.channel": { kind: "slack", state: {} },
+ "eve.continuationToken": "slack:C01:",
+ }),
+ }),
+ ).rejects.toBe(releaseError);
+
+ expect(candidateGetConflict).toHaveBeenCalledOnce();
+ expect(oldReturn).toHaveBeenCalledOnce();
+ expect(oldDispose).toHaveBeenCalledOnce();
+ expect(candidateDispose).toHaveBeenCalledOnce();
+ },
+ );
+
+ it("disposes a conflicting rekey candidate before cleaning up the active hook", async () => {
+ const baseSessionState = createBaseSessionState({ continuationToken: "slack:C01:" });
+ const rekeyedSessionState: DurableSessionState = {
+ ...baseSessionState,
+ continuationToken: "slack:C01:1800000000.123456",
+ };
+ vi.mocked(createSessionStep).mockResolvedValue(
+ createSessionStepResultForMock(baseSessionState),
+ );
+
+ const oldReturn = createIteratorReturn();
+ const oldDispose = vi.fn();
+ const candidateDispose = vi.fn();
+ const candidateGetConflict = vi.fn(async () => ({ runId: "wrun_owner" }));
+ installHookMocks({
+ parkHooks: [
+ {
+ dispose: oldDispose,
+ return: oldReturn,
+ token: "slack:C01:",
+ values: [
+ {
+ kind: "deliver",
+ payloads: [{ message: "follow up" }],
+ },
+ ],
+ },
+ {
+ dispose: candidateDispose,
+ getConflict: candidateGetConflict,
+ token: "slack:C01:1800000000.123456",
+ },
+ ],
+ turnCompletions: [
+ turnResult({ action: "park", sessionState: baseSessionState }),
+ turnResult({ action: "park", sessionState: rekeyedSessionState }),
+ ],
+ });
+
+ await expect(
+ workflowEntry({
+ input: { message: "hello" },
+ serializedContext: createSerializedContext({
+ "eve.channel": { kind: "slack", state: {} },
+ "eve.continuationToken": "slack:C01:",
+ }),
+ }),
+ ).rejects.toMatchObject({
+ conflictingRunId: "wrun_owner",
+ name: "HookConflictError",
+ token: "slack:C01:1800000000.123456",
+ });
+
+ expect(candidateGetConflict).toHaveBeenCalledOnce();
+ expect(candidateDispose).toHaveBeenCalledOnce();
+ expect(oldReturn).toHaveBeenCalledOnce();
+ expect(oldDispose).toHaveBeenCalledOnce();
+ expect(candidateDispose.mock.invocationCallOrder[0]).toBeLessThan(
+ vi.mocked(oldReturn).mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
+ );
+ expect(candidateDispose.mock.invocationCallOrder[0]).toBeLessThan(
+ oldDispose.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
+ );
});
it("disposes the workflow hook after the loop exits", async () => {
@@ -930,6 +1144,7 @@ function installHookMocks(input: {
return createMockHook({
dispose: config.dispose,
+ getConflict: config.getConflict,
return: config.return,
symbolDispose: input.symbolDispose,
token,
@@ -940,6 +1155,7 @@ function installHookMocks(input: {
function createMockHook<T>(input: {
readonly dispose?: () => void;
+ readonly getConflict?: () => Promise<{ readonly runId: string } | null>;
readonly next?: () => Promise<IteratorResult<T>>;
readonly return?: () => Promise<IteratorResult<T>>;
readonly symbolDispose?: () => void;
@@ -948,6 +1164,7 @@ function createMockHook<T>(input: {
}): unknown {
const values = [...input.values];
const dispose = input.dispose ?? vi.fn();
+ const getConflict = input.getConflict ?? vi.fn(async () => null);
const symbolDispose = input.symbolDispose ?? vi.fn();
const iteratorReturn = input.return;
@@ -968,6 +1185,7 @@ function createMockHook<T>(input: {
},
[Symbol.dispose]: symbolDispose,
dispose,
+ getConflict,
token: input.token,
});
}
diff --git a/packages/eve/src/execution/workflow-entry.ts b/packages/eve/src/execution/workflow-entry.ts
index 93625b149..31586b13c 100644
--- a/packages/eve/src/execution/workflow-entry.ts
+++ b/packages/eve/src/execution/workflow-entry.ts
@@ -42,6 +42,7 @@ import {
runProxyInputRequestStep,
} from "#execution/workflow-steps.js";
import { fireSessionCallbackStep } from "#execution/session-callback-step.js";
+import { claimHookOwnership, closeHookIterator, disposeHook } from "#execution/hook-ownership.js";
// workflow-entry.ts is the durable workflow body — the bundler rejects
// node built-ins here, so `internal/logging.ts` cannot be imported.
@@ -174,7 +175,7 @@ async function runDriverLoop(input: {
const nextTurnCompletionToken = (): string =>
`${input.sessionState.sessionId}:turn-completion:${String(turnDispatchIndex++)}`;
- // Register before the first turn when a placeholder token exists.
+ // Claim before the first turn when a placeholder token exists.
// Tokenless channels must anchor during that turn before hook registration.
let parkToken = "";
let hook: Hook<HookPayload> | undefined;
@@ -182,17 +183,6 @@ async function runDriverLoop(input: {
let pendingNext: Promise<IteratorResult<HookPayload>> | null = null;
const bufferedDeliveries: DeliverHookPayload[] = [];
- const createParkHook = (nextToken: string): void => {
- parkToken = nextToken;
- hook = createHook<HookPayload>({ token: parkToken });
- iterator = hook[Symbol.asyncIterator]();
- pendingNext = null;
- };
-
- if (input.sessionState.continuationToken) {
- createParkHook(input.sessionState.continuationToken);
- }
-
const getNextPromise = (): Promise<IteratorResult<HookPayload>> => {
if (iterator === undefined) {
throw new Error("Cannot wait for deliveries before a continuation token is available.");
@@ -207,65 +197,94 @@ async function runDriverLoop(input: {
};
/**
- * Disposes the current park hook and creates a fresh one at
- * `nextToken`. Channels that re-key mid-session must coordinate
- * with their senders — in-flight deliveries to the old token after
- * this returns are silently dropped.
+ * Stops accepting deliveries on the current park hook and releases its
+ * token. In-flight deliveries to that token after this returns are dropped.
*/
const closeParkHook = async (): Promise<void> => {
- if (iterator !== undefined) {
- await closeHookIterator(iterator);
- }
- if (hook !== undefined) {
- await disposeHook(hook);
- }
+ const currentIterator = iterator;
+ const currentHook = hook;
hook = undefined;
iterator = undefined;
pendingNext = null;
+
+ if (currentIterator !== undefined) {
+ try {
+ await closeHookIterator(currentIterator);
+ } catch (error) {
+ if (currentHook !== undefined) {
+ try {
+ await disposeHook(currentHook);
+ } catch {
+ // The iterator failure is authoritative; cleanup must not replace it.
+ }
+ }
+ throw error;
+ }
+ }
+ if (currentHook !== undefined) {
+ await disposeHook(currentHook);
+ }
};
const rekeyHook = async (nextToken: string): Promise<void> => {
if (!nextToken || (hook !== undefined && nextToken === parkToken)) return;
- await closeParkHook();
- createParkHook(nextToken);
+
+ // Claim the replacement before releasing the current token. A failed
+ // claim leaves the active hook intact until normal failure cleanup.
+ const nextHook = createHook<HookPayload>({ token: nextToken });
+ await claimHookOwnership(nextHook);
+
+ try {
+ await closeParkHook();
+ } catch (error) {
+ try {
+ await disposeHook(nextHook);
+ } catch {
+ // The active hook release failure is authoritative.
+ }
+ throw error;
+ }
+
+ parkToken = nextToken;
+ hook = nextHook;
+ iterator = nextHook[Symbol.asyncIterator]();
+ pendingNext = null;
};
- let action: NextDriverAction = await dispatchAndAwaitTurn({
- capabilities: input.capabilities,
- completionToken: nextTurnCompletionToken(),
- delivery: input.initialInput,
- mode: input.mode,
- parentWritable: input.driverWritable,
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
- });
+ try {
+ if (input.sessionState.continuationToken) {
+ await rekeyHook(input.sessionState.continuationToken);
+ }
- if (action.kind === "done") {
- await closeHookIterator(authIterator);
- await disposeHook(authHook);
- await closeParkHook();
- return await finalizeDone({
- action,
- driverWritable: input.driverWritable,
+ let action: NextDriverAction = await dispatchAndAwaitTurn({
+ capabilities: input.capabilities,
+ completionToken: nextTurnCompletionToken(),
+ delivery: input.initialInput,
+ mode: input.mode,
+ parentWritable: input.driverWritable,
+ serializedContext: input.serializedContext,
+ sessionState: input.sessionState,
});
- }
- if (!action.sessionState.continuationToken) {
- await closeHookIterator(authIterator);
- await disposeHook(authHook);
- await closeParkHook();
- throw new Error(
- "Cannot park: no continuation token available. The channel must " +
- "post the first message during the initial turn (anchoring the " +
- "session) or `send()` must be called with an explicit " +
- "continuationToken.",
- );
- }
+ if (action.kind === "done") {
+ return await finalizeDone({
+ action,
+ driverWritable: input.driverWritable,
+ });
+ }
- // Rekey if the first turn changed the continuation token.
- await rekeyHook(action.sessionState.continuationToken);
+ if (!action.sessionState.continuationToken) {
+ throw new Error(
+ "Cannot park: no continuation token available. The channel must " +
+ "post the first message during the initial turn (anchoring the " +
+ "session) or `send()` must be called with an explicit " +
+ "continuationToken.",
+ );
+ }
+
+ // Rekey if the first turn changed the continuation token.
+ await rekeyHook(action.sessionState.continuationToken);
- try {
while (true) {
switch (action.kind) {
case "done":
@@ -672,29 +691,3 @@ async function takeReadyPayload<T>(promise: Promise<T>): Promise<T | typeof NO_R
await Promise.resolve();
return await Promise.race([promise, Promise.resolve(NO_READY_MESSAGE)]);
}
-
-async function closeHookIterator(iterator: AsyncIterator<HookPayload>): Promise<void> {
- if (typeof iterator.return !== "function") {
- return;
- }
-
- await iterator.return(undefined);
-}
-
-async function disposeHook(hook: {
- dispose?: () => unknown;
- [Symbol.dispose]?: () => unknown;
-}): Promise<void> {
- const explicitDispose = hook.dispose;
- if (typeof explicitDispose === "function") {
- await explicitDispose.call(hook);
- return;
- }
-
- const symbolDispose = hook[Symbol.dispose];
- if (typeof symbolDispose !== "function") {
- return;
- }
-
- await symbolDispose.call(hook);
-}
diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.ts
index 0b44cb644..b98491b07 100644
--- a/packages/eve/src/execution/workflow-runtime.test.ts
+++ b/packages/eve/src/execution/workflow-runtime.test.ts
@@ -12,13 +12,11 @@ import { isRuntimeNoActiveSessionError } from "#execution/runtime-errors.js";
import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";
-const getHookByTokenMock = vi.fn();
const getRunMock = vi.fn();
const resumeHookMock = vi.fn();
const startMock = vi.fn();
vi.mock("#compiled/@workflow/core/runtime.js", () => ({
- getHookByToken: (...args: unknown[]) => getHookByTokenMock(...args),
getRun: (...args: unknown[]) => getRunMock(...args),
resumeHook: (...args: unknown[]) => resumeHookMock(...args),
start: (...args: unknown[]) => startMock(...args),
@@ -29,7 +27,6 @@ vi.mock("#runtime/sessions/compiled-agent-cache.js", () => ({
}));
afterEach(() => {
- getHookByTokenMock.mockReset();
getRunMock.mockReset();
resumeHookMock.mockReset();
startMock.mockReset();
@@ -64,7 +61,7 @@ describe("createWorkflowRuntime#deliver", () => {
it("normalizes `HookNotFoundError` into `RuntimeNoActiveSessionError`", async () => {
const { HookNotFoundError } = await import("#compiled/@workflow/errors/index.js");
- getHookByTokenMock.mockRejectedValue(new HookNotFoundError(NOT_FOUND_TOKEN));
+ resumeHookMock.mockRejectedValue(new HookNotFoundError(NOT_FOUND_TOKEN));
const runtime = buildRuntime();
@@ -77,9 +74,9 @@ describe("createWorkflowRuntime#deliver", () => {
).rejects.toSatisfy(isRuntimeNoActiveSessionError);
});
- it("re-throws unexpected errors from `getHookByToken`", async () => {
+ it("re-throws unexpected errors from `resumeHook`", async () => {
const failure = new Error("transient backing-store outage");
- getHookByTokenMock.mockRejectedValue(failure);
+ resumeHookMock.mockRejectedValue(failure);
const runtime = buildRuntime();
@@ -91,6 +88,26 @@ describe("createWorkflowRuntime#deliver", () => {
}),
).rejects.toBe(failure);
});
+
+ it("returns the owner from the hook resumed by the delivery", async () => {
+ resumeHookMock.mockResolvedValue({ runId: "owner-session" });
+
+ const runtime = buildRuntime();
+
+ await expect(
+ runtime.deliver({
+ auth: null,
+ continuationToken: "test:active-hook",
+ payload: { message: "hello" },
+ }),
+ ).resolves.toEqual({ sessionId: "owner-session" });
+ expect(resumeHookMock).toHaveBeenCalledOnce();
+ expect(resumeHookMock).toHaveBeenCalledWith("test:active-hook", {
+ auth: null,
+ kind: "deliver",
+ payloads: [{ message: "hello" }],
+ });
+ });
});
describe("createWorkflowRuntime#run", () => {
diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.ts
index 4d417d7f4..05fc8d9ae 100644
--- a/packages/eve/src/execution/workflow-runtime.ts
+++ b/packages/eve/src/execution/workflow-runtime.ts
@@ -1,5 +1,5 @@
import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";
-import { getHookByToken, getRun, resumeHook, start } from "#compiled/@workflow/core/runtime.js";
+import { getRun, resumeHook, start } from "#compiled/@workflow/core/runtime.js";
import type { Run } from "#compiled/@workflow/core/runtime.js";
import type { WorkflowFunction, WorkflowMetadata } from "#compiled/@workflow/core/runtime/start.js";
@@ -126,8 +126,7 @@ export function createWorkflowRuntime(config: {
payloads: [input.payload],
};
try {
- const hook = normalizeWorkflowHook(await getHookByToken(input.continuationToken));
- await resumeHook(input.continuationToken, hookPayload);
+ const hook = normalizeWorkflowHook(await resumeHook(input.continuationToken, hookPayload));
return { sessionId: hook.runId };
} catch (error) {
// "No hook" is the expected resume-or-start signal: normalize it to
diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.ts
index 90287e84d..37179297a 100644
--- a/packages/eve/src/execution/workflow-steps.test.ts
+++ b/packages/eve/src/execution/workflow-steps.test.ts
@@ -106,7 +106,6 @@ vi.mock("../runtime/sessions/compiled-agent-cache.js", () => ({
}));
vi.mock("#compiled/@workflow/core/runtime.js", () => ({
- getHookByToken: vi.fn(),
getRun: (...args: unknown[]) => getRunMock(...args),
resumeHook: vi.fn(),
start: (...args: unknown[]) => startMock(...args),
diff --git a/packages/eve/src/internal/workflow-bundle/builder.scenario.test.ts b/packages/eve/src/internal/workflow-bundle/builder.scenario.test.ts
index 44541bc65..a60cca58f 100644
--- a/packages/eve/src/internal/workflow-bundle/builder.scenario.test.ts
+++ b/packages/eve/src/internal/workflow-bundle/builder.scenario.test.ts
@@ -9,6 +9,7 @@ import {
resolveInstalledPackageInfo,
resolvePackageRoot,
resolvePackageSourceDirectoryPath,
+ resolvePackageSourceFilePath,
resolveWorkflowModulePath,
} from "#internal/application/package.js";
@@ -588,6 +589,72 @@ describe("WorkflowBundleBuilder", () => {
}
});
+ it("bundles hook ownership checks through the workflow core shim", async () => {
+ const tempRoot = await mkdtemp(join(tmpdir(), "eve-workflow-bundle-hook-conflict-"));
+ const outDir = join(tempRoot, "workflow-build");
+ const flowFilePath = join(tempRoot, "flow.ts");
+ const compiledArtifactsBootstrapPath = join(tempRoot, "compiled-artifacts-bootstrap.mjs");
+ const workflowCoreShimPath = resolvePackageSourceFilePath(
+ "src/internal/workflow-bundle/workflow-core-shim.ts",
+ ).replaceAll("\\", "/");
+
+ try {
+ await Promise.all([
+ writeFile(
+ compiledArtifactsBootstrapPath,
+ [
+ "export async function __eveInstallCompiledArtifactsStep() {",
+ ' "use step";',
+ " return null;",
+ "}",
+ "",
+ ].join("\n"),
+ ),
+ writeFile(
+ flowFilePath,
+ [
+ `import { createHook } from ${JSON.stringify(workflowCoreShimPath)};`,
+ "export async function claimHook() {",
+ ' "use workflow";',
+ ' const hook = createHook({ token: "shared-token" });',
+ " const conflict = await hook.getConflict();",
+ " return conflict?.runId ?? null;",
+ "}",
+ "",
+ ].join("\n"),
+ ),
+ ]);
+
+ const builder = new FixtureWorkflowBundleBuilder(
+ {
+ appRoot: tempRoot,
+ compiledArtifactsBootstrapPath,
+ outDir,
+ rootDir: resolvePackageRoot(),
+ watch: false,
+ },
+ [flowFilePath],
+ );
+
+ await builder.build();
+
+ const workflowsSource = await readFile(join(outDir, "workflows.mjs"), "utf8");
+ const encodedChunksMatch = workflowsSource.match(
+ /Buffer\.from\((\[[\s\S]*?\])\.join\(""\), "base64"\)\.toString\("utf8"\)/,
+ );
+ expect(encodedChunksMatch).not.toBeNull();
+
+ const encodedChunks = JSON.parse(encodedChunksMatch?.[1] ?? "[]") as string[];
+ const decodedWorkflowCode = Buffer.from(encodedChunks.join(""), "base64").toString("utf8");
+
+ expect(decodedWorkflowCode).toContain("getConflict");
+ expect(decodedWorkflowCode).toContain("WORKFLOW_CREATE_HOOK");
+ expect(decodedWorkflowCode).not.toContain("runtime/run.js");
+ } finally {
+ await rm(tempRoot, { force: true, recursive: true });
+ }
+ });
+
it("allows a node builtin used only inside a use step body", async () => {
const tempRoot = await mkdtemp(join(tmpdir(), "eve-workflow-bundle-node-step-ok-"));
const outDir = join(tempRoot, "workflow-build");
diff --git a/packages/eve/src/internal/workflow-bundle/workflow-core-shim.ts b/packages/eve/src/internal/workflow-bundle/workflow-core-shim.ts
index 9171c39f7..ce542ff2f 100644
--- a/packages/eve/src/internal/workflow-bundle/workflow-core-shim.ts
+++ b/packages/eve/src/internal/workflow-bundle/workflow-core-shim.ts
@@ -9,16 +9,17 @@ export class RetryableError extends Error {}
export class FatalError extends Error {}
+interface WorkflowHook<T> extends AsyncIterable<T> {
+ readonly token: string;
+ getConflict(): Promise<{ readonly runId: string } | null>;
+}
+
/**
* Creates a Workflow hook from inside a durable workflow body.
*/
-export function createHook<T = unknown>(
- options?: unknown,
-): AsyncIterable<T> & {
- readonly token: string;
-} {
+export function createHook<T = unknown>(options?: unknown): WorkflowHook<T> {
const createHookFn = workflowGlobal[WORKFLOW_CREATE_HOOK] as
- | ((hookOptions?: unknown) => AsyncIterable<T> & { readonly token: string })
+ | ((hookOptions?: unknown) => WorkflowHook<T>)
| undefined;
if (createHookFn === undefined) {
@@ -68,16 +69,8 @@ export function getWritable<T = unknown>(options: { namespace?: string } = {}):
/**
* Creates a Workflow webhook from inside a durable workflow body.
*/
-export function createWebhook<T = unknown>(
- options?: unknown,
-): AsyncIterable<T> & {
- readonly token: string;
- url?: string;
-} {
- const hook = createHook<T>(options) as AsyncIterable<T> & {
- readonly token: string;
- url?: string;
- };
+export function createWebhook<T = unknown>(options?: unknown): WorkflowHook<T> & { url?: string } {
+ const hook = createHook<T>(options) as WorkflowHook<T> & { url?: string };
const metadata = getWorkflowMetadata();
const baseUrl = typeof metadata.url === "string" ? metadata.url : "";
@@ -89,7 +82,7 @@ export function createWebhook<T = unknown>(
* Defines a Workflow hook factory for workflow-body code.
*/
export function defineHook<T = unknown>(): {
- readonly create: (options?: unknown) => AsyncIterable<T> & { readonly token: string };
+ readonly create: (options?: unknown) => WorkflowHook<T>;
readonly resume: () => never;
} {
return {