Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

Fix out-of-turn terminal session event delivery (#3402)

e0-gh-vercel-connect[bot]61e20b234075
diff --git a/.changeset/fix-session-stream-hangs.md b/.changeset/fix-session-stream-hangs.md
new file mode 100644
index 000000000..af63ea424
--- /dev/null
+++ b/.changeset/fix-session-stream-hangs.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Return a not-found or transient error before opening an unavailable session stream, and close streams after terminal failures.
diff --git a/.changeset/terminal-session-events.md b/.changeset/terminal-session-events.md
new file mode 100644
index 000000000..927cb834b
--- /dev/null
+++ b/.changeset/terminal-session-events.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Fix channel `session.completed` handlers throwing when a session expires, resets, or closes between turns. The handler's `ctx.session.turn` reports the session's last turn.
diff --git a/packages/eve/src/execution/publish-session-events.ts b/packages/eve/src/execution/publish-session-events.ts
index 2038c36cb..e916ebf1c 100644
--- a/packages/eve/src/execution/publish-session-events.ts
+++ b/packages/eve/src/execution/publish-session-events.ts
@@ -2,7 +2,13 @@ import { buildAdapterContext } from "#channel/adapter-context.js";
import { callAdapterEventHandler, type ChannelAdapterContext } from "#channel/adapter.js";
import { type ContextContainer, contextStorage } from "#context/container.js";
import { dispatchStreamEventHooks } from "#context/hook-lifecycle.js";
-import { ParentSessionKey, TurnDeliveryIdsKey } from "#context/keys.js";
+import {
+ AuthKey,
+ InitiatorAuthKey,
+ ParentSessionKey,
+ SessionKey,
+ TurnDeliveryIdsKey,
+} from "#context/keys.js";
import { withContextScope } from "#context/run-step.js";
import { deserializeContext, serializeContext } from "#context/serialize.js";
import { setChannelContext } from "#execution/channel-context.js";
@@ -18,6 +24,7 @@ import { reconcileSessionContinuationToken } from "#execution/reconcile-session-
import { hydrateDurableSession } from "#execution/session.js";
import { activeTurnId } from "#harness/active-turn-id.js";
import { getHarnessEmissionState } from "#harness/emission.js";
+import type { HarnessTurnRef } from "#harness/emission-state.js";
import { validateHarnessModelMessages, type HarnessModelMessage } from "#harness/messages.js";
import type { HandleEventFn, HarnessSession, HarnessSessionBase } from "#harness/types.js";
import { bindSessionInstrumentation } from "#instrumentation/runtime.js";
@@ -396,6 +403,8 @@ export async function publishTerminalSessionEvent(input: {
readonly event: TerminalSessionEvent;
readonly serializedContext: Record<string, unknown>;
readonly sessionWritable: WritableStream<Uint8Array>;
+ /** The session's last turn, for channel handlers' `ctx.session.turn`. */
+ readonly turn?: HarnessTurnRef;
/** The turn the event ends, for instrumentation. */
readonly turnId?: string;
}): Promise<void> {
@@ -420,6 +429,18 @@ export async function publishTerminalSessionEvent(input: {
return;
}
+ // Terminal events publish outside any turn step, and only a turn step
+ // installs the session callback context that channel `session.completed`
+ // handlers read, so install it here. A prewarmed session that expires,
+ // resets, or closes before its first message has no turn yet: `turn_0`.
+ const auth = ctx.get(AuthKey) ?? null;
+ ctx.setVirtualContext(SessionKey, {
+ auth: { current: auth, initiator: ctx.get(InitiatorAuthKey) ?? auth },
+ parent: ctx.get(ParentSessionKey),
+ sessionId,
+ turn: input.turn ?? { id: "turn_0", sequence: 0 },
+ });
+
// Emitted without its hooks; see above.
const publish: HandleEventFn = async (event) => {
await publisher.emit(event);
diff --git a/packages/eve/src/execution/session/finalization.ts b/packages/eve/src/execution/session/finalization.ts
index 4befac6bd..468d7fe70 100644
--- a/packages/eve/src/execution/session/finalization.ts
+++ b/packages/eve/src/execution/session/finalization.ts
@@ -8,6 +8,7 @@ import type { TurnOutcome } from "#execution/session/turn-step-types.js";
import { normalizeSerializableError } from "#execution/workflow-errors.js";
import type { WorkflowEntryResult } from "#execution/session/entry-input.js";
import type { TokenUsage } from "#shared/token-usage.js";
+import { lastHarnessTurn } from "#harness/emission-state.js";
import { getSessionUsage, takeSessionUsageDelta } from "#harness/turn-tag-state.js";
import { notifyTurnCallerStep } from "#subagents/parent-notification.js";
@@ -48,6 +49,7 @@ export async function finalizeSession(
await emitTerminalSessionCompletionStep({
sessionWritable: context.sessionWritable,
serializedContext,
+ turn: lastHarnessTurn(session?.state),
usage,
});
} else if (outcome.kind === "failed") {
diff --git a/packages/eve/src/execution/session/terminal-session-completed-channel.test.ts b/packages/eve/src/execution/session/terminal-session-completed-channel.test.ts
new file mode 100644
index 000000000..fe93de184
--- /dev/null
+++ b/packages/eve/src/execution/session/terminal-session-completed-channel.test.ts
@@ -0,0 +1,82 @@
+import { beforeEach, expect, it, vi } from "vitest";
+
+vi.mock("#context/serialize.js", () => ({
+ deserializeContext: vi.fn(),
+}));
+vi.mock("#context/hook-lifecycle.js", () => ({
+ dispatchStreamEventHooks: vi.fn(),
+}));
+
+import { isCompiledChannel } from "#channel/compiled-channel.js";
+import { ContextContainer } from "#context/container.js";
+import { dispatchStreamEventHooks } from "#context/hook-lifecycle.js";
+import { SessionIdKey } from "#context/keys.js";
+import { deserializeContext } from "#context/serialize.js";
+import { createDurableSessionState } from "#execution/durable-session-store.js";
+import { finalizeSession } from "#execution/session/finalization.js";
+import { setHarnessEmissionState } from "#harness/emission-state.js";
+import { POST, defineChannel } from "#public/definitions/channel.js";
+import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
+
+const SESSION_ID = "session-expired";
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubEnv("EVE_LOG_LEVEL", "silent");
+ return () => vi.unstubAllEnvs();
+});
+
+// Expiry, reset, and a closed inbox all end the session outside a turn, where
+// no turn step has installed the session callback context.
+it("delivers session.completed to the channel handler when a session expires between turns", async () => {
+ const handler = vi.fn();
+ const channel = defineChannel({
+ events: { "session.completed": handler },
+ routes: [POST("/test", async () => new Response("ok"))],
+ });
+ if (!isCompiledChannel(channel)) throw new Error("Expected a compiled channel.");
+
+ const restored = new ContextContainer();
+ restored.set(BundleKey, { hookRegistry: {}, turnAgent: { id: "test-agent" } } as any);
+ restored.set(ChannelKey, channel.adapter);
+ restored.set(SessionIdKey, SESSION_ID);
+ vi.mocked(deserializeContext).mockResolvedValue(restored);
+
+ // `turn_3` completed: its epilogue cleared the turn id and advanced the sequence to 4.
+ const session = setHarnessEmissionState(
+ {
+ agent: { modelReference: { id: "unused" }, system: "", tools: [] },
+ compaction: { recentWindowSize: 10, threshold: 100_000 },
+ continuationToken: "token",
+ history: [],
+ sessionId: SESSION_ID,
+ },
+ { sessionStarted: true, sequence: 4, stepIndex: 0, turnId: "" },
+ );
+
+ const written: string[] = [];
+ await finalizeSession(
+ { kind: "expired" },
+ {
+ caller: undefined,
+ cursor: {
+ serializedContext: { "eve.sessionId": SESSION_ID },
+ sessionState: createDurableSessionState({ session }),
+ },
+ sessionWritable: new WritableStream<Uint8Array>({
+ write(chunk) {
+ written.push(new TextDecoder().decode(chunk));
+ },
+ }),
+ },
+ );
+
+ expect(written.join("")).toContain('"type":"session.completed"');
+ expect(handler).toHaveBeenCalledOnce();
+ expect(handler.mock.calls[0]?.[2]?.session).toMatchObject({
+ id: SESSION_ID,
+ turn: { id: "turn_3", sequence: 3 },
+ });
+ // Terminal delivery runs no stream-event hooks, by design.
+ expect(dispatchStreamEventHooks).not.toHaveBeenCalled();
+});
diff --git a/packages/eve/src/execution/terminal-session-completion-step.ts b/packages/eve/src/execution/terminal-session-completion-step.ts
index 76000c52a..7037f5835 100644
--- a/packages/eve/src/execution/terminal-session-completion-step.ts
+++ b/packages/eve/src/execution/terminal-session-completion-step.ts
@@ -1,3 +1,4 @@
+import type { HarnessTurnRef } from "#harness/emission-state.js";
import { publishTerminalSessionEvent } from "#execution/publish-session-events.js";
import { createSessionCompletedEvent } from "#protocol/message.js";
import type { TokenUsage } from "#shared/token-usage.js";
@@ -6,6 +7,8 @@ import type { TokenUsage } from "#shared/token-usage.js";
export async function emitTerminalSessionCompletionStep(input: {
readonly sessionWritable: WritableStream<Uint8Array>;
readonly serializedContext: Record<string, unknown>;
+ /** The session's last turn, reported to channel handlers as `ctx.session.turn`. */
+ readonly turn?: HarnessTurnRef;
readonly usage: TokenUsage | undefined;
}): Promise<void> {
"use step";
@@ -13,6 +16,7 @@ export async function emitTerminalSessionCompletionStep(input: {
await publishTerminalSessionEvent({
sessionWritable: input.sessionWritable,
serializedContext: input.serializedContext,
+ turn: input.turn,
event: createSessionCompletedEvent(input.usage),
});
}
diff --git a/packages/eve/src/harness/emission-state.ts b/packages/eve/src/harness/emission-state.ts
index 531d5004e..d7dd643f1 100644
--- a/packages/eve/src/harness/emission-state.ts
+++ b/packages/eve/src/harness/emission-state.ts
@@ -24,6 +24,22 @@ const DEFAULT_EMISSION_STATE: HarnessEmissionState = {
turnId: "",
};
+/** A turn's id and sequence. */
+export interface HarnessTurnRef {
+ readonly id: string;
+ readonly sequence: number;
+}
+
+/**
+ * The open turn, or else the last completed one (the epilogue advances the
+ * sequence past it). `undefined` before the first turn.
+ */
+export function lastHarnessTurn(state: SessionStateMap | undefined): HarnessTurnRef | undefined {
+ const { sequence, turnId } = getHarnessEmissionState(state);
+ if (turnId !== "") return { id: turnId, sequence };
+ return sequence === 0 ? undefined : { id: `turn_${sequence - 1}`, sequence: sequence - 1 };
+}
+
/** Reads the emission state, returning defaults when absent. */
export function getHarnessEmissionState(state: SessionStateMap | undefined): HarnessEmissionState {
const emissionState = state?.[HARNESS_EMISSION_STATE_KEY] as HarnessEmissionState | undefined;