Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(channels): add session reset helper (#1139)

Casey Gowriedfd360fdfb39
diff --git a/.changeset/gentle-resets-remember.md b/.changeset/gentle-resets-remember.md
new file mode 100644
index 000000000..d5f00ab4f
--- /dev/null
+++ b/.changeset/gentle-resets-remember.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Custom channel routes can now call `reset()` and `ClientSession` can reset the session that owns a stable continuation token. The next `send()` starts a fresh workflow session and lazily initializes a new session-scoped sandbox instead of reusing prior history or workspace state, and the `eve dev` TUI's `/new` performs that durable reset before clearing its transcript.
diff --git a/docs/channels/custom.mdx b/docs/channels/custom.mdx
index c3e6bbfec..f41776ebb 100644
--- a/docs/channels/custom.mdx
+++ b/docs/channels/custom.mdx
@@ -48,6 +48,7 @@ Declare routes with the `POST()` and `GET()` helpers. Each route handler receive
- `send(message, { auth, continuationToken, state?, title? })` starts or resumes a session. `title` overrides the new workflow session's display title without changing the model message. Returns a `Session`.
- `cancel({ continuationToken, turnId? })` requests cancellation of the active turn on the session that owns the token. See [Cancel a turn](#cancel-a-turn).
+- `reset({ continuationToken, reason? })` retires the session that owns the token so the next `send()` starts a fresh session. See [Reset a session](#reset-a-session).
- `getSession(sessionId)` looks up an existing session. The returned `Session` exposes `getEventStream({ startIndex? })` for streaming and `cancel({ turnId? })` for session-id-addressed cancellation.
- `receive(channel, ...)` hands inbound work to a different channel for cross-channel hand-off.
- `params` holds route parameters extracted from the path pattern.
@@ -85,6 +86,40 @@ Semantics:
When you already hold a `Session` — returned by `send()` or `getSession(sessionId)` — call `session.cancel({ turnId? })` to request the same cancellation addressed by session id.
+## Reset a session
+
+Identity-addressed channels can consume commands such as `/new` in their route, without sending the command to the model. Call `reset` with the same channel-local continuation token used by `send()`:
+
+```ts
+import { defineChannel, POST } from "eve/channels";
+
+export default defineChannel({
+ routes: [
+ POST("/messages", async (request, { reset, send }) => {
+ const body = await request.json();
+
+ if (body.message.trim().toLowerCase() === "/new") {
+ await reset({
+ continuationToken: body.conversationId,
+ reason: "User requested /new",
+ });
+ return Response.json({ message: "Started a new conversation." });
+ }
+
+ const session = await send(body.message, {
+ auth: null,
+ continuationToken: body.conversationId,
+ });
+ return Response.json({ sessionId: session.id });
+ }),
+ ],
+});
+```
+
+`reset` returns `{ status: "reset", previousSessionId }` when it observed an owner, or `{ status: "no_active_session" }` when the token was already free. Both outcomes are successful. It terminally cancels the observed workflow run and waits until its non-retained continuation hook no longer blocks reuse, so the next `send()` using the same token creates a new session with fresh history and state.
+
+The replacement session owns a new session-scoped sandbox. eve initializes it lazily on that session's first sandbox use, so it never reuses the prior session's workspace or sandbox state. Resetting does not clear history in place, roll back tool calls, or delete the previous run or its sandbox; normal retention and backend cleanup policies still apply. Side effects or partial output that were already committed remain committed. Authenticate and deduplicate inbound command webhooks before calling this helper: a delayed duplicate `/new` can otherwise reset a newer session that has already reclaimed the same token.
+
## CORS
Custom HTTP channels leave CORS untouched unless you opt in. Pass `cors: true`
@@ -125,7 +160,7 @@ export default defineChannel({
});
```
-`WS()` handlers receive the same helpers as HTTP route handlers: `send`, `cancel`, `getSession`, `receive`, `params`, `waitUntil`, and `requestIp`. The returned hooks are eve-owned structural types compatible with Nitro/H3 websocket routing, including `upgrade`, `open`, `message`, `close`, and `error`.
+`WS()` handlers receive the same helpers as HTTP route handlers: `send`, `cancel`, `reset`, `getSession`, `receive`, `params`, `waitUntil`, and `requestIp`. The returned hooks are eve-owned structural types compatible with Nitro/H3 websocket routing, including `upgrade`, `open`, `message`, `close`, and `error`.
### Node upgrade server escape hatch
@@ -245,6 +280,8 @@ Custom channels write their own function that joins the identity fields. The fra
When the identity that should address a session is not known until later, the channel can re-key the parked session by calling `session.setContinuationToken(...)`. Pass the channel-local raw token; the runtime preserves the current channel namespace.
+Re-keying changes the address of the current session. `reset` is different: it terminally retires the current session and makes its existing address available to a later `send()`. `cancel` is narrower still: it stops only the active turn and leaves the session, history, and continuation-token ownership intact.
+
The `context(state, session)` config option builds the per-step `channel` argument handed to every event handler. It receives the channel's live adapter `state` and a `SessionHandle`, and returns the channel-owned context (thread handles, API clients, late-bound callbacks). The framework injects [`ChannelSessionOps`](#define-a-channel) and passes the result as the second positional argument to each handler. Closing over `session` lets the factory register callbacks that re-key the session later. State mutations made through the returned context are written back to adapter state.
```ts
diff --git a/docs/reference/cli.md b/docs/reference/cli.md
index e0cdd1bb3..abf5d590f 100644
--- a/docs/reference/cli.md
+++ b/docs/reference/cli.md
@@ -173,7 +173,7 @@ For bearer tokens or custom schemes, pass explicit headers with `-H`.
Local dev records the last ready URL per resolved app root in `.eve/dev-server-state.v1.json`. A second interactive `eve dev` reconnects only when that URL is loopback and healthy; each terminal UI creates a fresh client session while sharing the server process. A stale or malformed record is replaced when eve starts a new server. Passing `--host`, `--port`, or a `PORT` environment value skips reconnection and reports a healthy recorded server instead.
-Local dev keeps immutable runtime source snapshots under `.eve/dev-runtime/snapshots/` so in-flight turns hold a consistent code revision while new turns pick up rebuilds. The terminal REPL keeps its logical session across successful rebuilds, so the next turn continues the conversation on the latest generation; use `/new` to start a fresh session. After a generation is superseded, `eve dev` retains it for at least 30 minutes and also retains the five most recently superseded generations, regardless of the configured Workflow World. The active generation is never pruned. Old runtime snapshots and local sandbox templates are pruned in the background. For manual cleanup, stop `eve dev` before deleting `.eve/dev-runtime/snapshots/` or `.eve/sandbox-cache/local/templates/`. A turn that remains unfinished beyond the automatic retention window can no longer resume after its generation is pruned.
+Local dev keeps immutable runtime source snapshots under `.eve/dev-runtime/snapshots/` so in-flight turns hold a consistent code revision while new turns pick up rebuilds. The terminal REPL keeps its logical session across successful rebuilds, so the next turn continues the conversation on the latest generation; `/new` terminally retires that session before clearing the transcript, and the next prompt starts a fresh session with a new session-scoped sandbox on first sandbox use. After a generation is superseded, `eve dev` retains it for at least 30 minutes and also retains the five most recently superseded generations, regardless of the configured Workflow World. The active generation is never pruned. Old runtime snapshots and local sandbox templates are pruned in the background. For manual cleanup, stop `eve dev` before deleting `.eve/dev-runtime/snapshots/` or `.eve/sandbox-cache/local/templates/`. A turn that remains unfinished beyond the automatic retention window can no longer resume after its generation is pruned.
## `eve logs`
diff --git a/e2e/fixtures/agent-cancellation/agent/channels/threads.ts b/e2e/fixtures/agent-cancellation/agent/channels/threads.ts
index 1ca673924..e192c49f9 100644
--- a/e2e/fixtures/agent-cancellation/agent/channels/threads.ts
+++ b/e2e/fixtures/agent-cancellation/agent/channels/threads.ts
@@ -11,8 +11,8 @@ const AUTH = {
* Chat-style channel for the continuation-addressed cancellation eval.
*
* Messages address a thread by channel-local continuation token. The stop
- * route cancels the thread's active turn through the public `cancel` route
- * helper without knowing the runtime session id.
+ * and reset routes act through public channel helpers without knowing the
+ * runtime session id.
*/
export default defineChannel({
routes: [
@@ -28,5 +28,16 @@ export default defineChannel({
const result = await cancel({ continuationToken: params.threadId ?? "" });
return Response.json(result);
}),
+ POST("/threads/:threadId/new", async (_request, { params, reset }) => {
+ const result = await reset({
+ continuationToken: params.threadId ?? "",
+ reason: "E2E user requested /new",
+ });
+ return Response.json({ acknowledgement: "Started a new conversation.", ...result });
+ }),
+ POST("/threads/:threadId/owner", async (_request, { params, resolveActiveSession }) => {
+ const owner = await resolveActiveSession({ continuationToken: params.threadId ?? "" });
+ return Response.json({ sessionId: owner?.sessionId ?? null });
+ }),
],
});
diff --git a/e2e/fixtures/agent-cancellation/evals/cancellation/reset-channel-session.eval.ts b/e2e/fixtures/agent-cancellation/evals/cancellation/reset-channel-session.eval.ts
new file mode 100644
index 000000000..eabe81ce5
--- /dev/null
+++ b/e2e/fixtures/agent-cancellation/evals/cancellation/reset-channel-session.eval.ts
@@ -0,0 +1,104 @@
+import { defineEval, type EveEvalTargetHandle } from "eve/evals";
+import { satisfies } from "eve/evals/expect";
+
+interface MessageResponse {
+ readonly ok: boolean;
+ readonly sessionId?: string;
+}
+
+interface ResetResponse {
+ readonly acknowledgement?: string;
+ readonly previousSessionId?: string;
+ readonly status?: "no_active_session" | "reset";
+}
+
+interface OwnerResponse {
+ readonly sessionId: string | null;
+}
+
+async function postJson<T>(target: EveEvalTargetHandle, path: string, body: unknown): Promise<T> {
+ const response = await target.fetch(path, {
+ body: JSON.stringify(body),
+ headers: { "content-type": "application/json" },
+ method: "POST",
+ });
+ const text = await response.text();
+ if (!response.ok) {
+ throw new Error(`POST ${path} failed (${response.status}): ${text}`);
+ }
+ return JSON.parse(text) as T;
+}
+
+/**
+ * Reset a parked continuation-addressed conversation from a custom channel.
+ *
+ * The reset route does not call `send`: after its fixed acknowledgement the
+ * token has no owner. The next ordinary message claims the same thread token
+ * for a different workflow session.
+ */
+export default defineEval({
+ description: "Reset a custom-channel session without creating a model turn for /new.",
+ timeoutMs: 240_000,
+
+ async test(t) {
+ const threadId = crypto.randomUUID();
+ const initial = await postJson<MessageResponse>(t.target, `/threads/${threadId}/messages`, {
+ message: "Reply with exactly RESET-INITIAL-OK.",
+ });
+ await t.require(
+ initial,
+ satisfies(
+ (value: MessageResponse) => value.ok === true && typeof value.sessionId === "string",
+ "the initial message starts a session",
+ ),
+ );
+ const previousSessionId = initial.sessionId!;
+
+ const initialTurn = await t.target.watchTurn(previousSessionId).result();
+ initialTurn.notEvent("turn.failed");
+ initialTurn.notEvent("session.failed");
+ initialTurn.messageIncludes(/RESET-INITIAL-OK/i);
+
+ const reset = await postJson<ResetResponse>(t.target, `/threads/${threadId}/new`, {});
+ await t.require(
+ reset,
+ satisfies(
+ (value: ResetResponse) =>
+ value.status === "reset" &&
+ value.previousSessionId === previousSessionId &&
+ value.acknowledgement === "Started a new conversation.",
+ "the route retires the observed session and returns its fixed acknowledgement",
+ ),
+ );
+
+ const afterReset = await postJson<OwnerResponse>(t.target, `/threads/${threadId}/owner`, {});
+ await t.require(
+ afterReset,
+ satisfies(
+ (value: OwnerResponse) => value.sessionId === null,
+ "/new does not start a replacement model session",
+ ),
+ );
+
+ const replacement = await postJson<MessageResponse>(t.target, `/threads/${threadId}/messages`, {
+ message: "Reply with exactly RESET-REPLACEMENT-OK.",
+ });
+ await t.require(
+ replacement,
+ satisfies(
+ (value: MessageResponse) =>
+ value.ok === true &&
+ typeof value.sessionId === "string" &&
+ value.sessionId !== previousSessionId,
+ "the same thread token starts a fresh session after reset",
+ ),
+ );
+
+ const replacementTurn = await t.target.watchTurn(replacement.sessionId!).result();
+ replacementTurn.notEvent("turn.failed");
+ replacementTurn.notEvent("session.failed");
+ replacementTurn.messageIncludes(/RESET-REPLACEMENT-OK/i);
+
+ t.succeeded();
+ },
+});
diff --git a/packages/eve/src/channel/cancel.test.ts b/packages/eve/src/channel/cancel.test.ts
index ece8ff54c..7537af253 100644
--- a/packages/eve/src/channel/cancel.test.ts
+++ b/packages/eve/src/channel/cancel.test.ts
@@ -10,6 +10,7 @@ function createRuntime(overrides?: Partial<Runtime>): Runtime {
getEventStream: vi.fn(),
resolveSession: vi.fn().mockResolvedValue({ sessionId: "sess_1" }),
run: vi.fn(),
+ terminateSession: vi.fn(),
...overrides,
};
}
diff --git a/packages/eve/src/channel/cross-channel-receive.test.ts b/packages/eve/src/channel/cross-channel-receive.test.ts
index fad69c062..514b63c10 100644
--- a/packages/eve/src/channel/cross-channel-receive.test.ts
+++ b/packages/eve/src/channel/cross-channel-receive.test.ts
@@ -15,6 +15,7 @@ function makeRuntime(): Runtime {
getEventStream: vi.fn(),
resolveSession: vi.fn(),
run: vi.fn(),
+ terminateSession: vi.fn(),
};
}
diff --git a/packages/eve/src/channel/reset-session.test.ts b/packages/eve/src/channel/reset-session.test.ts
new file mode 100644
index 000000000..d42024637
--- /dev/null
+++ b/packages/eve/src/channel/reset-session.test.ts
@@ -0,0 +1,82 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { createResetFn } from "#channel/reset-session.js";
+import type { Runtime } from "#channel/types.js";
+
+function createRuntime(overrides?: Partial<Runtime>): Runtime {
+ return {
+ cancelTurn: vi.fn(),
+ deliver: vi.fn(),
+ getEventStream: vi.fn(),
+ resolveSession: vi.fn().mockResolvedValue({ sessionId: "sess_1" }),
+ run: vi.fn(),
+ terminateSession: vi.fn().mockResolvedValue({ status: "terminated" }),
+ ...overrides,
+ };
+}
+
+describe("createResetFn", () => {
+ it("namespaces the channel-local token before resolving its owner", async () => {
+ const runtime = createRuntime();
+
+ await createResetFn(runtime, "imessage")({ continuationToken: "direct:+1:+2" });
+
+ expect(runtime.resolveSession).toHaveBeenCalledWith("imessage:direct:+1:+2");
+ });
+
+ it("returns no_active_session without terminating when no session owns the token", async () => {
+ const runtime = createRuntime({ resolveSession: vi.fn().mockResolvedValue(undefined) });
+
+ await expect(
+ createResetFn(runtime, "imessage")({ continuationToken: "direct:+1:+2" }),
+ ).resolves.toEqual({ status: "no_active_session" });
+ expect(runtime.terminateSession).not.toHaveBeenCalled();
+ });
+
+ it("terminates the observed session id once and returns it", async () => {
+ const runtime = createRuntime();
+
+ await expect(
+ createResetFn(
+ runtime,
+ "imessage",
+ )({
+ continuationToken: "direct:+1:+2",
+ reason: "User requested /new",
+ }),
+ ).resolves.toEqual({ status: "reset", previousSessionId: "sess_1" });
+ expect(runtime.terminateSession).toHaveBeenCalledWith({
+ reason: "User requested /new",
+ sessionId: "sess_1",
+ });
+ expect(runtime.resolveSession).toHaveBeenCalledOnce();
+ });
+
+ it("treats an already-terminal observed owner as a successful reset", async () => {
+ const runtime = createRuntime({
+ terminateSession: vi.fn().mockResolvedValue({ status: "already_terminal" }),
+ });
+
+ await expect(
+ createResetFn(runtime, "imessage")({ continuationToken: "direct:+1:+2" }),
+ ).resolves.toEqual({ status: "reset", previousSessionId: "sess_1" });
+ });
+
+ it("propagates unexpected resolution and termination failures", async () => {
+ const resolutionFailure = new Error("World unavailable");
+ const resolutionRuntime = createRuntime({
+ resolveSession: vi.fn().mockRejectedValue(resolutionFailure),
+ });
+ await expect(
+ createResetFn(resolutionRuntime, "imessage")({ continuationToken: "direct:+1:+2" }),
+ ).rejects.toBe(resolutionFailure);
+
+ const terminationFailure = new Error("World unavailable");
+ const terminationRuntime = createRuntime({
+ terminateSession: vi.fn().mockRejectedValue(terminationFailure),
+ });
+ await expect(
+ createResetFn(terminationRuntime, "imessage")({ continuationToken: "direct:+1:+2" }),
+ ).rejects.toBe(terminationFailure);
+ });
+});
diff --git a/packages/eve/src/channel/reset-session.ts b/packages/eve/src/channel/reset-session.ts
new file mode 100644
index 000000000..fafb8378c
--- /dev/null
+++ b/packages/eve/src/channel/reset-session.ts
@@ -0,0 +1,22 @@
+import type { ResetFn, ResetOptions, ResetResult } from "#channel/routes.js";
+import type { Runtime } from "#channel/types.js";
+
+/**
+ * Builds a channel-scoped session reset helper. It resolves an owner once and
+ * retires that observed session id, so it can never cancel a later owner that
+ * claimed the same continuation token.
+ */
+export function createResetFn(runtime: Runtime, channelName: string): ResetFn {
+ return async (options: ResetOptions): Promise<ResetResult> => {
+ const continuationToken = `${channelName}:${options.continuationToken}`;
+ const owner = await runtime.resolveSession(continuationToken);
+
+ if (owner === undefined) {
+ return { status: "no_active_session" };
+ }
+
+ await runtime.terminateSession({ reason: options.reason, sessionId: owner.sessionId });
+
+ return { status: "reset", previousSessionId: owner.sessionId };
+ };
+}
diff --git a/packages/eve/src/channel/resolve-active-session.test.ts b/packages/eve/src/channel/resolve-active-session.test.ts
index 99f1426c5..0c0f8711d 100644
--- a/packages/eve/src/channel/resolve-active-session.test.ts
+++ b/packages/eve/src/channel/resolve-active-session.test.ts
@@ -10,6 +10,7 @@ function runtime(): Runtime {
getEventStream: vi.fn().mockResolvedValue(new ReadableStream()),
resolveSession: vi.fn(),
run: vi.fn(),
+ terminateSession: vi.fn(),
};
}
diff --git a/packages/eve/src/channel/routes.ts b/packages/eve/src/channel/routes.ts
index 2273430ed..aa8b43b8d 100644
--- a/packages/eve/src/channel/routes.ts
+++ b/packages/eve/src/channel/routes.ts
@@ -13,7 +13,8 @@ type WebSocketHeaders = Headers | readonly (readonly [string, string])[] | Recor
/**
* Second argument passed to every route handler. `send` starts or continues a
* session on this channel; `cancel` stops the active turn on a session
- * addressed by continuation token; `getSession` looks one up by id; `receive`
+ * addressed by continuation token; `reset` retires a session so its
+ * token can start a fresh session; `getSession` looks one up by id; `receive`
* hands inbound work to a different channel; `params` contains the matched
* path parameters; `waitUntil` keeps background work alive past the response;
* `requestIp` is the client IP, or `null` when the host cannot provide it.
@@ -26,6 +27,7 @@ export interface RouteHandlerArgs<TState = undefined> {
*/
resolveActiveSession: ResolveActiveSessionFn;
cancel: CancelFn;
+ reset: ResetFn;
getSession: GetSessionFn;
/**
* Starts a session on a different channel to hand off inbound work (e.g. an
@@ -123,6 +125,27 @@ export interface CancelOptions {
*/
export type CancelFn = (options: CancelOptions) => Promise<CancelTurnResult>;
+/** Options for {@link ResetFn}. */
+export interface ResetOptions {
+ /** Channel-local raw token, in the same format accepted by {@link SendFn}. */
+ readonly continuationToken: string;
+ /** Human-readable terminal reason. Do not include credentials or message contents. */
+ readonly reason?: string;
+}
+
+/** Result of resetting the session that owned a continuation token. */
+export type ResetResult =
+ | { readonly status: "reset"; readonly previousSessionId: string }
+ | { readonly status: "no_active_session" };
+
+/**
+ * Terminally retires the session currently owning a continuation token.
+ * The token is available for the next {@link SendFn} after this resolves;
+ * that send starts with fresh history and state, and initializes a new
+ * session-scoped sandbox on first sandbox use.
+ */
+export type ResetFn = (options: ResetOptions) => Promise<ResetResult>;
+
export type RouteHandler<TState = undefined> = (
req: Request,
args: RouteHandlerArgs<TState>,
diff --git a/packages/eve/src/channel/schedule.test.ts b/packages/eve/src/channel/schedule.test.ts
index 29021d212..3cb6e58b5 100644
--- a/packages/eve/src/channel/schedule.test.ts
+++ b/packages/eve/src/channel/schedule.test.ts
@@ -10,6 +10,7 @@ import {
ScheduleDispatcher,
} from "#channel/schedule.js";
import type { RunHandle, Runtime } from "#channel/types.js";
+import { RuntimeNoActiveSessionError } from "#execution/runtime-errors.js";
import { slackChannel } from "#public/channels/slack/slackChannel.js";
import type { ResolvedChannelDefinition } from "#runtime/types.js";
@@ -24,10 +25,11 @@ function createMockRunHandle(): RunHandle {
function createMockRuntime(): Runtime {
return {
cancelTurn: vi.fn(),
- deliver: vi.fn().mockRejectedValue(new Error("no parked session")),
+ deliver: vi.fn().mockRejectedValue(new RuntimeNoActiveSessionError("schedule:token")),
resolveSession: vi.fn(),
run: vi.fn().mockResolvedValue(createMockRunHandle()),
getEventStream: vi.fn().mockResolvedValue(new ReadableStream<HandleMessageStreamEvent>()),
+ terminateSession: vi.fn(),
};
}
diff --git a/packages/eve/src/channel/send.test.ts b/packages/eve/src/channel/send.test.ts
index f93285e0f..adf07c8fb 100644
--- a/packages/eve/src/channel/send.test.ts
+++ b/packages/eve/src/channel/send.test.ts
@@ -21,6 +21,7 @@ function createRuntime(deliverError: unknown): Runtime {
resolveSession: vi.fn(),
run: vi.fn().mockResolvedValue(createMockRunHandle()),
getEventStream: vi.fn().mockResolvedValue(new ReadableStream<HandleMessageStreamEvent>()),
+ terminateSession: vi.fn(),
};
}
@@ -50,22 +51,14 @@ describe("createSendFn", () => {
warn.mockRestore();
});
- it("warns and falls back to a new session when delivery fails unexpectedly", async () => {
- const runtime = createRuntime(new Error("boom"));
- const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ it("propagates unexpected delivery failures without starting a new session", async () => {
+ const failure = new Error("boom");
+ const runtime = createRuntime(failure);
const send = createSendFn(runtime, ADAPTER, "test");
- const session = await send("hello", {
- auth: null,
- continuationToken: "token",
- });
+ await expect(send("hello", { auth: null, continuationToken: "token" })).rejects.toBe(failure);
- expect(session.id).toBe("mock-session-id");
- expect(warn).toHaveBeenCalledTimes(1);
- const payload = warn.mock.calls[0]?.[0];
- expect(String(payload)).toContain("deliver failed");
-
- warn.mockRestore();
+ expect(runtime.run).not.toHaveBeenCalled();
});
it("rejects inputResponses when no active session exists", async () => {
@@ -91,6 +84,7 @@ describe("createSendFn", () => {
resolveSession: vi.fn(),
run: vi.fn().mockResolvedValue(createMockRunHandle()),
getEventStream: vi.fn().mockResolvedValue(new ReadableStream<HandleMessageStreamEvent>()),
+ terminateSession: vi.fn(),
};
const deliverSend = createSendFn(deliverRuntime, ADAPTER, "test");
@@ -124,6 +118,7 @@ describe("createSendFn", () => {
resolveSession: vi.fn(),
run: vi.fn().mockResolvedValue(createMockRunHandle()),
getEventStream: vi.fn().mockResolvedValue(new ReadableStream<HandleMessageStreamEvent>()),
+ terminateSession: vi.fn(),
};
const deliverSend = createSendFn(deliverRuntime, ADAPTER, "test", {
@@ -152,6 +147,7 @@ describe("createSendFn", () => {
resolveSession: vi.fn(),
run: vi.fn().mockResolvedValue(createMockRunHandle()),
getEventStream: vi.fn().mockResolvedValue(new ReadableStream<HandleMessageStreamEvent>()),
+ terminateSession: vi.fn(),
};
const deliverSend = createSendFn(deliverRuntime, ADAPTER, "test");
diff --git a/packages/eve/src/channel/send.ts b/packages/eve/src/channel/send.ts
index 145907741..a4fe110aa 100644
--- a/packages/eve/src/channel/send.ts
+++ b/packages/eve/src/channel/send.ts
@@ -6,9 +6,6 @@ import { createSession, type Session } from "#channel/session.js";
import type { SendFn, SendOptions, SendPayload } from "#channel/routes.js";
import { isRuntimeNoActiveSessionError } from "#execution/runtime-errors.js";
import { serializeUrlFilePart } from "#internal/attachments/url-refs.js";
-import { createLogger } from "#internal/logging.js";
-
-const log = createLogger("channel.send");
export function createSendFn<TState = undefined>(
runtime: Runtime,
@@ -47,12 +44,8 @@ export function createSendFn<TState = undefined>(
return createSession(sessionId, rawToken, runtime);
} catch (error) {
- // No-active-session is the expected resume-or-start signal. The
- // failure itself is logged in `deliver`; this only records the fallback.
if (!isRuntimeNoActiveSessionError(error)) {
- log.warn("deliver failed, falling back to starting a new session", {
- continuationToken,
- });
+ throw error;
}
}
diff --git a/packages/eve/src/channel/session.test.ts b/packages/eve/src/channel/session.test.ts
index f41c30f72..f15a5ceed 100644
--- a/packages/eve/src/channel/session.test.ts
+++ b/packages/eve/src/channel/session.test.ts
@@ -12,6 +12,7 @@ function createRuntime(): Runtime {
getEventStream: vi.fn(),
resolveSession: vi.fn(),
run: vi.fn(),
+ terminateSession: vi.fn(),
};
}
diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.ts
index 970c9f6d5..d57472b7c 100644
--- a/packages/eve/src/channel/types.ts
+++ b/packages/eve/src/channel/types.ts
@@ -31,6 +31,18 @@ export interface CancelTurnResult {
readonly status: CancelTurnStatus;
}
+/** Identifies a session to transition permanently to a terminal state. */
+export interface TerminateSessionInput {
+ /** Human-readable reason recorded on the terminal workflow transition. */
+ readonly reason?: string;
+ readonly sessionId: string;
+}
+
+/** Result of attempting to terminally retire a session. */
+export type TerminateSessionResult =
+ | { readonly status: "terminated" }
+ | { readonly status: "already_terminal" };
+
// ---------------------------------------------------------------------------
// Lineage
// ---------------------------------------------------------------------------
@@ -383,6 +395,9 @@ export interface Runtime {
/** Requests cancellation of a session's in-flight turn. */
cancelTurn(input: CancelTurnInput): Promise<CancelTurnResult>;
+ /** Terminally retires a session and releases its non-retained continuation hooks. */
+ terminateSession(input: TerminateSessionInput): Promise<TerminateSessionResult>;
+
/**
* Delivers a follow-up message to a parked session.
*/
diff --git a/packages/eve/src/cli/dev/tui/runner.test.ts b/packages/eve/src/cli/dev/tui/runner.test.ts
index 76ad8337f..7971c7d9b 100644
--- a/packages/eve/src/cli/dev/tui/runner.test.ts
+++ b/packages/eve/src/cli/dev/tui/runner.test.ts
@@ -604,6 +604,9 @@ describe("EveTUIRunner development session continuity", () => {
it("starts a fresh session only after an explicit /new command", async () => {
const initialSession = sessionYielding([{ type: "session.waiting" }]);
+ const reset = vi
+ .spyOn(initialSession, "reset")
+ .mockResolvedValue({ previousSessionId: "session_1", status: "reset" });
const newSession = sessionYielding([{ type: "session.waiting" }]);
const client = stubClient();
const createSession = vi.spyOn(client, "session").mockReturnValue(newSession);
@@ -625,9 +628,66 @@ describe("EveTUIRunner development session continuity", () => {
await runner.run();
expect(createSession).toHaveBeenCalledOnce();
+ expect(reset).toHaveBeenCalledOnce();
expect(initialSession.send).toHaveBeenCalledOnce();
expect(newSession.send).toHaveBeenCalledOnce();
});
+
+ it("keeps the current transcript and session when /new cannot reset the owner", async () => {
+ const session = sessionYielding([]);
+ const reset = vi.spyOn(session, "reset").mockRejectedValue(new Error("World unavailable"));
+ const resetRenderer = vi.fn();
+ const notices: string[] = [];
+ const prompts: Array<string | undefined> = ["/new", undefined];
+ const runner = new EveTUIRunner({
+ name: "Weather Agent",
+ renderer: fakeRenderer({
+ readPrompt: vi.fn(async () => prompts.shift()),
+ renderNotice: (message) => notices.push(message),
+ reset: resetRenderer,
+ }),
+ session,
+ });
+
+ await runner.run();
+
+ expect(reset).toHaveBeenCalledOnce();
+ expect(resetRenderer).not.toHaveBeenCalled();
+ expect(notices).toEqual(["Couldn't reset the session: World unavailable"]);
+ });
+
+ it("resets rather than sending a queued /new after a turn boundary", async () => {
+ const initialSession = sessionYielding([{ type: "session.waiting" }]);
+ const reset = vi
+ .spyOn(initialSession, "reset")
+ .mockResolvedValue({ previousSessionId: "session_1", status: "reset" });
+ const newSession = sessionYielding([]);
+ const client = stubClient();
+ const createSession = vi.spyOn(client, "session").mockReturnValue(newSession);
+ const prompts: Array<string | undefined> = ["first", undefined];
+ const renderer = fakeRenderer({
+ readPrompt: vi.fn(async () => prompts.shift()),
+ renderStream: vi.fn(async (result) => {
+ for await (const event of result.events as AsyncIterable<unknown>) {
+ void event;
+ }
+ }),
+ takeQueuedPrompt: vi.fn(() => "/new"),
+ });
+ const runner = new EveTUIRunner({
+ client,
+ name: "Weather Agent",
+ renderer,
+ session: initialSession,
+ });
+
+ await runner.run();
+
+ expect(reset).toHaveBeenCalledOnce();
+ expect(createSession).toHaveBeenCalledOnce();
+ expect(initialSession.send).toHaveBeenCalledOnce();
+ expect(newSession.send).not.toHaveBeenCalled();
+ });
});
describe("EveTUIRunner terminal-failure recovery", () => {
diff --git a/packages/eve/src/cli/dev/tui/runner.ts b/packages/eve/src/cli/dev/tui/runner.ts
index 850e7973e..fe3bcf84c 100644
--- a/packages/eve/src/cli/dev/tui/runner.ts
+++ b/packages/eve/src/cli/dev/tui/runner.ts
@@ -763,11 +763,15 @@ export class EveTUIRunner {
}
if (command?.type === "new") {
- this.#startNewSession();
+ if (!(await this.#resetCurrentSession())) {
+ pendingInputResponses = undefined;
+ streamWithoutPrompt = false;
+ prompt = undefined;
+ continue;
+ }
pendingInputResponses = undefined;
streamWithoutPrompt = false;
prompt = undefined;
- this.#renderer.reset?.();
continue;
}
@@ -986,6 +990,20 @@ export class EveTUIRunner {
this.#runtimeArtifacts?.clear();
}
+ /** Resets the durable owner before clearing the local conversation view. */
+ async #resetCurrentSession(): Promise<boolean> {
+ try {
+ await this.#session.reset();
+ } catch (error) {
+ this.#renderer.renderNotice?.(`Couldn't reset the session: ${toErrorMessage(error)}`);
+ return false;
+ }
+
+ this.#startNewSession();
+ this.#renderer.reset?.();
+ return true;
+ }
+
async #readPromptWithIdleRefresh(options: AgentTUISessionOptions): Promise<string | undefined> {
if (!this.#renderer.readPrompt) {
return undefined;
diff --git a/packages/eve/src/client/index.ts b/packages/eve/src/client/index.ts
index d531d3795..fa0c477b7 100644
--- a/packages/eve/src/client/index.ts
+++ b/packages/eve/src/client/index.ts
@@ -49,6 +49,7 @@ export type {
HeadersValue,
HealthResult,
MessageResult,
+ ResetResult,
ResolvedStreamReconnectPolicy,
SendTurnInput,
SendTurnPayload,
diff --git a/packages/eve/src/client/session.test.ts b/packages/eve/src/client/session.test.ts
index 0f720905c..c9f184d56 100644
--- a/packages/eve/src/client/session.test.ts
+++ b/packages/eve/src/client/session.test.ts
@@ -131,6 +131,80 @@ describe("ClientSession", () => {
await expect(session.cancel()).rejects.toThrow("Cancel route returned an invalid response");
});
+ it("resets the continuation owner and clears the local session state", async () => {
+ let headerResolution = 0;
+ const requests: Array<{ headers: Headers; method: string; url: string; body?: string }> = [];
+ vi.spyOn(globalThis, "fetch").mockImplementation(async (request, init) => {
+ const url =
+ typeof request === "string" ? request : request instanceof URL ? request.href : request.url;
+ requests.push({
+ body: typeof init?.body === "string" ? init.body : undefined,
+ headers: new Headers(init?.headers),
+ method: init?.method ?? "GET",
+ url,
+ });
+ return Response.json({
+ ok: true,
+ previousSessionId: "session_1",
+ status: "reset",
+ });
+ });
+ const session = createSession(
+ { continuationToken: "eve:test", sessionId: "session_1", streamIndex: 4 },
+ {
+ redirect: "error",
+ resolveHeaders: async () => {
+ headerResolution += 1;
+ return new Headers({ authorization: `Bearer token-${headerResolution}` });
+ },
+ },
+ );
+
+ await expect(session.reset()).resolves.toEqual({
+ previousSessionId: "session_1",
+ status: "reset",
+ });
+
+ expect(session.state).toEqual({ streamIndex: 0 });
+ expect(requests).toHaveLength(1);
+ expect(new URL(requests[0]!.url).pathname).toBe("/eve/v1/session/reset");
+ expect(requests[0]!.method).toBe("POST");
+ expect(requests[0]!.headers.get("authorization")).toBe("Bearer token-1");
+ expect(JSON.parse(requests[0]!.body ?? "{}")).toEqual({ continuationToken: "eve:test" });
+ });
+
+ it("treats a never-started session as already reset", async () => {
+ const fetchMock = vi.spyOn(globalThis, "fetch");
+ const session = createSession();
+
+ await expect(session.reset()).resolves.toEqual({ status: "no_active_session" });
+
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(session.state).toEqual({ streamIndex: 0 });
+ });
+
+ it("refuses to discard a session that has no continuation token", async () => {
+ const session = createSession({ sessionId: "session_1", streamIndex: 4 });
+
+ await expect(session.reset()).rejects.toThrow("Consume its event stream before resetting");
+ expect(session.state).toEqual({ sessionId: "session_1", streamIndex: 4 });
+ });
+
+ it("preserves the local session when the reset response names another owner", async () => {
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ Response.json({
+ ok: true,
+ previousSessionId: "another-session",
+ status: "reset",
+ }),
+ );
+ const state = { continuationToken: "eve:test", sessionId: "session_1", streamIndex: 4 };
+ const session = createSession(state);
+
+ await expect(session.reset()).rejects.toThrow("Reset route returned an invalid response");
+ expect(session.state).toEqual(state);
+ });
+
it("serializes clientContext when sending a create-session message", async () => {
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(createAcceptedResponse());
const session = createSession();
diff --git a/packages/eve/src/client/session.ts b/packages/eve/src/client/session.ts
index 69b922d0e..e07096433 100644
--- a/packages/eve/src/client/session.ts
+++ b/packages/eve/src/client/session.ts
@@ -1,20 +1,23 @@
import type { HandleMessageStreamEvent } from "#protocol/message.js";
import { EVE_SESSION_ID_HEADER, isCurrentTurnBoundaryEvent } from "#protocol/message.js";
import { CancelTurnResponseSchema } from "#protocol/cancel-turn.js";
+import { ResetResponseSchema } from "#protocol/reset-session.js";
import {
EVE_CREATE_SESSION_ROUTE_PATH,
+ EVE_RESET_SESSION_ROUTE_PATH,
createEveCancelTurnRoutePath,
createEveContinueSessionRoutePath,
} from "#protocol/routes.js";
import { ClientError } from "#client/client-error.js";
import { MessageResponse } from "#client/message-response.js";
import { followStreamIterable } from "#client/open-stream.js";
-import { advanceSession } from "#client/session-utils.js";
+import { advanceSession, createInitialSessionState } from "#client/session-utils.js";
import { serializeOutputSchema } from "#shared/tool-schema.js";
import { createClientUrl } from "#client/url.js";
import type {
CancelSessionResult,
ClientRedirectPolicy,
+ ResetResult,
SendTurnInput,
SendTurnPayload,
SessionState,
@@ -77,7 +80,9 @@ export class ClientSession {
// Cancellation and observation can begin as soon as the POST is accepted,
// before the response stream reaches a turn boundary.
if (this.#state === state) {
- this.#state = { ...state, sessionId };
+ const nextState = { ...state, sessionId };
+ if (continuationToken !== undefined) nextState.continuationToken = continuationToken;
+ this.#state = nextState;
}
return new MessageResponse<TOutput>({
@@ -141,6 +146,80 @@ export class ClientSession {
return { sessionId: result.data.sessionId, status: result.data.status };
}
+ /**
+ * Terminally retires the session that owns this handle's continuation token.
+ *
+ * Unlike {@link cancel}, reset does not merely stop an active turn: it
+ * releases the durable workflow owner so the next {@link send} creates a
+ * fresh conversation and initializes a new session-scoped sandbox on first
+ * sandbox use. Resetting a never-started handle is a successful no-op. After
+ * a successful reset, this handle has no session state.
+ *
+ * @throws {ClientError} If the reset route returns a non-successful status.
+ */
+ async reset(): Promise<ResetResult> {
+ const state = this.#state;
+ const continuationToken = state.continuationToken;
+
+ if (continuationToken === undefined) {
+ if (state.sessionId !== undefined) {
+ throw new Error(
+ "Session has no continuation token. Consume its event stream before resetting.",
+ );
+ }
+ this.#state = createInitialSessionState();
+ return { status: "no_active_session" };
+ }
+
+ const url = createClientUrl(this.#context.host, EVE_RESET_SESSION_ROUTE_PATH);
+ const headers = await this.#context.resolveHeaders();
+ headers.set("content-type", "application/json");
+
+ const response = await fetch(
+ url,
+ withRedirectPolicy(
+ {
+ body: JSON.stringify({ continuationToken }),
+ headers,
+ method: "POST",
+ },
+ this.#context.redirect,
+ ),
+ );
+ const body = await response.text();
+
+ if (!response.ok) {
+ throw new ClientError(response.status, body, response.headers);
+ }
+
+ let payload: unknown;
+ try {
+ payload = JSON.parse(body);
+ } catch {
+ throw new Error(`Reset route returned invalid JSON (${response.status}).`);
+ }
+
+ const result = ResetResponseSchema.safeParse(payload);
+ if (!result.success) {
+ throw new Error(`Reset route returned an invalid response (${response.status}).`);
+ }
+ if (
+ result.data.status === "reset" &&
+ state.sessionId !== undefined &&
+ result.data.previousSessionId !== state.sessionId
+ ) {
+ throw new Error(`Reset route returned an invalid response (${response.status}).`);
+ }
+
+ if (this.#state === state) {
+ this.#state = createInitialSessionState();
+ }
+
+ return result.data.status === "reset"
+ ? { previousSessionId: result.data.previousSessionId, status: "reset" }
+ : { status: "no_active_session" };
+ }
+
/**
* Opens this session's event stream for the current session ID.
*
diff --git a/packages/eve/src/client/types.ts b/packages/eve/src/client/types.ts
index e0675f11e..c9e07e6f4 100644
--- a/packages/eve/src/client/types.ts
+++ b/packages/eve/src/client/types.ts
@@ -3,6 +3,7 @@ import type { StandardJSONSchemaV1 } from "#compiled/@standard-schema/spec/index
import type { HandleMessageStreamEvent } from "#protocol/message.js";
import type { CancelTurnStatus } from "#protocol/cancel-turn.js";
+import type { ResetStatus } from "#protocol/reset-session.js";
import type { InputRequest, InputResponse } from "#runtime/input/types.js";
import type { JsonObject } from "#shared/json.js";
@@ -227,6 +228,18 @@ export interface CancelSessionResult {
readonly status: CancelTurnStatus;
}
+/** Result of terminally resetting a client session. */
+export type ResetResult =
+ | {
+ /** The prior session was retired and its continuation token released. */
+ readonly previousSessionId: string;
+ readonly status: Extract<ResetStatus, "reset">;
+ }
+ | {
+ /** The client had no continuation token or the token was already free. */
+ readonly status: Extract<ResetStatus, "no_active_session">;
+ };
+
/**
* Aggregated result of one message turn, returned by
* {@link MessageResponse.result}.
diff --git a/packages/eve/src/execution/node-step.test.ts b/packages/eve/src/execution/node-step.test.ts
index 6a77eb283..52d0c8e8c 100644
--- a/packages/eve/src/execution/node-step.test.ts
+++ b/packages/eve/src/execution/node-step.test.ts
@@ -223,6 +223,7 @@ function createNoopRuntime(): Runtime {
getEventStream: vi
.fn()
.mockRejectedValue(new Error("runtime.getEventStream should not be called in this test")),
+ terminateSession: vi.fn(),
};
}
diff --git a/packages/eve/src/execution/session-reset.integration.test.ts b/packages/eve/src/execution/session-reset.integration.test.ts
new file mode 100644
index 000000000..2369f8687
--- /dev/null
+++ b/packages/eve/src/execution/session-reset.integration.test.ts
@@ -0,0 +1,126 @@
+import { describe, expect, it } from "vitest";
+
+import { ContextContainer, contextStorage } from "#context/container.js";
+import { SessionKey } from "#context/keys.js";
+import { ensureSandboxAccess } from "#execution/sandbox/ensure.js";
+import { clearActiveSandboxHandlesForTest } from "#execution/sandbox/active-handles.js";
+import { sessionDeliveryHookWorkflow } from "#internal/testing/session-delivery-hook-workflow.js";
+import { waitForHook } from "#internal/testing/workflow-test-helpers.js";
+import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";
+import { getWorld, start } from "#internal/workflow/runtime.js";
+import { createWorkflowRuntime } from "#execution/workflow-runtime.js";
+import type { SandboxBackend } from "#public/definitions/sandbox-backend.js";
+import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
+import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
+import type { RuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";
+import type { ResolvedSandboxDefinition } from "#runtime/types.js";
+
+describe("session reset integration", () => {
+ it("releases a parked continuation token and initializes a fresh sandbox", async () => {
+ const continuationToken = "http:session-reset-immediate-reuse";
+ const runtime = createWorkflowRuntime({
+ compiledArtifactsSource: {} as RuntimeCompiledArtifactsSource,
+ });
+ const sandboxes = createSessionSandboxHarness();
+ const first = await start(sessionDeliveryHookWorkflow, [
+ { nextToken: continuationToken, token: "http:session-reset-placeholder-1" },
+ ]);
+
+ try {
+ await waitForHook(first, { token: continuationToken });
+ await expect(sandboxes.open(first.runId)).resolves.toMatchObject({ id: "sandbox-1" });
+
+ await expect(
+ runtime.terminateSession({ reason: "User requested /new", sessionId: first.runId }),
+ ).resolves.toEqual({ status: "terminated" });
+
+ await expect(runtime.resolveSession(continuationToken)).resolves.toBeUndefined();
+ await expect(getWorld().then((world) => world.runs.get(first.runId))).resolves.toMatchObject({
+ status: "cancelled",
+ });
+
+ const second = await start(sessionDeliveryHookWorkflow, [
+ { nextToken: continuationToken, token: "http:session-reset-placeholder-2" },
+ ]);
+ try {
+ await expect(waitForHook(second, { token: continuationToken })).resolves.toMatchObject({
+ runId: second.runId,
+ });
+ await expect(runtime.resolveSession(continuationToken)).resolves.toEqual({
+ sessionId: second.runId,
+ });
+ await expect(sandboxes.open(second.runId)).resolves.toMatchObject({ id: "sandbox-2" });
+ expect(sandboxes.initializedSessionIds).toEqual([first.runId, second.runId]);
+ expect(sandboxes.sessionKeys).toHaveLength(2);
+ expect(sandboxes.sessionKeys[0]).not.toBe(sandboxes.sessionKeys[1]);
+ } finally {
+ await second.cancel();
+ }
+ } finally {
+ await first.cancel();
+ clearActiveSandboxHandlesForTest();
+ }
+ });
+});
+
+function createSessionSandboxHarness() {
+ const initializedSessionIds: string[] = [];
+ const sessionKeys: string[] = [];
+ let sandboxCount = 0;
+ const backend: SandboxBackend = {
+ async create(input) {
+ sessionKeys.push(input.sessionKey);
+ sandboxCount += 1;
+ const sandbox = mockSandbox({ id: `sandbox-${sandboxCount}` });
+ return {
+ captureState: async () => ({
+ backendName: "session-reset-test",
+ metadata: {},
+ sessionKey: input.sessionKey,
+ }),
+ session: sandbox.session,
+ shutdown: async () => {},
+ useSessionFn: async () => sandbox.session,
+ };
+ },
+ name: "session-reset-test",
+ prewarm: async () => ({ reused: false }),
+ };
+ const definition: ResolvedSandboxDefinition = {
+ backend,
+ logicalPath: "agent/sandbox/sandbox.ts",
+ onSession({ ctx }) {
+ initializedSessionIds.push(ctx.session.id);
+ },
+ sourceId: "agent/sandbox/sandbox",
+ sourceKind: "module",
+ };
+ const registry: RuntimeSandboxRegistry = {
+ sandbox: {
+ definition,
+ workspaceResourceRoot: { logicalPath: "", rootEntries: [] },
+ },
+ };
+
+ return {
+ initializedSessionIds,
+ sessionKeys,
+ async open(sessionId: string) {
+ const context = new ContextContainer();
+ context.set(SessionKey, {
+ auth: { current: null, initiator: null },
+ sessionId,
+ turn: { id: "turn_0", sequence: 0 },
+ });
+ const access = await ensureSandboxAccess({
+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
+ nodeId: "__root__",
+ registry,
+ runOnSession: async (callback) => await contextStorage.run(context, callback),
+ sessionId,
+ state: null,
+ });
+ return await access.get();
+ },
+ };
+}
diff --git a/packages/eve/src/execution/turn-cancellation.integration.test.ts b/packages/eve/src/execution/turn-cancellation.integration.test.ts
index 18f90cf74..efa9695f1 100644
--- a/packages/eve/src/execution/turn-cancellation.integration.test.ts
+++ b/packages/eve/src/execution/turn-cancellation.integration.test.ts
@@ -252,6 +252,9 @@ function createCancelRouteCaller(): (
cancel: () => {
throw new Error("cancel route must not use the channel cancel helper");
},
+ reset: () => {
+ throw new Error("cancel route must not reset a session");
+ },
getSession: () => {
throw new Error("cancel route must not get a session");
},
diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.ts
index c0f8d28c7..2ab666291 100644
--- a/packages/eve/src/execution/workflow-runtime.test.ts
+++ b/packages/eve/src/execution/workflow-runtime.test.ts
@@ -15,12 +15,16 @@ import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-
const getHookByTokenMock = vi.fn();
const getRunMock = vi.fn();
+const getWorldMock = vi.fn();
const resumeHookMock = vi.fn();
+const cancelRunMock = vi.fn();
const startMock = vi.fn();
vi.mock("#compiled/@workflow/core/runtime.js", () => ({
+ cancelRun: (...args: unknown[]) => cancelRunMock(...args),
getHookByToken: (...args: unknown[]) => getHookByTokenMock(...args),
getRun: (...args: unknown[]) => getRunMock(...args),
+ getWorld: (...args: unknown[]) => getWorldMock(...args),
resumeHook: (...args: unknown[]) => resumeHookMock(...args),
start: (...args: unknown[]) => startMock(...args),
}));
@@ -32,7 +36,9 @@ vi.mock("#runtime/sessions/compiled-agent-cache.js", () => ({
afterEach(() => {
getHookByTokenMock.mockReset();
getRunMock.mockReset();
+ getWorldMock.mockReset();
resumeHookMock.mockReset();
+ cancelRunMock.mockReset();
startMock.mockReset();
vi.mocked(getCompiledRuntimeAgentBundle).mockReset();
vi.unstubAllEnvs();
@@ -183,6 +189,62 @@ describe("createWorkflowRuntime#cancelTurn", () => {
});
});
+describe("createWorkflowRuntime#terminateSession", () => {
+ function buildRuntime() {
+ return createWorkflowRuntime({ compiledArtifactsSource: {} as RuntimeCompiledArtifactsSource });
+ }
+
+ it("cancels the whole workflow run with the supplied reason", async () => {
+ const world = {};
+ getWorldMock.mockResolvedValue(world);
+ cancelRunMock.mockResolvedValue(undefined);
+
+ await expect(
+ buildRuntime().terminateSession({ reason: "User requested /new", sessionId: "session-1" }),
+ ).resolves.toEqual({ status: "terminated" });
+ expect(cancelRunMock).toHaveBeenCalledWith(world, "session-1", {
+ cancelReason: "User requested /new",
+ });
+ });
+
+ it("uses a safe default terminal reason", async () => {
+ const world = {};
+ getWorldMock.mockResolvedValue(world);
+ cancelRunMock.mockResolvedValue(undefined);
+
+ await buildRuntime().terminateSession({ sessionId: "session-1" });
+
+ expect(cancelRunMock).toHaveBeenCalledWith(world, "session-1", {
+ cancelReason: "Session reset by channel",
+ });
+ });
+
+ it("normalizes expected terminal races", async () => {
+ const { EntityConflictError, RunExpiredError, WorkflowRunNotFoundError } =
+ await import("#compiled/@workflow/errors/index.js");
+ getWorldMock.mockResolvedValue({});
+
+ for (const cause of [
+ new EntityConflictError("run is terminal"),
+ new RunExpiredError("run is terminal"),
+ new WorkflowRunNotFoundError("session-1"),
+ ]) {
+ cancelRunMock.mockRejectedValueOnce(new Error("Failed to cancel run", { cause }));
+ await expect(buildRuntime().terminateSession({ sessionId: "session-1" })).resolves.toEqual({
+ status: "already_terminal",
+ });
+ }
+ });
+
+ it("propagates unexpected World failures", async () => {
+ const failure = new Error("World unavailable");
+ getWorldMock.mockResolvedValue({});
+ cancelRunMock.mockRejectedValue(failure);
+
+ await expect(buildRuntime().terminateSession({ sessionId: "session-1" })).rejects.toBe(failure);
+ });
+});
+
describe("createWorkflowRuntime#resolveSession", () => {
function buildRuntime() {
return createWorkflowRuntime({ compiledArtifactsSource: {} as RuntimeCompiledArtifactsSource });
diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.ts
index c3de291fa..f4163c1bf 100644
--- a/packages/eve/src/execution/workflow-runtime.ts
+++ b/packages/eve/src/execution/workflow-runtime.ts
@@ -14,6 +14,8 @@ import type {
RunHandle,
RunInput,
Runtime,
+ TerminateSessionInput,
+ TerminateSessionResult,
} from "#channel/types.js";
import { serializeContext } from "#context/serialize.js";
import {
@@ -25,8 +27,10 @@ import { resolveInstalledPackageInfo } from "#internal/application/package.js";
import { isEveDevEnvironment } from "#internal/application/dev-environment.js";
import { createLogger, logError } from "#internal/logging.js";
import {
+ cancelRun,
getHookByToken,
getRun,
+ getWorld,
resumeHook,
start,
type Run,
@@ -42,6 +46,7 @@ import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-
import { buildRunContext } from "#execution/runtime-context.js";
import { parseNdjsonStream } from "#execution/ndjson-stream.js";
import { RuntimeNoActiveSessionError } from "#execution/runtime-errors.js";
+import { walkCauseChain } from "#shared/errors.js";
import {
sessionCancelHookToken,
type TurnCancelPayload,
@@ -174,6 +179,20 @@ export function createWorkflowRuntime(config: {
return await requestWorkflowTurnCancellation(input);
},
+ async terminateSession(input: TerminateSessionInput): Promise<TerminateSessionResult> {
+ try {
+ await cancelRun(await getWorld(), input.sessionId, {
+ cancelReason: input.reason ?? "Session reset by channel",
+ });
+ return { status: "terminated" };
+ } catch (error) {
+ if (isAlreadyTerminalSessionError(error)) {
+ return { status: "already_terminal" };
+ }
+ throw error;
+ }
+ },
+
async deliver(input: DeliverInput): Promise<{ sessionId: string }> {
const hookPayload: Extract<HookPayload, { kind: "deliver" }> = {
auth: input.auth,
@@ -249,6 +268,19 @@ function isInactiveCancelTarget(error: unknown): boolean {
);
}
+function isAlreadyTerminalSessionError(error: unknown): boolean {
+ for (const candidate of walkCauseChain(error)) {
+ if (
+ WorkflowRunNotFoundError.is(candidate) ||
+ RunExpiredError.is(candidate) ||
+ EntityConflictError.is(candidate)
+ ) {
+ return true;
+ }
+ }
+ return false;
+}
+
/**
* Starts a workflow on the latest deployment when latest routing applies,
* while preserving local/dev worlds that do not implement latest routing.
diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts
index 3c18fc243..3118571b3 100644
--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts
+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts
@@ -237,6 +237,7 @@ describe("dispatchChannelRequest", () => {
resolveSession: vi.fn(),
getEventStream: vi.fn().mockResolvedValue(new ReadableStream()),
run: vi.fn(),
+ terminateSession: vi.fn(),
};
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
@@ -277,6 +278,57 @@ describe("dispatchChannelRequest", () => {
);
});
+ it("supplies a channel-scoped reset helper", async () => {
+ const runtimeForTest: Runtime = {
+ cancelTurn: vi.fn(),
+ deliver: vi.fn(),
+ getEventStream: vi.fn(),
+ resolveSession: vi.fn().mockResolvedValue({ sessionId: "sess_previous" }),
+ run: vi.fn(),
+ terminateSession: vi.fn().mockResolvedValue({ status: "terminated" }),
+ };
+
+ mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
+ channels: [
+ {
+ handler: async (_req, args) =>
+ Response.json(
+ await args.reset({
+ continuationToken: "direct:+15551234567:+15557654321",
+ reason: "User requested /new",
+ }),
+ ),
+ fetch: async () => new Response("ok"),
+ logicalPath: "agent/channels/imessage.ts",
+ method: "POST",
+ name: "imessage",
+ sourceId: "channel-imessage",
+ sourceKind: "module",
+ urlPath: "/imessage",
+ } satisfies ResolvedChannelDefinition,
+ ],
+ runtime: runtimeForTest,
+ });
+
+ const response = await dispatchChannelRequest(
+ createEvent({ waitUntil: vi.fn() }),
+ "POST /imessage",
+ {} as never,
+ );
+
+ await expect(response.json()).resolves.toEqual({
+ previousSessionId: "sess_previous",
+ status: "reset",
+ });
+ expect(runtimeForTest.resolveSession).toHaveBeenCalledWith(
+ "imessage:direct:+15551234567:+15557654321",
+ );
+ expect(runtimeForTest.terminateSession).toHaveBeenCalledWith({
+ reason: "User requested /new",
+ sessionId: "sess_previous",
+ });
+ });
+
it("does not invent a channel request id when Vercel did not send one", async () => {
const runtimeForTest: Runtime = {
cancelTurn: vi.fn(),
@@ -284,6 +336,7 @@ describe("dispatchChannelRequest", () => {
resolveSession: vi.fn(),
getEventStream: vi.fn().mockResolvedValue(new ReadableStream()),
run: vi.fn(),
+ terminateSession: vi.fn(),
};
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
@@ -330,6 +383,7 @@ describe("dispatchChannelRequest", () => {
events: new ReadableStream(),
sessionId: "sess_run",
}),
+ terminateSession: vi.fn(),
};
const deliverInput = Object.freeze({
auth: null,
diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.ts
index 52915f8f6..e3684ab4d 100644
--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts
+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.ts
@@ -7,6 +7,7 @@ import {
import type { DeliverInput, RunInput, Runtime } from "#channel/types.js";
import type { RouteHandlerArgs, WebSocketRouteHooks } from "#channel/routes.js";
import { createCancelFn } from "#channel/cancel.js";
+import { createResetFn } from "#channel/reset-session.js";
import { createSendFn } from "#channel/send.js";
import { createResolveActiveSessionFn } from "#channel/resolve-active-session.js";
import { createGetSessionFn } from "#channel/session.js";
@@ -191,6 +192,7 @@ function buildRouteArgs(
const send = createSendFn(bundle.runtime, adapter, channelName, { requestId });
const resolveActiveSession = createResolveActiveSessionFn(bundle.runtime, channelName);
const cancel = createCancelFn(bundle.runtime, channelName);
+ const reset = createResetFn(bundle.runtime, channelName);
const getSession = createGetSessionFn(bundle.runtime);
const receive = createCrossChannelReceiveFn(
bundle.runtime,
@@ -203,6 +205,7 @@ function buildRouteArgs(
send,
resolveActiveSession,
cancel,
+ reset,
getSession,
receive,
params,
diff --git a/packages/eve/src/internal/testing/scenario-apps/session-reset.ts b/packages/eve/src/internal/testing/scenario-apps/session-reset.ts
new file mode 100644
index 000000000..89877ea0a
--- /dev/null
+++ b/packages/eve/src/internal/testing/scenario-apps/session-reset.ts
@@ -0,0 +1,47 @@
+import type { ScenarioAppDescriptor } from "#internal/testing/scenario-app.js";
+
+/** Vercel deployment fixture for continuation-token session reset behavior. */
+export const SESSION_RESET_DESCRIPTOR: ScenarioAppDescriptor = {
+ files: {
+ "agent/agent.ts": `import { defineAgent } from "eve";
+
+export default defineAgent({ model: "openai/gpt-5.4-mini" });
+`,
+ "agent/channels/threads.ts": `import { defineChannel, POST } from "eve/channels";
+
+const AUTH = {
+ attributes: { source: "session-reset-vercel-test" },
+ authenticator: "session-reset-vercel-test",
+ principalId: "session-reset-vercel-test",
+ principalType: "service",
+};
+
+export default defineChannel({
+ routes: [
+ POST("/session-reset/:threadId/messages", async (request, { params, send }) => {
+ const body = (await request.json().catch(() => ({}))) as { message?: string };
+ const session = await send(body.message ?? "Reply with hello.", {
+ auth: AUTH,
+ continuationToken: params.threadId ?? "",
+ });
+ return Response.json({ sessionId: session.id });
+ }),
+ POST("/session-reset/:threadId/owner", async (_request, { params, resolveActiveSession }) => {
+ const owner = await resolveActiveSession({ continuationToken: params.threadId ?? "" });
+ return Response.json({ sessionId: owner?.sessionId ?? null });
+ }),
+ POST("/session-reset/:threadId/new", async (_request, { params, reset }) => {
+ return Response.json(
+ await reset({
+ continuationToken: params.threadId ?? "",
+ reason: "Vercel session reset integration test",
+ }),
+ );
+ }),
+ ],
+});
+`,
+ "agent/instructions.md": "You are a concise test assistant.\n",
+ },
+ name: "session-reset",
+};
diff --git a/packages/eve/src/protocol/reset-session.ts b/packages/eve/src/protocol/reset-session.ts
new file mode 100644
index 000000000..dfeb72bb2
--- /dev/null
+++ b/packages/eve/src/protocol/reset-session.ts
@@ -0,0 +1,29 @@
+import { z } from "#compiled/zod/index.js";
+
+/** Outcome of retiring the owner of a continuation token. */
+export type ResetStatus = "no_active_session" | "reset";
+
+/** Successful response returned by the standard session-reset route. */
+export type ResetResponse =
+ | {
+ readonly ok: true;
+ readonly previousSessionId: string;
+ readonly status: "reset";
+ }
+ | {
+ readonly ok: true;
+ readonly status: "no_active_session";
+ };
+
+/** Validates successful responses from the standard session-reset route. */
+export const ResetResponseSchema: z.ZodType<ResetResponse> = z.discriminatedUnion("status", [
+ z.object({
+ ok: z.literal(true),
+ previousSessionId: z.string().min(1),
+ status: z.literal("reset"),
+ }),
+ z.object({
+ ok: z.literal(true),
+ status: z.literal("no_active_session"),
+ }),
+]);
diff --git a/packages/eve/src/protocol/routes.ts b/packages/eve/src/protocol/routes.ts
index e2ea33a77..d1f403765 100644
--- a/packages/eve/src/protocol/routes.ts
+++ b/packages/eve/src/protocol/routes.ts
@@ -21,6 +21,12 @@ export const EVE_INFO_ROUTE_PATH = `${EVE_ROUTE_PREFIX}/info`;
*/
export const EVE_CREATE_SESSION_ROUTE_PATH = `${EVE_ROUTE_PREFIX}/session`;
+/**
+ * Stable framework-owned route for retiring the session that owns a client
+ * continuation token. The request body supplies the channel-local token.
+ */
+export const EVE_RESET_SESSION_ROUTE_PATH = `${EVE_ROUTE_PREFIX}/session/reset`;
+
/**
* Stable framework-owned route pattern for sending a message to an existing
* session.
diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts
index ab0afefdb..b47f30337 100644
--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts
+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts
@@ -119,6 +119,7 @@ async function firePost(
getSession: vi.fn() as any,
resolveActiveSession: async () => undefined,
cancel: vi.fn(),
+ reset: vi.fn(),
params: {},
receive: vi.fn() as any,
requestIp: null,
@@ -175,6 +176,7 @@ describe("chatSdkChannel", () => {
getSession: vi.fn() as any,
resolveActiveSession: async () => undefined,
cancel: vi.fn(),
+ reset: vi.fn(),
params: {},
receive: vi.fn() as any,
requestIp: null,
diff --git a/packages/eve/src/public/channels/eve.test.ts b/packages/eve/src/public/channels/eve.test.ts
index 2e213116a..85ff22214 100644
--- a/packages/eve/src/public/channels/eve.test.ts
+++ b/packages/eve/src/public/channels/eve.test.ts
@@ -76,6 +76,7 @@ function createEveCreateHandler(input: EveChannelInput) {
send: mockSend,
resolveActiveSession: async () => undefined,
cancel: vi.fn(),
+ reset: vi.fn(),
getSession: vi.fn(),
receive: vi.fn() as any,
params: {},
@@ -119,6 +120,7 @@ function createEveContinueHandler(input: EveChannelInput) {
send: mockSend,
resolveActiveSession: async () => undefined,
cancel: vi.fn(),
+ reset: vi.fn(),
getSession: mockGetSession,
receive: vi.fn() as any,
params: { sessionId: "test-session-id" },
@@ -152,6 +154,7 @@ function createEveCancelHandler(input: EveChannelInput) {
send: vi.fn(),
resolveActiveSession: async () => undefined,
cancel: vi.fn(),
+ reset: vi.fn(),
getSession: vi.fn(),
receive: vi.fn() as any,
params: { sessionId: "test-session-id" },
@@ -177,6 +180,46 @@ function cancelRequest(body?: unknown): Request {
});
}
+/** Creates a POST handler test harness for the continuation-addressed reset route. */
+function createEveResetHandler(input: EveChannelInput) {
+ const channel = eveChannel(input);
+ const resetRoute = channel.routes.find(
+ (r) => r.method === "POST" && r.path === "/eve/v1/session/reset",
+ );
+ if (!resetRoute) throw new Error("No session reset POST route found");
+
+ const reset = vi.fn().mockResolvedValue({
+ previousSessionId: "test-session-id",
+ status: "reset",
+ });
+
+ return {
+ reset,
+ async fetch(req: Request) {
+ const args: RouteHandlerArgs = {
+ send: vi.fn(),
+ resolveActiveSession: async () => undefined,
+ cancel: vi.fn(),
+ reset,
+ getSession: vi.fn(),
+ receive: vi.fn() as any,
+ params: {},
+ waitUntil: () => undefined,
+ requestIp: "127.0.0.1",
+ };
+ return (resetRoute as any).handler(req, args);
+ },
+ };
+}
+
+function resetRequest(body: unknown): Request {
+ return new Request("https://example.com/eve/v1/session/reset", {
+ body: JSON.stringify(body),
+ headers: { "content-type": "application/json" },
+ method: "POST",
+ });
+}
+
/** Creates a GET handler test harness for the durable session stream route. */
function createEveStreamHandler(input: EveChannelInput) {
const channel = eveChannel(input);
@@ -200,6 +243,7 @@ function createEveStreamHandler(input: EveChannelInput) {
send: vi.fn(),
resolveActiveSession: async () => undefined,
cancel: vi.fn(),
+ reset: vi.fn(),
getSession: mockGetSession,
receive: vi.fn() as any,
params: { sessionId: "test-session-id" },
@@ -1397,3 +1441,68 @@ describe("eveChannel — cancel turn", () => {
});
});
});
+
+describe("eveChannel — reset session", () => {
+ it("retires the owner of the supplied channel-local continuation token", async () => {
+ const handler = createEveResetHandler({ auth: none() });
+
+ const response = await handler.fetch(resetRequest({ continuationToken: "eve:token" }));
+
+ expect(response.status).toBe(200);
+ expect(response.headers.get("cache-control")).toBe("no-store");
+ await expect(response.json()).resolves.toEqual({
+ ok: true,
+ previousSessionId: "test-session-id",
+ status: "reset",
+ });
+ expect(handler.reset).toHaveBeenCalledWith({
+ continuationToken: "eve:token",
+ reason: "Client requested session reset",
+ });
+ });
+
+ it("reports a token that is already free as a successful no-op", async () => {
+ const handler = createEveResetHandler({ auth: none() });
+ handler.reset.mockResolvedValue({ status: "no_active_session" });
+
+ const response = await handler.fetch(resetRequest({ continuationToken: "eve:token" }));
+
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toEqual({ ok: true, status: "no_active_session" });
+ });
+
+ it("rejects unauthenticated reset requests", async () => {
+ const handler = createEveResetHandler({ auth: [] });
+
+ const response = await handler.fetch(resetRequest({ continuationToken: "eve:token" }));
+
+ expect(response.status).toBe(401);
+ expect(handler.reset).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ["an empty token", { continuationToken: "" }],
+ ["a non-string token", { continuationToken: 7 }],
+ ["a non-object body", ["eve:token"]],
+ ])("rejects %s with 400", async (_description, body) => {
+ const handler = createEveResetHandler({ auth: none() });
+
+ const response = await handler.fetch(resetRequest(body));
+
+ expect(response.status).toBe(400);
+ expect(handler.reset).not.toHaveBeenCalled();
+ });
+
+ it("returns 500 when reset fails unexpectedly", async () => {
+ const handler = createEveResetHandler({ auth: none() });
+ handler.reset.mockRejectedValue(new Error("backing store outage"));
+
+ const response = await handler.fetch(resetRequest({ continuationToken: "eve:token" }));
+
+ expect(response.status).toBe(500);
+ await expect(response.json()).resolves.toMatchObject({
+ error: "Failed to reset the session.",
+ ok: false,
+ });
+ });
+});
diff --git a/packages/eve/src/public/channels/eve.ts b/packages/eve/src/public/channels/eve.ts
index 2d4825e6a..4b15180a4 100644
--- a/packages/eve/src/public/channels/eve.ts
+++ b/packages/eve/src/public/channels/eve.ts
@@ -2,6 +2,7 @@ import { type FilePart, type TextPart, type UserContent } from "ai";
import type { CancelTurnResult, SessionAuthContext, SessionCallback } from "#channel/types.js";
import type { CancelTurnResponse } from "#protocol/cancel-turn.js";
+import type { ResetResponse } from "#protocol/reset-session.js";
import { parseSessionCallback } from "#channel/session-callback.js";
import { hasInternalRefScheme } from "#internal/attachments/url-refs.js";
import { createLogger, logError } from "#internal/logging.js";
@@ -17,7 +18,11 @@ import {
EVE_STREAM_FORMAT_HEADER,
EVE_STREAM_VERSION_HEADER,
} from "#protocol/message.js";
-import { EVE_CANCEL_TURN_ROUTE_PATTERN, EVE_INFO_ROUTE_PATH } from "#protocol/routes.js";
+import {
+ EVE_CANCEL_TURN_ROUTE_PATTERN,
+ EVE_INFO_ROUTE_PATH,
+ EVE_RESET_SESSION_ROUTE_PATH,
+} from "#protocol/routes.js";
import { type InputResponse, isInputResponse } from "#runtime/input/types.js";
import { type AuthFn, routeAuth } from "#public/channels/auth.js";
import {
@@ -158,8 +163,8 @@ export interface EveChannel extends Channel {}
/**
* Builds the default eve HTTP channel: a {@link defineChannel} instance serving the
* built-in `/eve/v1` routes (GET inspects the agent, POST creates a session, POST
- * delivers a follow-up, POST cancels the in-flight turn, GET streams a session's
- * NDJSON event feed). Every route
+ * delivers a follow-up, POST cancels an active turn or retires a session, GET
+ * streams a session's NDJSON event feed). Every route
* runs {@link EveChannelInput.auth} via {@link routeAuth} before dispatching.
* Default-export the result as your `agent/channels/eve.ts` channel; reach for
* {@link defineChannel} directly only for a custom transport.
@@ -242,6 +247,36 @@ export function eveChannel(input: EveChannelInput): EveChannel {
);
}),
+ POST(EVE_RESET_SESSION_ROUTE_PATH, async (req, { reset }) => {
+ const authResult = await routeAuth(req, input.auth);
+ if (authResult instanceof Response) return authResult;
+
+ const body = await parseResetSessionBody(req);
+ if (body instanceof Response) return body;
+
+ let result: Awaited<ReturnType<typeof reset>>;
+ try {
+ result = await reset({
+ continuationToken: body.continuationToken,
+ reason: "Client requested session reset",
+ });
+ } catch (error) {
+ const errorId = logError(log, "session-reset request failed", error);
+ return Response.json(
+ { error: "Failed to reset the session.", errorId, ok: false },
+ { status: 500 },
+ );
+ }
+
+ const response: ResetResponse =
+ result.status === "reset"
+ ? { ok: true, previousSessionId: result.previousSessionId, status: "reset" }
+ : { ok: true, status: "no_active_session" };
+ return Response.json(response, {
+ headers: { "cache-control": "no-store" },
+ });
+ }),
+
POST("/eve/v1/session/:sessionId", async (req, { send, getSession, params }) => {
const authResult = await routeAuth(req, input.auth);
if (authResult instanceof Response) return authResult;
@@ -595,6 +630,33 @@ interface ParsedCancelTurnBody {
turnId?: string;
}
+interface ParsedResetSessionBody {
+ readonly continuationToken: string;
+}
+
+async function parseResetSessionBody(req: Request): Promise<ParsedResetSessionBody | Response> {
+ let payload: unknown;
+ try {
+ payload = await req.json();
+ } catch {
+ return Response.json({ error: "Invalid JSON body.", ok: false }, { status: 400 });
+ }
+
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
+ return Response.json({ error: "Expected a JSON object.", ok: false }, { status: 400 });
+ }
+
+ const continuationToken = (payload as { continuationToken?: unknown }).continuationToken;
+ if (typeof continuationToken !== "string" || continuationToken.length === 0) {
+ return Response.json(
+ { error: "Expected 'continuationToken' to be a non-empty string.", ok: false },
+ { status: 400 },
+ );
+ }
+
+ return { continuationToken };
+}
+
async function parseCancelTurnBody(req: Request): Promise<ParsedCancelTurnBody | Response> {
let text: string;
try {
diff --git a/packages/eve/src/public/channels/github/githubChannel.test.ts b/packages/eve/src/public/channels/github/githubChannel.test.ts
index f7cc36257..bd72030ce 100644
--- a/packages/eve/src/public/channels/github/githubChannel.test.ts
+++ b/packages/eve/src/public/channels/github/githubChannel.test.ts
@@ -172,6 +172,7 @@ async function firePost(
const response = await post.handler(request, {
cancel: vi.fn(),
+ reset: vi.fn(),
resolveActiveSession: async () => undefined,
getSession: vi.fn() as any,
params: {},
diff --git a/packages/eve/src/public/channels/index.ts b/packages/eve/src/public/channels/index.ts
index ed9998326..7357800f3 100644
--- a/packages/eve/src/public/channels/index.ts
+++ b/packages/eve/src/public/channels/index.ts
@@ -20,6 +20,9 @@ export {
type SessionHandle,
type RouteDefinition,
type RouteHandlerArgs,
+ type ResetFn,
+ type ResetOptions,
+ type ResetResult,
type SendFn,
type SendOptions,
type SendPayload,
diff --git a/packages/eve/src/public/channels/linear/linearChannel.test.ts b/packages/eve/src/public/channels/linear/linearChannel.test.ts
index d91204e49..eff91db1f 100644
--- a/packages/eve/src/public/channels/linear/linearChannel.test.ts
+++ b/packages/eve/src/public/channels/linear/linearChannel.test.ts
@@ -127,6 +127,7 @@ async function firePost(
const response = await post.handler(request, {
cancel: vi.fn(),
+ reset: vi.fn(),
resolveActiveSession: async () => undefined,
getSession: vi.fn() as any,
params: {},
diff --git a/packages/eve/src/public/channels/teams/teamsChannel.test.ts b/packages/eve/src/public/channels/teams/teamsChannel.test.ts
index ddfbc023d..52b67f8bf 100644
--- a/packages/eve/src/public/channels/teams/teamsChannel.test.ts
+++ b/packages/eve/src/public/channels/teams/teamsChannel.test.ts
@@ -47,6 +47,7 @@ async function firePost(
getSession: vi.fn(),
resolveActiveSession: overrides.resolveActiveSession ?? vi.fn().mockResolvedValue(undefined),
cancel: vi.fn(),
+ reset: vi.fn(),
params: {},
receive: vi.fn(),
requestIp: null,
diff --git a/packages/eve/src/public/definitions/channel.ts b/packages/eve/src/public/definitions/channel.ts
index e7e2019f1..a96d8d01d 100644
--- a/packages/eve/src/public/definitions/channel.ts
+++ b/packages/eve/src/public/definitions/channel.ts
@@ -29,6 +29,9 @@ export { GET, POST, PUT, PATCH, DELETE, WS } from "#channel/routes.js";
export type {
CancelFn,
CancelOptions,
+ ResetFn,
+ ResetOptions,
+ ResetResult,
HttpRouteDefinition,
RouteDefinition,
RouteHandlerArgs,
diff --git a/packages/eve/test/eve-run-stream-channel.test.ts b/packages/eve/test/eve-run-stream-channel.test.ts
index 39f4f3e64..2c5f63952 100644
--- a/packages/eve/test/eve-run-stream-channel.test.ts
+++ b/packages/eve/test/eve-run-stream-channel.test.ts
@@ -187,6 +187,7 @@ function createArgs(input: {
send: vi.fn(),
resolveActiveSession: async () => undefined,
cancel: vi.fn(),
+ reset: vi.fn(),
getSession: input.getSession,
receive: vi.fn() as any,
params: input.params,
diff --git a/packages/eve/test/scenarios/cross-channel-receive.scenario.test.ts b/packages/eve/test/scenarios/cross-channel-receive.scenario.test.ts
index 38035df8d..69d4c9d32 100644
--- a/packages/eve/test/scenarios/cross-channel-receive.scenario.test.ts
+++ b/packages/eve/test/scenarios/cross-channel-receive.scenario.test.ts
@@ -9,6 +9,7 @@ import {
} from "../../src/channel/cross-channel-receive.js";
import type { Runtime } from "../../src/channel/types.js";
import { compileAgent } from "../../src/compiler/compile-agent.js";
+import { RuntimeNoActiveSessionError } from "../../src/execution/runtime-errors.js";
import { createDiskRuntimeCompiledArtifactsSource } from "../../src/runtime/compiled-artifacts-source.js";
import { getCompiledRuntimeAgentBundle } from "../../src/runtime/sessions/compiled-agent-cache.js";
import {
@@ -98,12 +99,15 @@ function createCapturingRuntime(captured: CapturedRun[]): Runtime {
sessionId: "sess_scenario",
};
},
- async deliver() {
- throw new Error("deliver should not be called in this scenario");
+ async deliver(input) {
+ throw new RuntimeNoActiveSessionError(input.continuationToken);
},
async getEventStream() {
return new ReadableStream();
},
+ async terminateSession() {
+ throw new Error("terminateSession should not be called in this scenario");
+ },
};
}
@@ -178,6 +182,9 @@ describe("cross-channel receive end-to-end", () => {
cancel: async () => {
throw new Error("webhook should not cancel turns");
},
+ reset: async () => {
+ throw new Error("webhook should not reset sessions");
+ },
getSession: () => {
throw new Error("webhook should not read sessions directly");
},
diff --git a/packages/eve/test/scenarios/schedule-trigger.scenario.test.ts b/packages/eve/test/scenarios/schedule-trigger.scenario.test.ts
index f2f90ddd9..3b9176e51 100644
--- a/packages/eve/test/scenarios/schedule-trigger.scenario.test.ts
+++ b/packages/eve/test/scenarios/schedule-trigger.scenario.test.ts
@@ -82,6 +82,9 @@ function createCapturingRuntime(captured: CapturedRun[]): Runtime {
async getEventStream() {
return new ReadableStream<HandleMessageStreamEvent>();
},
+ async terminateSession() {
+ throw new Error("terminateSession should not be called in this scenario");
+ },
};
}
diff --git a/packages/eve/test/vercel/session-reset.vercel.test.ts b/packages/eve/test/vercel/session-reset.vercel.test.ts
new file mode 100644
index 000000000..669f31338
--- /dev/null
+++ b/packages/eve/test/vercel/session-reset.vercel.test.ts
@@ -0,0 +1,154 @@
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+import { SESSION_RESET_DESCRIPTOR } from "#internal/testing/scenario-apps/session-reset.js";
+import {
+ createTarballVercelDeploymentFixture,
+ type TarballVercelDeploymentFixture,
+} from "../helpers/vercel-deployment-fixture.js";
+
+const REQUIRED_VERCEL_ENV_NAMES = ["VERCEL_TOKEN", "VERCEL_ORG_ID", "VERCEL_PROJECT_ID"] as const;
+const missingEnvironmentVariables = REQUIRED_VERCEL_ENV_NAMES.filter(
+ (name) => !hasEnvironmentVariable(name),
+);
+
+if (missingEnvironmentVariables.length > 0) {
+ throw new Error(
+ [
+ "Missing required environment variables for session-reset Vercel deployment tests.",
+ `Set: ${missingEnvironmentVariables.join(", ")}`,
+ ].join("\n"),
+ );
+}
+
+describe.sequential("session reset Vercel deployment integration", () => {
+ let deploymentFixture: TarballVercelDeploymentFixture | undefined;
+
+ beforeAll(async () => {
+ deploymentFixture = await createTarballVercelDeploymentFixture({
+ descriptor: SESSION_RESET_DESCRIPTOR,
+ orgId: readRequiredEnvironmentVariable("VERCEL_ORG_ID"),
+ prefix: "eve-vercel-session-reset-",
+ projectId: readRequiredEnvironmentVariable("VERCEL_PROJECT_ID"),
+ runtimeEnv: collectDeploymentEnvironment(["AI_GATEWAY_API_KEY"]),
+ scope: readOptionalEnvironmentVariable("VERCEL_SCOPE"),
+ token: readRequiredEnvironmentVariable("VERCEL_TOKEN"),
+ });
+ }, 20 * 60_000);
+
+ afterAll(async () => {
+ await deploymentFixture?.cleanup();
+ deploymentFixture = undefined;
+ });
+
+ it(
+ "releases a stable continuation token before the next message starts",
+ async () => {
+ const deploymentUrl = deploymentFixture?.deploymentUrl;
+ if (deploymentUrl === undefined) {
+ throw new Error("Expected Vercel deployment fixture to be initialized.");
+ }
+
+ const threadId = `thread-${crypto.randomUUID()}`;
+ const first = await postJson(deploymentUrl, `/session-reset/${threadId}/messages`, {
+ message: "Write a detailed 1,000-word explanation of test isolation.",
+ });
+ const firstSessionId = requireString(first, "sessionId");
+
+ await expect(waitForOwner(deploymentUrl, threadId, "present")).resolves.toBe(firstSessionId);
+
+ const reset = await postJson(deploymentUrl, `/session-reset/${threadId}/new`);
+ expect(reset).toEqual({ previousSessionId: firstSessionId, status: "reset" });
+
+ await expect(waitForOwner(deploymentUrl, threadId, "absent")).resolves.toBeNull();
+
+ const second = await postJson(deploymentUrl, `/session-reset/${threadId}/messages`, {
+ message: "Give another concise greeting.",
+ });
+ expect(requireString(second, "sessionId")).not.toBe(firstSessionId);
+ },
+ 5 * 60_000,
+ );
+});
+
+async function postJson(
+ deploymentUrl: string,
+ path: string,
+ body?: unknown,
+): Promise<Record<string, unknown>> {
+ const response = await fetch(new URL(path, deploymentUrl), {
+ ...(body === undefined
+ ? {}
+ : { body: JSON.stringify(body), headers: { "content-type": "application/json" } }),
+ method: "POST",
+ });
+
+ if (!response.ok) {
+ throw new Error(await response.text());
+ }
+
+ const value: unknown = await response.json();
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
+ throw new Error("Expected the channel route to return a JSON object.");
+ }
+ return value as Record<string, unknown>;
+}
+
+async function waitForOwner(
+ deploymentUrl: string,
+ threadId: string,
+ expected: "absent" | "present",
+): Promise<string | null> {
+ const deadline = Date.now() + 30_000;
+
+ while (Date.now() < deadline) {
+ const response = await postJson(deploymentUrl, `/session-reset/${threadId}/owner`);
+ const sessionId = response.sessionId;
+ const owner = typeof sessionId === "string" ? sessionId : null;
+
+ if ((expected === "present" && owner !== null) || (expected === "absent" && owner === null)) {
+ return owner;
+ }
+
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }
+
+ throw new Error(`Timed out waiting for the continuation token owner to become ${expected}.`);
+}
+
+function requireString(value: Record<string, unknown>, key: string): string {
+ const field = value[key];
+ if (typeof field !== "string" || field.length === 0) {
+ throw new Error(`Expected response field ${key} to be a non-empty string.`);
+ }
+ return field;
+}
+
+function collectDeploymentEnvironment(names: readonly string[]): Record<string, string> {
+ const environment: Record<string, string> = {};
+
+ for (const name of names) {
+ const value = readOptionalEnvironmentVariable(name);
+ if (value !== undefined) {
+ environment[name] = value;
+ }
+ }
+
+ return environment;
+}
+
+function hasEnvironmentVariable(name: string): boolean {
+ return readOptionalEnvironmentVariable(name) !== undefined;
+}
+
+function readOptionalEnvironmentVariable(name: string): string | undefined {
+ const value = process.env[name]?.trim();
+ return value === undefined || value.length === 0 ? undefined : value;
+}
+
+function readRequiredEnvironmentVariable(name: string): string {
+ const value = readOptionalEnvironmentVariable(name);
+ if (value === undefined) {
+ throw new Error(`Missing required environment variable: ${name}`);
+ }
+ return value;
+}