Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): add configurable session timeouts (#1308)

Casey Gowriefeac858eda0a
diff --git a/.changeset/session-timeouts.md b/.changeset/session-timeouts.md
new file mode 100644
index 000000000..26947b56d
--- /dev/null
+++ b/.changeset/session-timeouts.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Complete durable sessions after 30 days by default, and add `limits.sessionTimeoutMs` to configure or disable the lifetime for each agent. Once an expired session settles, the next qualifying channel message for its continuation starts a fresh session.
diff --git a/docs/agent-config.md b/docs/agent-config.md
index 753e5fa77..d8d425e1c 100644
--- a/docs/agent-config.md
+++ b/docs/agent-config.md
@@ -131,10 +131,18 @@ export default defineAgent({
limits: {
maxInputTokensPerSession: 200_000,
maxOutputTokensPerSession: 20_000,
+ sessionTimeoutMs: 7 * 24 * 60 * 60 * 1_000,
},
});
```
+`sessionTimeoutMs` sets an absolute lifetime for every session, including
+delegated sessions. It defaults to 30 days, starts at creation, and survives
+restarts and redeployments. At the deadline, eve lets an active turn settle,
+then emits `session.completed` and releases the continuation; the next
+qualifying channel message starts fresh. Set it to `false` to disable the
+timeout. Expiration does not delete stored session data.
+
Input and output budgets are checked independently. The model call that crosses
either limit is allowed to finish because providers only report exact token
usage after a call completes. Before the next model call, eve pauses the
@@ -208,14 +216,14 @@ installed package must stay external in hosted output, list it in
`defineAgent` takes a few more fields, all optional. For the exported types, see the [TypeScript API](./reference/typescript-api).
-| Field | Type | Default | Description |
-| -------------- | --------------------------------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `reasoning` | `AgentReasoningDefinition` | provider default | Provider-agnostic reasoning effort forwarded to the agent's turn model calls. |
-| `modelOptions` | `AgentModelOptionsDefinition` | none | Provider option overrides forwarded to the model call. |
-| `limits` | `AgentLimitsDefinition` | field-specific | Framework-owned runtime limits. `maxInputTokensPerSession` defaults to `40_000_000` for root sessions, and delegated subagent sessions inherit the parent's remaining quota; `maxOutputTokensPerSession` is unset unless configured; `false` uncaps a session token limit. |
-| `experimental` | `{ workflow?: { world?: string } }` | unset | Opt-in settings that can change or disappear in any release. Treat them as unstable. `workflow.world` selects the Workflow world package backing session state, queues, hooks, and streams on the root agent. |
-| `outputSchema` | Standard Schema or a JSON Schema object | none | Structured return type for task-mode runs (a subagent, schedule, or remote job). Interactive conversation turns ignore it unless the client supplies a per-message schema. |
-| `build` | `{ externalDependencies?: string[] }` | none | Hosted-build packaging controls. `externalDependencies` keeps listed packages external while eve compiles authored modules such as tools and channels, and traces those packages into the hosted output. |
+| Field | Type | Default | Description |
+| -------------- | --------------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `reasoning` | `AgentReasoningDefinition` | provider default | Provider-agnostic reasoning effort forwarded to the agent's turn model calls. |
+| `modelOptions` | `AgentModelOptionsDefinition` | none | Provider option overrides forwarded to the model call. |
+| `limits` | `AgentLimitsDefinition` | field-specific | Framework-owned runtime limits. Sessions complete after 30 days by default; token-limit defaults and inheritance are described above. Set a limit to `false` to disable it. |
+| `experimental` | `{ workflow?: { world?: string } }` | unset | Opt-in settings that can change or disappear in any release. Treat them as unstable. `workflow.world` selects the Workflow world package backing session state, queues, hooks, and streams on the root agent. |
+| `outputSchema` | Standard Schema or a JSON Schema object | none | Structured return type for task-mode runs (a subagent, schedule, or remote job). Interactive conversation turns ignore it unless the client supplies a per-message schema. |
+| `build` | `{ externalDependencies?: string[] }` | none | Hosted-build packaging controls. `externalDependencies` keeps listed packages external while eve compiles authored modules such as tools and channels, and traces those packages into the hosted output. |
`externalDependencies` is a packaging control only. It keeps selected packages as runtime dependencies in the hosted output; it does not authorize, configure, or review any third-party service those packages may call.
diff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.md
index 84ee18092..0859c5163 100644
--- a/docs/concepts/sessions-runs-and-streaming.md
+++ b/docs/concepts/sessions-runs-and-streaming.md
@@ -14,6 +14,12 @@ Two handles do two jobs, and mixing them up is the most common mistake. One hand
A session has one active continuation at a time: each follow-up uses the current `continuationToken`, and a stale one is rejected.
+Sessions last 30 days by default; configure `limits.sessionTimeoutMs` in
+`agent.ts`, or set it to `false` to disable the deadline. At expiration, eve
+lets an active turn settle, emits `session.completed`, and releases the
+continuation so the next qualifying channel message starts fresh. Stored
+session data is not deleted. See [Agent config](../agent-config#runtime-limits).
+
React, Vue, and Svelte apps reach for [`useEveAgent()`](../guides/frontend/overview) instead of calling these routes by hand. Next.js and Nuxt apps can proxy them to the eve runtime from the same origin.
## Start a session
diff --git a/e2e/fixtures/agent-session-timeout/.gitignore b/e2e/fixtures/agent-session-timeout/.gitignore
new file mode 100644
index 000000000..eb095f0f8
--- /dev/null
+++ b/e2e/fixtures/agent-session-timeout/.gitignore
@@ -0,0 +1,10 @@
+node_modules
+.env*
+.eve
+.vercel
+.next
+.output
+.nitro
+dist
+.DS_Store
+*.tsbuildinfo
diff --git a/e2e/fixtures/agent-session-timeout/.vercelignore b/e2e/fixtures/agent-session-timeout/.vercelignore
new file mode 100644
index 000000000..27188ef27
--- /dev/null
+++ b/e2e/fixtures/agent-session-timeout/.vercelignore
@@ -0,0 +1,7 @@
+.env*.local
+node_modules
+.eve
+.next
+.output
+.nitro
+dist
diff --git a/e2e/fixtures/agent-session-timeout/agent/agent.ts b/e2e/fixtures/agent-session-timeout/agent/agent.ts
new file mode 100644
index 000000000..9b2fcae12
--- /dev/null
+++ b/e2e/fixtures/agent-session-timeout/agent/agent.ts
@@ -0,0 +1,18 @@
+import { defineAgent } from "eve";
+import { mockModel } from "eve/evals";
+
+const ACTIVE_TURN_DELAY_MS = 1_500;
+
+export default defineAgent({
+ model: mockModel(async ({ lastUserMessage }) => {
+ if (lastUserMessage?.includes("SLOW-TURN") === true) {
+ await new Promise((resolve) => setTimeout(resolve, ACTIVE_TURN_DELAY_MS));
+ }
+
+ return `timeout-ack:${lastUserMessage ?? ""}`;
+ }),
+ modelContextWindowTokens: 1_000_000,
+ limits: {
+ sessionTimeoutMs: 750,
+ },
+});
diff --git a/e2e/fixtures/agent-session-timeout/agent/channels/threads.ts b/e2e/fixtures/agent-session-timeout/agent/channels/threads.ts
new file mode 100644
index 000000000..90d400c6e
--- /dev/null
+++ b/e2e/fixtures/agent-session-timeout/agent/channels/threads.ts
@@ -0,0 +1,25 @@
+import { defineChannel, POST } from "eve/channels";
+
+const AUTH = {
+ attributes: { source: "session-timeout-eval" },
+ authenticator: "threads",
+ principalId: "session-timeout-eval",
+ principalType: "service",
+} as const;
+
+export default defineChannel({
+ routes: [
+ POST("/threads/:threadId/messages", async (request, { params, send }) => {
+ const body = (await request.json().catch(() => ({}))) as { message?: string };
+ const session = await send(body.message ?? "", {
+ auth: AUTH,
+ continuationToken: params.threadId ?? "",
+ });
+ return Response.json({ sessionId: session.id });
+ }),
+ 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-session-timeout/agent/instructions.md b/e2e/fixtures/agent-session-timeout/agent/instructions.md
new file mode 100644
index 000000000..c3ae235c4
--- /dev/null
+++ b/e2e/fixtures/agent-session-timeout/agent/instructions.md
@@ -0,0 +1 @@
+You are a deterministic session-timeout test agent.
diff --git a/e2e/fixtures/agent-session-timeout/evals/evals.config.ts b/e2e/fixtures/agent-session-timeout/evals/evals.config.ts
new file mode 100644
index 000000000..962d8d02d
--- /dev/null
+++ b/e2e/fixtures/agent-session-timeout/evals/evals.config.ts
@@ -0,0 +1,6 @@
+import { defineEvalConfig } from "eve/evals";
+
+export default defineEvalConfig({
+ maxConcurrency: 1,
+ timeoutMs: 60_000,
+});
diff --git a/e2e/fixtures/agent-session-timeout/evals/session-timeout-channel-rollover.eval.ts b/e2e/fixtures/agent-session-timeout/evals/session-timeout-channel-rollover.eval.ts
new file mode 100644
index 000000000..8c1591104
--- /dev/null
+++ b/e2e/fixtures/agent-session-timeout/evals/session-timeout-channel-rollover.eval.ts
@@ -0,0 +1,83 @@
+import { defineEval, type EveEvalTargetHandle } from "eve/evals";
+import { equals, satisfies } from "eve/evals/expect";
+
+interface MessageResponse {
+ readonly sessionId?: string;
+}
+
+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;
+}
+
+export default defineEval({
+ description:
+ "Session TTL lets an active turn settle, then the same channel thread starts a new session.",
+
+ async test(t) {
+ const threadId = crypto.randomUUID();
+ const initial = await postJson<MessageResponse>(t.target, `/threads/${threadId}/messages`, {
+ message: "SLOW-TURN",
+ });
+ await t.require(
+ initial,
+ satisfies(
+ (value: MessageResponse) => typeof value.sessionId === "string",
+ "the channel starts the initial session",
+ ),
+ );
+ const expiredSessionId = initial.sessionId!;
+
+ const activeTurn = await t.target.watchTurn(expiredSessionId).result();
+ activeTurn.expectOk();
+ activeTurn.notEvent("turn.failed");
+ await t.require(activeTurn.message, equals("timeout-ack:SLOW-TURN"));
+
+ const terminal = await t.target
+ .watchTurn(expiredSessionId, { startIndex: activeTurn.events.length })
+ .result();
+ await t.require(terminal.status, equals("completed"));
+ terminal.event("session.completed");
+ terminal.notEvent("turn.failed");
+ terminal.notEvent("session.failed");
+
+ let owner: OwnerResponse = { sessionId: expiredSessionId };
+ for (let attempt = 0; attempt < 50 && owner.sessionId !== null; attempt += 1) {
+ owner = await postJson<OwnerResponse>(t.target, `/threads/${threadId}/owner`, {});
+ if (owner.sessionId !== null) {
+ await t.sleep(100);
+ }
+ }
+ await t.require(owner.sessionId, equals(null));
+
+ const replacement = await postJson<MessageResponse>(t.target, `/threads/${threadId}/messages`, {
+ message: "REPLACEMENT-TURN",
+ });
+ await t.require(
+ replacement,
+ satisfies(
+ (value: MessageResponse) =>
+ typeof value.sessionId === "string" && value.sessionId !== expiredSessionId,
+ "the expired channel thread starts a fresh session",
+ ),
+ );
+
+ const replacementTurn = await t.target.watchTurn(replacement.sessionId!).result();
+ replacementTurn.expectOk();
+ replacementTurn.notEvent("turn.failed");
+ replacementTurn.notEvent("session.failed");
+ await t.require(replacementTurn.message, equals("timeout-ack:REPLACEMENT-TURN"));
+ },
+});
diff --git a/e2e/fixtures/agent-session-timeout/package.json b/e2e/fixtures/agent-session-timeout/package.json
new file mode 100644
index 000000000..2b033a4cc
--- /dev/null
+++ b/e2e/fixtures/agent-session-timeout/package.json
@@ -0,0 +1,24 @@
+{
+ "name": "agent-session-timeout",
+ "version": "0.0.0",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "build": "eve build",
+ "dev": "eve dev",
+ "start": "eve start",
+ "typecheck": "eve build && tsc",
+ "test:e2e": "eve eval --strict"
+ },
+ "dependencies": {
+ "@opentelemetry/core": "catalog:",
+ "@opentelemetry/sdk-trace-base": "catalog:",
+ "@vercel/otel": "catalog:",
+ "ai": "catalog:",
+ "eve": "workspace:*"
+ },
+ "devDependencies": {
+ "@types/node": "catalog:",
+ "typescript": "catalog:"
+ }
+}
diff --git a/e2e/fixtures/agent-session-timeout/tsconfig.json b/e2e/fixtures/agent-session-timeout/tsconfig.json
new file mode 100644
index 000000000..85e3eceb8
--- /dev/null
+++ b/e2e/fixtures/agent-session-timeout/tsconfig.json
@@ -0,0 +1,17 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "esnext",
+ "moduleResolution": "bundler",
+ "outDir": "dist",
+ "rootDir": ".",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "declaration": true,
+ "noEmit": true,
+ "types": ["node"]
+ },
+ "include": ["agent/**/*.ts", "evals/**/*.ts"]
+}
diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.ts
index add8a380d..564b47dfd 100644
--- a/packages/eve/src/channel/types.ts
+++ b/packages/eve/src/channel/types.ts
@@ -149,6 +149,11 @@ export interface DeliverHookPayload {
readonly payloads: readonly DeliverPayload[];
}
+/** Internal deadline signal sent through the session's delivery hook. */
+export interface SessionTimeoutHookPayload {
+ readonly kind: "session-timeout";
+}
+
/**
* Runtime-action results resumed back into a parked parent workflow.
*/
@@ -213,6 +218,7 @@ export interface SubagentAuthorizationEventHookPayload {
export type HookPayload =
| DeliverHookPayload
| RuntimeActionResultHookPayload
+ | SessionTimeoutHookPayload
| SubagentAuthorizationEventHookPayload
| SubagentInputRequestHookPayload;
diff --git a/packages/eve/src/compiler/compile-from-memory.ts b/packages/eve/src/compiler/compile-from-memory.ts
index 88ced77c4..da9ccfaf9 100644
--- a/packages/eve/src/compiler/compile-from-memory.ts
+++ b/packages/eve/src/compiler/compile-from-memory.ts
@@ -32,6 +32,7 @@ export interface CompileFromMemoryInput {
readonly limits?: {
readonly maxInputTokensPerSession?: number | false;
readonly maxOutputTokensPerSession?: number | false;
+ readonly sessionTimeoutMs?: number | false;
};
readonly outputSchema?: JsonObject;
/**
diff --git a/packages/eve/src/compiler/manifest.test.ts b/packages/eve/src/compiler/manifest.test.ts
index ae84c877e..00fdccb52 100644
--- a/packages/eve/src/compiler/manifest.test.ts
+++ b/packages/eve/src/compiler/manifest.test.ts
@@ -28,6 +28,7 @@ describe("compiledAgentManifestSchema", () => {
limits: {
maxInputTokensPerSession: 200_000,
maxOutputTokensPerSession: 20_000,
+ sessionTimeoutMs: 86_400_000,
},
model: { id: "openai/gpt-5.5", routing: classifyModelRouting("openai/gpt-5.5") },
name: "app",
@@ -39,6 +40,7 @@ describe("compiledAgentManifestSchema", () => {
expect(parsed.config.limits).toEqual({
maxInputTokensPerSession: 200_000,
maxOutputTokensPerSession: 20_000,
+ sessionTimeoutMs: 86_400_000,
});
});
@@ -128,6 +130,7 @@ describe("compiledAgentManifestSchema", () => {
limits: {
maxInputTokensPerSession: false,
maxOutputTokensPerSession: false,
+ sessionTimeoutMs: false,
},
model: { id: "openai/gpt-5.5", routing: classifyModelRouting("openai/gpt-5.5") },
name: "app",
@@ -139,6 +142,7 @@ describe("compiledAgentManifestSchema", () => {
expect(parsed.config.limits).toEqual({
maxInputTokensPerSession: false,
maxOutputTokensPerSession: false,
+ sessionTimeoutMs: false,
});
});
diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.ts
index 461f3ac76..f25c18da8 100644
--- a/packages/eve/src/compiler/manifest.ts
+++ b/packages/eve/src/compiler/manifest.ts
@@ -41,7 +41,7 @@ export const ROOT_COMPILED_AGENT_NODE_ID = "__root__";
/**
* Current compiled manifest schema version.
*/
-export const COMPILED_AGENT_MANIFEST_VERSION = 36;
+export const COMPILED_AGENT_MANIFEST_VERSION = 37;
/**
* Compiled channel entry preserved in the compiled manifest.
@@ -398,11 +398,13 @@ const compiledAgentCompactionDefinitionSchema: z.ZodType<CompiledAgentCompaction
.strict();
const sessionTokenLimitSchema = z.union([z.number().int().positive(), z.literal(false)]);
+const sessionTimeoutSchema = z.union([z.number().int().positive(), z.literal(false)]);
const compiledAgentLimitsDefinitionSchema = z
.object({
maxInputTokensPerSession: sessionTokenLimitSchema.optional(),
maxOutputTokensPerSession: sessionTokenLimitSchema.optional(),
+ sessionTimeoutMs: sessionTimeoutSchema.optional(),
})
.strict();
@@ -825,6 +827,7 @@ export function createCompiledAgentNodeManifest(input: {
: {
maxInputTokensPerSession: input.config.limits.maxInputTokensPerSession,
maxOutputTokensPerSession: input.config.limits.maxOutputTokensPerSession,
+ sessionTimeoutMs: input.config.limits.sessionTimeoutMs,
},
source:
input.config.source === undefined
diff --git a/packages/eve/src/compiler/normalize-agent-config.ts b/packages/eve/src/compiler/normalize-agent-config.ts
index ffa999e02..49be80d49 100644
--- a/packages/eve/src/compiler/normalize-agent-config.ts
+++ b/packages/eve/src/compiler/normalize-agent-config.ts
@@ -129,6 +129,7 @@ export async function compileAgentConfig(
compiledConfig.limits = {
maxInputTokensPerSession: definition.limits.maxInputTokensPerSession,
maxOutputTokensPerSession: definition.limits.maxOutputTokensPerSession,
+ sessionTimeoutMs: definition.limits.sessionTimeoutMs,
};
}
diff --git a/packages/eve/src/execution/session-delivery-hook.test.ts b/packages/eve/src/execution/session-delivery-hook.test.ts
index d3337c139..6b77207fb 100644
--- a/packages/eve/src/execution/session-delivery-hook.test.ts
+++ b/packages/eve/src/execution/session-delivery-hook.test.ts
@@ -66,6 +66,39 @@ describe("createSessionDeliveryHook", () => {
]);
});
+ it("latches a timeout consumed while an active turn owns delivery reads", async () => {
+ const hook = createMockHook({
+ reads: [Promise.resolve(sessionTimeout())],
+ token: "active",
+ });
+ installHooks(hook);
+ const deliveryHook = createSessionDeliveryHook([]);
+
+ await deliveryHook.rekey("active");
+ await expect(deliveryHook.next()).resolves.toEqual(sessionTimeout());
+ deliveryHook.consumeNext();
+
+ expect(deliveryHook.consumeSessionTimeout()).toBe(true);
+ expect(deliveryHook.consumeSessionTimeout()).toBe(false);
+ await deliveryHook.dispose();
+ });
+
+ it("latches a timeout drained from a retired hook during rekey", async () => {
+ const oldHook = createMockHook({
+ reads: [Promise.resolve(sessionTimeout())],
+ token: "old",
+ });
+ const replacementHook = createMockHook({ token: "replacement" });
+ installHooks(oldHook, replacementHook);
+ const deliveryHook = createSessionDeliveryHook([]);
+
+ await deliveryHook.rekey("old");
+ await deliveryHook.rekey("replacement");
+
+ expect(deliveryHook.consumeSessionTimeout()).toBe(true);
+ await deliveryHook.dispose();
+ });
+
it("disposes a conflicting candidate without releasing the active hook", async () => {
const oldHook = createMockHook({ token: "old" });
const candidateHook = createMockHook({
@@ -235,6 +268,10 @@ function deliveryPayload(message: string): DeliverHookPayload {
return { kind: "deliver", payloads: [{ message }] };
}
+function sessionTimeout(): IteratorResult<HookPayload> {
+ return { done: false, value: { kind: "session-timeout" } };
+}
+
function createDeferred<T>(): { readonly promise: Promise<T>; resolve(value: T): void } {
let resolve!: (value: T) => void;
const promise = new Promise<T>((next) => {
diff --git a/packages/eve/src/execution/session-delivery-hook.ts b/packages/eve/src/execution/session-delivery-hook.ts
index 6af0d2970..a063febc3 100644
--- a/packages/eve/src/execution/session-delivery-hook.ts
+++ b/packages/eve/src/execution/session-delivery-hook.ts
@@ -22,6 +22,7 @@ interface SessionDeliveryHookState {
/** Reads and rekeys the public delivery hook for one session driver. */
export interface SessionDeliveryHook {
consumeNext(): void;
+ consumeSessionTimeout(): boolean;
next(): Promise<IteratorResult<HookPayload>>;
rekey(token: string): Promise<void>;
}
@@ -48,6 +49,7 @@ export function createSessionDeliveryHook(
let nextOrder = 0;
let offered: Promise<IteratorResult<HookPayload>> | null = null;
let offeredRead: HookRead | undefined;
+ let sessionTimedOut = false;
let wake: (() => void) | undefined;
const enqueue = (read: HookRead): void => {
@@ -115,6 +117,8 @@ export function createSessionDeliveryHook(
read.state.closed = true;
} else if (read.result.value.kind === "deliver") {
bufferedDeliveries.push(read.result.value);
+ } else if (read.result.value.kind === "session-timeout") {
+ sessionTimedOut = true;
}
arm(read.state);
@@ -128,6 +132,9 @@ export function createSessionDeliveryHook(
throw new Error("Cannot consume a public delivery before it resolves.");
}
+ if (!offeredRead.result.done && offeredRead.result.value.kind === "session-timeout") {
+ sessionTimedOut = true;
+ }
offeredRead.state.pending = false;
offeredRead.state.resolved = undefined;
if (offeredRead.result.done) offeredRead.state.closed = true;
@@ -135,6 +142,12 @@ export function createSessionDeliveryHook(
offered = null;
},
+ consumeSessionTimeout(): boolean {
+ const timedOut = sessionTimedOut;
+ sessionTimedOut = false;
+ return timedOut;
+ },
+
async dispose(): Promise<void> {
if (active !== undefined) {
await disposeHook(active.hook);
diff --git a/packages/eve/src/execution/session-timeout-control.test.ts b/packages/eve/src/execution/session-timeout-control.test.ts
new file mode 100644
index 000000000..c2bac578e
--- /dev/null
+++ b/packages/eve/src/execution/session-timeout-control.test.ts
@@ -0,0 +1,83 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { createSessionTimeoutControl } from "#execution/session-timeout-control.js";
+import {
+ cancelSessionTimeoutStep,
+ startSessionTimeoutStep,
+} from "#execution/session-timeout-steps.js";
+
+vi.mock("./session-timeout-steps.js", () => ({
+ cancelSessionTimeoutStep: vi.fn(),
+ startSessionTimeoutStep: vi.fn(),
+}));
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("createSessionTimeoutControl", () => {
+ it("retargets one absolute deadline when the delivery hook is rekeyed", async () => {
+ const deadline = new Date("2026-02-01T00:00:00.000Z");
+ vi.mocked(startSessionTimeoutStep)
+ .mockResolvedValueOnce({ runId: "timer-old" })
+ .mockResolvedValueOnce({ runId: "timer-new" });
+ const control = createSessionTimeoutControl({ deadline });
+
+ await control.rekey("old");
+ await control.rekey("old");
+ await control.rekey("replacement");
+
+ expect(startSessionTimeoutStep).toHaveBeenNthCalledWith(1, {
+ deadline,
+ token: "old",
+ });
+ expect(startSessionTimeoutStep).toHaveBeenNthCalledWith(2, {
+ deadline,
+ token: "replacement",
+ });
+ expect(cancelSessionTimeoutStep).toHaveBeenCalledOnce();
+ expect(cancelSessionTimeoutStep).toHaveBeenCalledWith({ runId: "timer-old" });
+ expect(vi.mocked(cancelSessionTimeoutStep).mock.invocationCallOrder[0]).toBeLessThan(
+ vi.mocked(startSessionTimeoutStep).mock.invocationCallOrder[1]!,
+ );
+ });
+
+ it("cancels the active timer when the session settles", async () => {
+ vi.mocked(startSessionTimeoutStep).mockResolvedValue({ runId: "timer-run" });
+ const control = createSessionTimeoutControl({
+ deadline: new Date("2026-02-01T00:00:00.000Z"),
+ });
+
+ await control.rekey("active");
+ await control.dispose();
+ await control.dispose();
+
+ expect(cancelSessionTimeoutStep).toHaveBeenCalledOnce();
+ expect(cancelSessionTimeoutStep).toHaveBeenCalledWith({ runId: "timer-run" });
+ });
+
+ it("does not start a timer without a continuation token", async () => {
+ const control = createSessionTimeoutControl({
+ deadline: new Date("2026-02-01T00:00:00.000Z"),
+ });
+
+ await control.rekey("");
+ await control.dispose();
+
+ expect(startSessionTimeoutStep).not.toHaveBeenCalled();
+ expect(cancelSessionTimeoutStep).not.toHaveBeenCalled();
+ });
+
+ it("propagates timer startup failures", async () => {
+ const failure = new Error("timer startup failed");
+ vi.mocked(startSessionTimeoutStep).mockRejectedValue(failure);
+ const control = createSessionTimeoutControl({
+ deadline: new Date("2026-02-01T00:00:00.000Z"),
+ });
+
+ await expect(control.rekey("active")).rejects.toBe(failure);
+ await control.dispose();
+
+ expect(cancelSessionTimeoutStep).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/eve/src/execution/session-timeout-control.ts b/packages/eve/src/execution/session-timeout-control.ts
new file mode 100644
index 000000000..fc3b2784c
--- /dev/null
+++ b/packages/eve/src/execution/session-timeout-control.ts
@@ -0,0 +1,40 @@
+import {
+ cancelSessionTimeoutStep,
+ startSessionTimeoutStep,
+} from "#execution/session-timeout-steps.js";
+
+/** Workflow-body handle that targets a durable deadline at the active delivery hook. */
+export interface SessionTimeoutControl {
+ dispose(): Promise<void>;
+ rekey(token: string): Promise<void>;
+}
+
+/** Creates a timer controller that preserves one absolute session deadline across hook rekeys. */
+export function createSessionTimeoutControl(input: {
+ readonly deadline: Date;
+}): SessionTimeoutControl {
+ let active: { readonly runId: string; readonly token: string } | undefined;
+
+ return {
+ async dispose(): Promise<void> {
+ if (active === undefined) return;
+ const current = active;
+ active = undefined;
+ await cancelSessionTimeoutStep({ runId: current.runId });
+ },
+
+ async rekey(token: string): Promise<void> {
+ if (!token || active?.token === token) return;
+
+ if (active !== undefined) {
+ await cancelSessionTimeoutStep({ runId: active.runId });
+ }
+
+ const { runId } = await startSessionTimeoutStep({
+ deadline: input.deadline,
+ token,
+ });
+ active = { runId, token };
+ },
+ };
+}
diff --git a/packages/eve/src/execution/session-timeout-steps.test.ts b/packages/eve/src/execution/session-timeout-steps.test.ts
new file mode 100644
index 000000000..854d6aeb7
--- /dev/null
+++ b/packages/eve/src/execution/session-timeout-steps.test.ts
@@ -0,0 +1,98 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import {
+ cancelSessionTimeoutStep,
+ signalSessionTimeoutStep,
+ startSessionTimeoutStep,
+} from "#execution/session-timeout-steps.js";
+import { sessionTimeoutWorkflowReference } from "#execution/workflow-runtime.js";
+
+const cancelRunMock = vi.fn();
+const getWorldMock = vi.fn();
+const resumeHookMock = vi.fn();
+const startMock = vi.fn();
+
+vi.mock("#compiled/@workflow/core/runtime.js", () => ({
+ cancelRun: (...args: unknown[]) => cancelRunMock(...args),
+ getWorld: (...args: unknown[]) => getWorldMock(...args),
+ resumeHook: (...args: unknown[]) => resumeHookMock(...args),
+ start: (...args: unknown[]) => startMock(...args),
+}));
+
+afterEach(() => {
+ cancelRunMock.mockReset();
+ getWorldMock.mockReset();
+ resumeHookMock.mockReset();
+ startMock.mockReset();
+ vi.unstubAllEnvs();
+});
+
+describe("session timeout steps", () => {
+ it("starts the durable timer workflow", async () => {
+ vi.stubEnv("VERCEL_ENV", "preview");
+ startMock.mockResolvedValue({ runId: "timer-run" });
+ const input = {
+ deadline: new Date("2026-02-01T00:00:00.000Z"),
+ token: "session-1:session-timeout",
+ };
+
+ await expect(startSessionTimeoutStep(input)).resolves.toEqual({ runId: "timer-run" });
+ expect(startMock).toHaveBeenCalledWith(sessionTimeoutWorkflowReference, [input]);
+ });
+
+ it("signals the owning session hook", async () => {
+ resumeHookMock.mockResolvedValue({ runId: "session-1" });
+
+ await signalSessionTimeoutStep({ token: "session-1:session-timeout" });
+
+ expect(resumeHookMock).toHaveBeenCalledWith("session-1:session-timeout", {
+ kind: "session-timeout",
+ });
+ });
+
+ it("ignores a signal after the owning session is gone", async () => {
+ const { HookNotFoundError } = await import("#compiled/@workflow/errors/index.js");
+ resumeHookMock.mockRejectedValue(new HookNotFoundError("session-1:session-timeout"));
+
+ await expect(
+ signalSessionTimeoutStep({ token: "session-1:session-timeout" }),
+ ).resolves.toBeUndefined();
+ });
+
+ it("cancels a timer that is no longer needed", async () => {
+ const world = {};
+ getWorldMock.mockResolvedValue(world);
+ cancelRunMock.mockResolvedValue(undefined);
+
+ await cancelSessionTimeoutStep({ runId: "timer-run" });
+
+ expect(cancelRunMock).toHaveBeenCalledWith(world, "timer-run", {
+ cancelReason: "Session ended before its timeout",
+ });
+ });
+
+ it("ignores a timer that already reached a terminal state", async () => {
+ const { RunExpiredError } = await import("#compiled/@workflow/errors/index.js");
+ getWorldMock.mockResolvedValue({});
+ cancelRunMock.mockRejectedValue(
+ new Error("Failed to cancel timer", {
+ cause: new RunExpiredError("timer already completed"),
+ }),
+ );
+
+ await expect(cancelSessionTimeoutStep({ runId: "timer-run" })).resolves.toBeUndefined();
+ });
+
+ it("propagates unexpected timeout runtime failures", async () => {
+ const signalFailure = new Error("resume failed");
+ resumeHookMock.mockRejectedValue(signalFailure);
+ await expect(signalSessionTimeoutStep({ token: "session-1:session-timeout" })).rejects.toBe(
+ signalFailure,
+ );
+
+ const cancelFailure = new Error("cancel failed");
+ getWorldMock.mockResolvedValue({});
+ cancelRunMock.mockRejectedValue(cancelFailure);
+ await expect(cancelSessionTimeoutStep({ runId: "timer-run" })).rejects.toBe(cancelFailure);
+ });
+});
diff --git a/packages/eve/src/execution/session-timeout-steps.ts b/packages/eve/src/execution/session-timeout-steps.ts
new file mode 100644
index 000000000..7ec6707a8
--- /dev/null
+++ b/packages/eve/src/execution/session-timeout-steps.ts
@@ -0,0 +1,66 @@
+import {
+ EntityConflictError,
+ HookNotFoundError,
+ RunExpiredError,
+ WorkflowRunNotFoundError,
+} from "#compiled/@workflow/errors/index.js";
+
+import {
+ startWorkflowPreferLatest,
+ sessionTimeoutWorkflowReference,
+} from "#execution/workflow-runtime.js";
+import type { SessionTimeoutWorkflowInput } from "#execution/session-timeout-workflow.js";
+import { cancelRun, getWorld, resumeHook } from "#internal/workflow/runtime.js";
+import { walkCauseChain } from "#shared/errors.js";
+
+/** Starts the durable timer that signals one session deadline. */
+export async function startSessionTimeoutStep(
+ input: SessionTimeoutWorkflowInput,
+): Promise<{ readonly runId: string }> {
+ "use step";
+
+ const run = await startWorkflowPreferLatest(sessionTimeoutWorkflowReference, [input]);
+ return { runId: run.runId };
+}
+
+/** Resumes the owning driver when its durable timer elapses. */
+export async function signalSessionTimeoutStep(input: { readonly token: string }): Promise<void> {
+ "use step";
+
+ try {
+ await resumeHook(input.token, { kind: "session-timeout" });
+ } catch (error) {
+ if (!isInactiveTimeoutTarget(error)) {
+ throw error;
+ }
+ }
+}
+
+/** Cancels a timer whose session reached another terminal outcome first. */
+export async function cancelSessionTimeoutStep(input: { readonly runId: string }): Promise<void> {
+ "use step";
+
+ try {
+ await cancelRun(await getWorld(), input.runId, {
+ cancelReason: "Session ended before its timeout",
+ });
+ } catch (error) {
+ if (!isInactiveTimeoutTarget(error)) {
+ throw error;
+ }
+ }
+}
+
+function isInactiveTimeoutTarget(error: unknown): boolean {
+ for (const candidate of walkCauseChain(error)) {
+ if (
+ HookNotFoundError.is(candidate) ||
+ WorkflowRunNotFoundError.is(candidate) ||
+ RunExpiredError.is(candidate) ||
+ EntityConflictError.is(candidate)
+ ) {
+ return true;
+ }
+ }
+ return false;
+}
diff --git a/packages/eve/src/execution/session-timeout-workflow.test.ts b/packages/eve/src/execution/session-timeout-workflow.test.ts
new file mode 100644
index 000000000..73b569f34
--- /dev/null
+++ b/packages/eve/src/execution/session-timeout-workflow.test.ts
@@ -0,0 +1,43 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { sleep } from "#compiled/@workflow/core/index.js";
+
+import { signalSessionTimeoutStep } from "#execution/session-timeout-steps.js";
+import { sessionTimeoutWorkflow } from "#execution/session-timeout-workflow.js";
+
+vi.mock("#compiled/@workflow/core/index.js", () => ({
+ sleep: vi.fn(),
+}));
+
+vi.mock("./session-timeout-steps.js", () => ({
+ signalSessionTimeoutStep: vi.fn(),
+}));
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("sessionTimeoutWorkflow", () => {
+ it("signals the session only after its durable sleep settles", async () => {
+ let wake: (() => void) | undefined;
+ vi.mocked(sleep).mockImplementation(
+ () =>
+ new Promise<void>((resolve) => {
+ wake = resolve;
+ }),
+ );
+
+ const deadline = new Date("2026-02-01T00:00:00.000Z");
+ const timer = sessionTimeoutWorkflow({ deadline, token: "session-1:session-timeout" });
+ await vi.waitFor(() => {
+ expect(sleep).toHaveBeenCalledWith(deadline);
+ });
+ expect(signalSessionTimeoutStep).not.toHaveBeenCalled();
+
+ wake?.();
+ await timer;
+
+ expect(signalSessionTimeoutStep).toHaveBeenCalledWith({
+ token: "session-1:session-timeout",
+ });
+ });
+});
diff --git a/packages/eve/src/execution/session-timeout-workflow.ts b/packages/eve/src/execution/session-timeout-workflow.ts
new file mode 100644
index 000000000..7bfef4b44
--- /dev/null
+++ b/packages/eve/src/execution/session-timeout-workflow.ts
@@ -0,0 +1,16 @@
+import { sleep } from "#compiled/@workflow/core/index.js";
+
+import { signalSessionTimeoutStep } from "#execution/session-timeout-steps.js";
+
+export interface SessionTimeoutWorkflowInput {
+ readonly deadline: Date;
+ readonly token: string;
+}
+
+/** Sleeps until the session deadline, then signals its driver. */
+export async function sessionTimeoutWorkflow(input: SessionTimeoutWorkflowInput): Promise<void> {
+ "use workflow";
+
+ await sleep(input.deadline);
+ await signalSessionTimeoutStep({ token: input.token });
+}
diff --git a/packages/eve/src/execution/session-timeout.ts b/packages/eve/src/execution/session-timeout.ts
new file mode 100644
index 000000000..ced5b1a53
--- /dev/null
+++ b/packages/eve/src/execution/session-timeout.ts
@@ -0,0 +1,2 @@
+/** Default absolute lifetime of one durable session. */
+export const DEFAULT_SESSION_TIMEOUT_MS = 30 * 24 * 60 * 60 * 1_000;
diff --git a/packages/eve/src/execution/terminal-session-completion-step.ts b/packages/eve/src/execution/terminal-session-completion-step.ts
new file mode 100644
index 000000000..509765c4c
--- /dev/null
+++ b/packages/eve/src/execution/terminal-session-completion-step.ts
@@ -0,0 +1,51 @@
+import { buildAdapterContext } from "#channel/adapter-context.js";
+import { callAdapterEventHandler } from "#channel/adapter.js";
+import { deserializeContext } from "#context/serialize.js";
+import { createLogger } from "#internal/logging.js";
+import {
+ createSessionCompletedEvent,
+ encodeMessageStreamEvent,
+ stampMessageStreamEvent,
+} from "#protocol/message.js";
+import { ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
+
+const log = createLogger("execution.workflow-entry");
+
+/** Emits a terminal `session.completed` outside a turn. */
+export async function emitTerminalSessionCompletionStep(input: {
+ readonly parentWritable: WritableStream<Uint8Array>;
+ readonly serializedContext: Record<string, unknown>;
+}): Promise<void> {
+ "use step";
+
+ const event = createSessionCompletedEvent();
+ const sessionId = (input.serializedContext["eve.sessionId"] as string | undefined) ?? "";
+
+ try {
+ const ctx = await deserializeContext(input.serializedContext);
+ const adapter = ctx.get(ChannelKey);
+ if (adapter !== undefined) {
+ const adapterCtx = buildAdapterContext(adapter, ctx);
+ await callAdapterEventHandler(adapter, event, adapterCtx);
+ }
+ } catch (notificationError) {
+ log.error("adapter failed to handle terminal session.completed event", {
+ error: notificationError,
+ sessionId,
+ });
+ }
+
+ try {
+ const writer = input.parentWritable.getWriter();
+ try {
+ await writer.write(encodeMessageStreamEvent(stampMessageStreamEvent(event)));
+ } finally {
+ writer.releaseLock();
+ }
+ } catch (writeError) {
+ log.error("failed to write terminal session.completed event to durable stream", {
+ error: writeError,
+ sessionId,
+ });
+ }
+}
diff --git a/packages/eve/src/execution/turn-control-receiver.test.ts b/packages/eve/src/execution/turn-control-receiver.test.ts
index 3e587039f..dda25c0f5 100644
--- a/packages/eve/src/execution/turn-control-receiver.test.ts
+++ b/packages/eve/src/execution/turn-control-receiver.test.ts
@@ -126,6 +126,7 @@ function parkResult(): Extract<TurnControlPayload, { readonly kind: "turn-result
function createDeliveryHook(overrides: Partial<SessionDeliveryHook> = {}): SessionDeliveryHook {
return {
consumeNext: vi.fn(),
+ consumeSessionTimeout: vi.fn(() => false),
next: vi.fn(() => new Promise<IteratorResult<HookPayload>>(() => {})),
rekey: vi.fn(),
...overrides,
diff --git a/packages/eve/src/execution/turn-dispatch.test.ts b/packages/eve/src/execution/turn-dispatch.test.ts
index 5a20d8cb3..1839a0a95 100644
--- a/packages/eve/src/execution/turn-dispatch.test.ts
+++ b/packages/eve/src/execution/turn-dispatch.test.ts
@@ -218,6 +218,7 @@ describe("dispatchAndAwaitTurn", () => {
function createDeliveryHook(overrides: Partial<SessionDeliveryHook> = {}): SessionDeliveryHook {
return {
consumeNext: vi.fn(),
+ consumeSessionTimeout: vi.fn(() => false),
next: vi.fn(() => new Promise<IteratorResult<HookPayload>>(() => {})),
rekey: vi.fn(),
...overrides,
diff --git a/packages/eve/src/execution/workflow-entry.integration.test.ts b/packages/eve/src/execution/workflow-entry.integration.test.ts
index f62da641c..ad106cb5b 100644
--- a/packages/eve/src/execution/workflow-entry.integration.test.ts
+++ b/packages/eve/src/execution/workflow-entry.integration.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { getWorld, resumeHook, start } from "#internal/workflow/runtime.js";
+import { createSendFn } from "#channel/send.js";
import { captureTurnEvents, filterEventsByType } from "#internal/testing/events.js";
import { createTestRuntime } from "#internal/testing/app-harness.js";
import { waitForHook } from "#internal/testing/workflow-test-helpers.js";
@@ -15,7 +16,7 @@ import { createWorkflowRuntime } from "#execution/workflow-runtime.js";
import { normalizeEveAttributes } from "#runtime/attributes/normalize.js";
import { ROOT_COMPILED_AGENT_NODE_ID } from "#compiler/manifest.js";
import { ConnectionAuthorizationRequiredError } from "#public/connections/errors.js";
-import type { UnstampedMessageStreamEvent, MessageStreamEvent } from "#protocol/message.js";
+import type { MessageStreamEvent } from "#protocol/message.js";
import { isEventId } from "#protocol/event-id.js";
import type { ToolContext } from "#public/definitions/tool.js";
import type { AuthorizationDefinition, TokenResult } from "#runtime/connections/types.js";
@@ -354,6 +355,63 @@ describe("workflowEntry integration", () => {
});
});
+ it("completes an expired conversation and lets its channel start a fresh session", async () => {
+ const runtime = createTestRuntime({ agent: { name: "workflow-entry-timeout" } });
+ const continuationToken = "http:workflow-entry-timeout";
+ const workflowRuntime = createWorkflowRuntime({
+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
+ });
+
+ await runtime.run(async () => {
+ const run = await start(workflowEntry, [
+ {
+ input: { message: "hello there" },
+ serializedContext: buildSerializedContext({
+ channelKind: "http",
+ continuationToken,
+ mode: "conversation",
+ }),
+ sessionTimeoutMs: 25,
+ },
+ ]);
+ const stream = captureEvents(run);
+ let replacementSessionId: string | undefined;
+
+ try {
+ const events = await stream.nextUntil(
+ "session completion",
+ (event) => event.type === "session.completed",
+ );
+
+ expect(events.some((event) => event.type === "session.waiting")).toBe(true);
+ expect(events.at(-1)?.type).toBe("session.completed");
+ expect(isEventId(events.at(-1)?.meta.id ?? "")).toBe(true);
+ expect(filterEventsByType(events, "session.failed")).toHaveLength(0);
+ await expect(run.returnValue).resolves.toEqual({ output: "" });
+
+ const send = createSendFn(workflowRuntime, { kind: "http" }, "http");
+ const replacement = await send("start fresh", {
+ auth: null,
+ continuationToken: "workflow-entry-timeout",
+ });
+ replacementSessionId = replacement.id;
+
+ expect(replacement.id).not.toBe(run.runId);
+ await waitForHook(
+ { runId: replacement.id },
+ {
+ token: continuationToken,
+ },
+ );
+ } finally {
+ stream.dispose();
+ if (replacementSessionId !== undefined) {
+ await workflowRuntime.terminateSession({ sessionId: replacementSessionId });
+ }
+ }
+ });
+ });
+
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";
@@ -645,8 +703,8 @@ interface CapturedEventStream {
dispose(): void;
nextUntil(
label: string,
- predicate: (event: UnstampedMessageStreamEvent) => boolean,
- ): Promise<UnstampedMessageStreamEvent[]>;
+ predicate: (event: MessageStreamEvent) => boolean,
+ ): Promise<MessageStreamEvent[]>;
}
function captureEvents(run: Parameters<typeof captureTurnEvents>[0]): CapturedEventStream {
@@ -677,9 +735,9 @@ async function readUntil(
reader: ReadableStreamDefaultReader<Uint8Array>,
decoder: InstanceType<typeof TextDecoder>,
initialBuffer: string,
- predicate: (event: UnstampedMessageStreamEvent) => boolean,
-): Promise<{ buffer: string; events: UnstampedMessageStreamEvent[] }> {
- const events: UnstampedMessageStreamEvent[] = [];
+ predicate: (event: MessageStreamEvent) => boolean,
+): Promise<{ buffer: string; events: MessageStreamEvent[] }> {
+ const events: MessageStreamEvent[] = [];
let buffer = initialBuffer;
while (true) {
@@ -703,7 +761,7 @@ async function readUntil(
continue;
}
- const event = JSON.parse(line) as UnstampedMessageStreamEvent;
+ const event = JSON.parse(line) as MessageStreamEvent;
events.push(event);
if (predicate(event)) {
diff --git a/packages/eve/src/execution/workflow-entry.test.ts b/packages/eve/src/execution/workflow-entry.test.ts
index f17458aec..b20aa27c3 100644
--- a/packages/eve/src/execution/workflow-entry.test.ts
+++ b/packages/eve/src/execution/workflow-entry.test.ts
@@ -8,6 +8,11 @@ import { createSessionStep } from "#execution/create-session-step.js";
import { notifyDelegatedParentStep } from "#execution/delegated-parent-notification.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
import { fireSessionCallbackStep } from "#execution/session-callback-step.js";
+import { emitTerminalSessionCompletionStep } from "#execution/terminal-session-completion-step.js";
+import {
+ createSessionTimeoutControl,
+ type SessionTimeoutControl,
+} from "#execution/session-timeout-control.js";
import type { TurnControlPayload } from "#execution/turn-control-protocol.js";
import { workflowEntry } from "#execution/workflow-entry.js";
import { routeDeliverToChildren } from "#execution/route-child-delivery.js";
@@ -20,6 +25,7 @@ vi.mock("#compiled/@workflow/core/index.js", () => ({
getWorkflowMetadata: vi.fn(() => ({
url: "https://eve.example.com",
workflowRunId: "wrun_test_123",
+ workflowStartedAt: new Date("2026-01-01T00:00:00.000Z"),
})),
getWritable: vi.fn(
() =>
@@ -60,10 +66,18 @@ vi.mock("./terminal-session-failure-step.js", () => ({
emitTerminalSessionFailureStep: vi.fn().mockResolvedValue(undefined),
}));
+vi.mock("./terminal-session-completion-step.js", () => ({
+ emitTerminalSessionCompletionStep: vi.fn().mockResolvedValue(undefined),
+}));
+
vi.mock("./settle-cancelled-turn-step.js", () => ({
settleCancelledTurnStep: vi.fn().mockResolvedValue(undefined),
}));
+vi.mock("./session-timeout-control.js", () => ({
+ createSessionTimeoutControl: vi.fn(),
+}));
+
function createSessionStateForMock(
overrides: Partial<DurableSessionState> = {},
): DurableSessionState {
@@ -91,6 +105,7 @@ vi.mock("./session-callback-step.js", () => ({
interface DeliveryHookConfig {
readonly dispose?: () => void;
readonly getConflict?: () => Promise<{ readonly runId: string } | null>;
+ readonly next?: () => Promise<IteratorResult<HookPayload>>;
readonly return?: () => Promise<IteratorResult<HookPayload>>;
readonly token: string;
readonly values?: readonly HookPayload[];
@@ -105,6 +120,7 @@ describe("workflowEntry", () => {
beforeEach(() => {
vi.stubEnv("VERCEL_PROJECT_PRODUCTION_URL", "");
vi.stubEnv("VERCEL_ENV", "");
+ vi.mocked(createSessionTimeoutControl).mockReturnValue(createTimeoutControl());
});
afterEach(() => {
@@ -134,6 +150,9 @@ describe("workflowEntry", () => {
});
expect(result).toEqual({ output: "ok" });
+ expect(createSessionTimeoutControl).toHaveBeenCalledWith({
+ deadline: new Date("2026-01-31T00:00:00.000Z"),
+ });
expect(createSessionStep).toHaveBeenCalledWith({
compiledArtifactsSource: {},
continuationToken: "http:test",
@@ -287,6 +306,116 @@ describe("workflowEntry", () => {
);
});
+ it("completes a parked session when its durable deadline elapses", async () => {
+ const sessionState = createBaseSessionState();
+ const dispose = vi.fn();
+ const timeoutControl = createTimeoutControl();
+ vi.mocked(createSessionTimeoutControl).mockReturnValueOnce(timeoutControl);
+ vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));
+ installHookMocks({
+ deliveryHooks: [
+ {
+ dispose,
+ token: "http:test",
+ values: [{ kind: "session-timeout" }],
+ },
+ ],
+ turnControls: [turnResult({ action: "park", sessionState })],
+ });
+
+ await expect(
+ workflowEntry({
+ input: { message: "hello there" },
+ serializedContext: createSerializedContext(),
+ sessionTimeoutMs: 1_000,
+ }),
+ ).resolves.toEqual({ output: "" });
+
+ expect(createSessionTimeoutControl).toHaveBeenCalledWith({
+ deadline: new Date("2026-01-01T00:00:01.000Z"),
+ });
+ expect(timeoutControl.rekey).toHaveBeenCalledWith("http:test");
+ expect(timeoutControl.dispose).toHaveBeenCalledOnce();
+ expect(emitTerminalSessionFailureStep).not.toHaveBeenCalled();
+ expect(emitTerminalSessionCompletionStep).toHaveBeenCalledWith({
+ parentWritable: expect.any(WritableStream),
+ serializedContext: { "eve.sessionId": "wrun_test_123" },
+ });
+ expect(dispose.mock.invocationCallOrder[0]).toBeLessThan(
+ vi.mocked(emitTerminalSessionCompletionStep).mock.invocationCallOrder[0] ??
+ Number.POSITIVE_INFINITY,
+ );
+ expect(fireSessionCallbackStep).toHaveBeenCalledWith({
+ output: "",
+ serializedContext: { "eve.sessionId": "wrun_test_123" },
+ status: "completed",
+ });
+ });
+
+ it("does not complete at the deadline until the active turn settles", async () => {
+ const sessionState = createBaseSessionState();
+ const dispose = vi.fn();
+ let settleTurn: ((result: IteratorResult<TurnControlPayload>) => void) | undefined;
+ const activeTurn = new Promise<IteratorResult<TurnControlPayload>>((resolve) => {
+ settleTurn = resolve;
+ });
+
+ vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));
+ vi.mocked(createHook).mockImplementation((options?: { readonly token?: string }) => {
+ const token = options?.token ?? "";
+ if (isTurnCompletionToken(token)) {
+ return createMockHook({
+ next: () => activeTurn,
+ token,
+ values: [],
+ }) as never;
+ }
+ if (token.endsWith(":auth")) {
+ return createMockHook({ token, values: [] }) as never;
+ }
+ return createMockHook({
+ dispose,
+ token,
+ values: [{ kind: "session-timeout" }],
+ }) as never;
+ });
+
+ const result = workflowEntry({
+ input: { message: "hello there" },
+ serializedContext: createSerializedContext(),
+ sessionTimeoutMs: 1,
+ });
+
+ await vi.waitFor(() => {
+ expect(dispatchTurnStep).toHaveBeenCalledOnce();
+ });
+ expect(emitTerminalSessionCompletionStep).not.toHaveBeenCalled();
+
+ settleTurn?.({
+ done: false,
+ value: turnResult({ action: "park", sessionState }),
+ });
+
+ await expect(result).resolves.toEqual({ output: "" });
+ expect(emitTerminalSessionCompletionStep).toHaveBeenCalledOnce();
+ });
+
+ it("allows the session timeout to be disabled", async () => {
+ const sessionState = createBaseSessionState();
+ vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));
+ installHookMocks({
+ turnControls: [turnResult({ action: "done", output: "ok", sessionState })],
+ });
+
+ await workflowEntry({
+ input: { message: "hello there" },
+ serializedContext: createSerializedContext(),
+ sessionTimeoutMs: false,
+ });
+
+ expect(createSessionTimeoutControl).not.toHaveBeenCalled();
+ });
+
it("notifies a delegated parent once when a turn fails terminally", async () => {
const sessionState = createBaseSessionState();
vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));
@@ -902,6 +1031,7 @@ function installHookMocks(input: {
return createMockHook({
dispose: config.dispose,
getConflict: config.getConflict,
+ next: config.next,
return: config.return,
symbolDispose: input.symbolDispose,
token,
@@ -910,6 +1040,13 @@ function installHookMocks(input: {
});
}
+function createTimeoutControl(): SessionTimeoutControl {
+ return {
+ dispose: vi.fn(async () => undefined),
+ rekey: vi.fn(async () => undefined),
+ };
+}
+
function createMockHook<T>(input: {
readonly dispose?: () => void;
readonly getConflict?: () => Promise<{ readonly runId: string } | null>;
diff --git a/packages/eve/src/execution/workflow-entry.ts b/packages/eve/src/execution/workflow-entry.ts
index 3af4d4127..4127dbdc7 100644
--- a/packages/eve/src/execution/workflow-entry.ts
+++ b/packages/eve/src/execution/workflow-entry.ts
@@ -30,6 +30,9 @@ import {
createSessionDeliveryHook,
type SessionDeliveryHook,
} from "#execution/session-delivery-hook.js";
+import { DEFAULT_SESSION_TIMEOUT_MS } from "#execution/session-timeout.js";
+import { emitTerminalSessionCompletionStep } from "#execution/terminal-session-completion-step.js";
+import { createSessionTimeoutControl } from "#execution/session-timeout-control.js";
import { readSerializedSubagentDepth } from "#harness/subagent-depth.js";
const SAFE_OUTER_WORKFLOW_FAILURE_MESSAGE =
@@ -47,6 +50,7 @@ const SAFE_OUTER_WORKFLOW_FAILURE_MESSAGE =
export interface WorkflowEntryInput {
readonly input: RunInput["input"];
readonly limits?: RunInput["limits"];
+ readonly sessionTimeoutMs?: number | false;
readonly serializedContext: Record<string, unknown>;
}
@@ -54,6 +58,23 @@ export interface WorkflowEntryResult {
readonly output: unknown;
}
+type DriverLoopOutcome =
+ | {
+ readonly kind: "expired";
+ readonly serializedContext: Record<string, unknown>;
+ }
+ | {
+ readonly kind: "result";
+ readonly result: WorkflowEntryResult;
+ };
+
+type NextSessionAction =
+ | {
+ readonly delivery: DeliverHookPayload | null;
+ readonly kind: "delivery";
+ }
+ | { readonly kind: "expired" };
+
/**
* Long-lived workflow entrypoint. Handles both root sessions and
* delegated child sessions: root sessions expose only parent
@@ -71,7 +92,7 @@ export interface WorkflowEntryResult {
export async function workflowEntry(input: WorkflowEntryInput): Promise<WorkflowEntryResult> {
"use workflow";
- const { workflowRunId: sessionId } = getWorkflowMetadata();
+ const { workflowRunId: sessionId, workflowStartedAt } = getWorkflowMetadata();
const continuationToken = (input.serializedContext["eve.continuationToken"] as string) || "";
const mode = input.serializedContext["eve.mode"] as RunMode;
const capabilities = input.serializedContext["eve.capabilities"] as
@@ -105,7 +126,7 @@ export async function workflowEntry(input: WorkflowEntryInput): Promise<Workflow
subagentDepth,
});
- return await runDriverLoop({
+ const outcome = await runDriverLoop({
capabilities,
driverWritable,
initialInput: {
@@ -122,6 +143,19 @@ export async function workflowEntry(input: WorkflowEntryInput): Promise<Workflow
mode,
serializedContext: input.serializedContext,
sessionState,
+ sessionTimeoutDeadline:
+ input.sessionTimeoutMs === false
+ ? undefined
+ : new Date(
+ workflowStartedAt.getTime() + (input.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS),
+ ),
+ });
+ if (outcome.kind === "result") {
+ return outcome.result;
+ }
+ return await finalizeExpiredSession({
+ driverWritable,
+ serializedContext: outcome.serializedContext,
});
} catch (error) {
// Safety net for failures the tool-loop harness does not already
@@ -159,7 +193,8 @@ async function runDriverLoop(input: {
readonly mode: RunMode;
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
-}): Promise<WorkflowEntryResult> {
+ readonly sessionTimeoutDeadline?: Date;
+}): Promise<DriverLoopOutcome> {
// Per-session auth hook. Created before any turns so it exists
// when authorization.required events trigger OAuth callbacks.
// getHookUrl() builds callback URLs with this token.
@@ -176,6 +211,10 @@ async function runDriverLoop(input: {
const bufferedDeliveries: DeliverHookPayload[] = [];
const deliveryHook = createSessionDeliveryHook(bufferedDeliveries);
+ const sessionTimeout =
+ input.sessionTimeoutDeadline === undefined
+ ? undefined
+ : createSessionTimeoutControl({ deadline: input.sessionTimeoutDeadline });
// Control-hook disposal is deferred one turn — see DispatchedTurn.
let disposeSettledTurnControl: (() => Promise<void>) | undefined;
@@ -203,6 +242,7 @@ async function runDriverLoop(input: {
try {
if (input.sessionState.continuationToken) {
await deliveryHook.rekey(input.sessionState.continuationToken);
+ await sessionTimeout?.rekey(input.sessionState.continuationToken);
}
let action: NextDriverAction = await runTurn({
@@ -213,10 +253,13 @@ async function runDriverLoop(input: {
while (true) {
if (action.kind === "done") {
- return await finalizeDone({
- action,
- driverWritable: input.driverWritable,
- });
+ return {
+ kind: "result",
+ result: await finalizeDone({
+ action,
+ driverWritable: input.driverWritable,
+ }),
+ };
}
if (action.kind !== "park") {
@@ -251,6 +294,7 @@ async function runDriverLoop(input: {
// Rekey to the parked turn's continuation token before awaiting the next
// delivery — covers both the first turn's anchor and any later rekey.
await deliveryHook.rekey(action.sessionState.continuationToken);
+ await sessionTimeout?.rekey(action.sessionState.continuationToken);
if (action.authorizationNames && action.authorizationNames.length > 0) {
const expected = action.authorizationNames.length;
@@ -275,13 +319,21 @@ async function runDriverLoop(input: {
continue;
}
- const nextDeliver = await waitForNextDeliver({
+ const nextAction = await waitForNextSessionAction({
bufferedDeliveries,
deliveryHook,
});
+ if (nextAction.kind === "expired") {
+ return {
+ kind: "expired",
+ serializedContext: action.serializedContext,
+ };
+ }
+
+ const nextDeliver = nextAction.delivery;
if (nextDeliver === null) {
- return { output: "" };
+ return { kind: "result", result: { output: "" } };
}
const remainder = await routeDeliverToChildren({
@@ -309,6 +361,7 @@ async function runDriverLoop(input: {
}
} finally {
await disposeSettledTurnControl?.();
+ await sessionTimeout?.dispose();
await deliveryHook.dispose();
// Dispose without closing the iterator: a session cancelled while
// awaiting authorization can leave a durable read in flight, and an
@@ -317,36 +370,19 @@ async function runDriverLoop(input: {
}
}
-async function finalizeDone(input: {
- readonly action: NextDriverAction & { readonly kind: "done" };
- readonly driverWritable: WritableStream<Uint8Array>;
-}): Promise<WorkflowEntryResult> {
- const { output, serializedContext } = input.action;
- const failed = input.action.isError === true;
-
- await fireSessionCallbackStep({
- error: failed ? output : undefined,
- output: failed ? undefined : output,
- serializedContext,
- status: failed ? "failed" : "completed",
- usage: failed ? undefined : input.action.usage,
- });
- await notifyDelegatedParentStep({
- result: failed
- ? createDelegatedSubagentErrorResult(serializedContext, output)
- : createDelegatedSubagentSuccessResult(serializedContext, output),
- serializedContext,
- usage: failed ? undefined : input.action.usage,
- });
- return { output };
-}
-
-async function waitForNextDeliver(input: {
+async function waitForNextSessionAction(input: {
readonly bufferedDeliveries: DeliverHookPayload[];
readonly deliveryHook: SessionDeliveryHook;
-}): Promise<DeliverHookPayload | null> {
+}): Promise<NextSessionAction> {
+ if (input.deliveryHook.consumeSessionTimeout()) {
+ return { kind: "expired" };
+ }
+
if (input.bufferedDeliveries.length > 0) {
- return coalesceDeliveries(input.bufferedDeliveries.splice(0));
+ return {
+ delivery: coalesceDeliveries(input.bufferedDeliveries.splice(0)),
+ kind: "delivery",
+ };
}
while (true) {
@@ -354,7 +390,11 @@ async function waitForNextDeliver(input: {
input.deliveryHook.consumeNext();
if (first.done) {
- return null;
+ return { delivery: null, kind: "delivery" };
+ }
+
+ if (first.value.kind === "session-timeout") {
+ return { kind: "expired" };
}
if (first.value.kind !== "deliver") {
@@ -370,12 +410,19 @@ async function waitForNextDeliver(input: {
break;
}
- input.deliveryHook.consumeNext();
-
if (ready.done) {
+ input.deliveryHook.consumeNext();
+ break;
+ }
+
+ // Preserve a timeout queued after a delivery. The delivery committed
+ // first, so its active turn settles before the offered timeout is read.
+ if (ready.value.kind === "session-timeout") {
break;
}
+ input.deliveryHook.consumeNext();
+
if (ready.value.kind !== "deliver") {
continue;
}
@@ -383,10 +430,54 @@ async function waitForNextDeliver(input: {
coalesced = coalesceDeliveries([coalesced, ready.value]);
}
- return coalesced;
+ return { delivery: coalesced, kind: "delivery" };
}
}
+async function finalizeExpiredSession(input: {
+ readonly driverWritable: WritableStream<Uint8Array>;
+ readonly serializedContext: Record<string, unknown>;
+}): Promise<WorkflowEntryResult> {
+ await emitTerminalSessionCompletionStep({
+ parentWritable: input.driverWritable,
+ serializedContext: input.serializedContext,
+ });
+ await fireSessionCallbackStep({
+ output: "",
+ serializedContext: input.serializedContext,
+ status: "completed",
+ });
+ await notifyDelegatedParentStep({
+ result: createDelegatedSubagentSuccessResult(input.serializedContext, ""),
+ serializedContext: input.serializedContext,
+ });
+ return { output: "" };
+}
+
+async function finalizeDone(input: {
+ readonly action: NextDriverAction & { readonly kind: "done" };
+ readonly driverWritable: WritableStream<Uint8Array>;
+}): Promise<WorkflowEntryResult> {
+ const { output, serializedContext } = input.action;
+ const failed = input.action.isError === true;
+
+ await fireSessionCallbackStep({
+ error: failed ? output : undefined,
+ output: failed ? undefined : output,
+ serializedContext,
+ status: failed ? "failed" : "completed",
+ usage: failed ? undefined : input.action.usage,
+ });
+ await notifyDelegatedParentStep({
+ result: failed
+ ? createDelegatedSubagentErrorResult(serializedContext, output)
+ : createDelegatedSubagentSuccessResult(serializedContext, output),
+ serializedContext,
+ usage: failed ? undefined : input.action.usage,
+ });
+ return { output };
+}
+
const NO_READY_MESSAGE = Symbol("no-ready-message");
async function takeReadyPayload<T>(promise: Promise<T>): Promise<T | typeof NO_READY_MESSAGE> {
diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.ts
index 2ab666291..79346d5cc 100644
--- a/packages/eve/src/execution/workflow-runtime.test.ts
+++ b/packages/eve/src/execution/workflow-runtime.test.ts
@@ -6,6 +6,7 @@ import { resolveInstalledPackageInfo } from "#internal/application/package.js";
import {
createWorkflowRuntime,
LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE,
+ sessionTimeoutWorkflowReference,
turnWorkflowReference,
workflowEntryReference,
} from "#execution/workflow-runtime.js";
@@ -58,6 +59,11 @@ describe("workflowEntryReference", () => {
expect(turnWorkflowReference.workflowId).toBe(`workflow//${packageInfo.name}//turnWorkflow`);
expect(turnWorkflowReference.workflowId).not.toContain("/src/execution/");
expect(turnWorkflowReference.workflowId).not.toContain("@");
+ expect(sessionTimeoutWorkflowReference.workflowId).toBe(
+ `workflow//${packageInfo.name}//sessionTimeoutWorkflow`,
+ );
+ expect(sessionTimeoutWorkflowReference.workflowId).not.toContain("/src/execution/");
+ expect(sessionTimeoutWorkflowReference.workflowId).not.toContain("@");
});
});
@@ -281,9 +287,17 @@ describe("createWorkflowRuntime#run", () => {
return createWorkflowRuntime({ compiledArtifactsSource });
}
- function mockBundleAndRun(compiledArtifactsSource: RuntimeCompiledArtifactsSource): void {
+ function mockBundleAndRun(
+ compiledArtifactsSource: RuntimeCompiledArtifactsSource,
+ sessionTimeoutMs?: number | false,
+ ): void {
vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({
compiledArtifactsSource,
+ resolvedAgent: {
+ config: {
+ limits: sessionTimeoutMs === undefined ? undefined : { sessionTimeoutMs },
+ },
+ },
} as never);
getRunMock.mockReturnValue({
getReadable: () =>
@@ -351,6 +365,25 @@ describe("createWorkflowRuntime#run", () => {
expect(startOptions.attributes["$eve.title"]).toBe("ship it");
});
+ it("passes the configured session timeout to the durable workflow", async () => {
+ const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;
+ mockBundleAndRun(compiledArtifactsSource, 86_400_000);
+ startMock.mockResolvedValue({ runId: "driver-run" });
+
+ await buildRuntime(compiledArtifactsSource).run({
+ adapter,
+ auth: null,
+ input: { message: "hello" },
+ mode: "conversation",
+ });
+
+ const [, [workflowInput]] = startMock.mock.calls[0]!;
+ expect(workflowInput).toMatchObject({
+ input: { message: "hello" },
+ sessionTimeoutMs: 86_400_000,
+ });
+ });
+
it("serializes the channel request id into workflow context", async () => {
vi.stubEnv("VERCEL_ENV", "production");
const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;
@@ -393,6 +426,7 @@ describe("createWorkflowRuntime#run", () => {
vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({
compiledArtifactsSource,
nodeId: "researcher",
+ resolvedAgent: { config: {} },
} as never);
startMock.mockResolvedValue({ runId: "subagent-run" });
@@ -500,6 +534,7 @@ describe("createWorkflowRuntime#run", () => {
const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;
vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({
compiledArtifactsSource,
+ resolvedAgent: { config: {} },
} as never);
const bytes = new TextEncoder().encode('{"type":"test.event"}\n');
const getReadable = vi.fn(
diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.ts
index 921af99fd..d63ab146e 100644
--- a/packages/eve/src/execution/workflow-runtime.ts
+++ b/packages/eve/src/execution/workflow-runtime.ts
@@ -46,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 type { WorkflowEntryInput } from "#execution/workflow-entry.js";
import { walkCauseChain } from "#shared/errors.js";
import {
sessionCancelHookToken,
@@ -54,6 +55,7 @@ import {
const WORKFLOW_ENTRY_NAME = "workflowEntry";
const TURN_WORKFLOW_NAME = "turnWorkflow";
+const SESSION_TIMEOUT_WORKFLOW_NAME = "sessionTimeoutWorkflow";
const EVE_PACKAGE_INFO = resolveInstalledPackageInfo();
export const LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE =
@@ -72,6 +74,7 @@ export const LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE =
export const STABLE_WORKFLOW_NAMES: ReadonlySet<string> = new Set([
WORKFLOW_ENTRY_NAME,
TURN_WORKFLOW_NAME,
+ SESSION_TIMEOUT_WORKFLOW_NAME,
]);
const STABLE_ID_BASE = EVE_PACKAGE_INFO.name;
@@ -103,6 +106,11 @@ export const turnWorkflowReference = {
workflowId: `workflow//${STABLE_ID_BASE}//${TURN_WORKFLOW_NAME}`,
};
+/** Stable workflow reference for session deadline timers. */
+export const sessionTimeoutWorkflowReference = {
+ workflowId: `workflow//${STABLE_ID_BASE}//${SESSION_TIMEOUT_WORKFLOW_NAME}`,
+};
+
/**
* Creates a workflow-backed runtime whose long-lived driver owns the
* event stream and dispatches each turn as a child workflow run.
@@ -120,6 +128,17 @@ export function createWorkflowRuntime(config: {
const ctx = buildRunContext({ bundle, run: input });
const serializedContext = serializeContext(ctx);
const parentLineage = readParentLineage(serializedContext);
+ const sessionTimeoutMs = bundle.resolvedAgent.config.limits?.sessionTimeoutMs;
+ const workflowInput: {
+ -readonly [K in keyof WorkflowEntryInput]: WorkflowEntryInput[K];
+ } = {
+ input: input.input,
+ limits: input.limits,
+ serializedContext,
+ };
+ if (sessionTimeoutMs !== undefined) {
+ workflowInput.sessionTimeoutMs = sessionTimeoutMs;
+ }
const attributes =
parentLineage.sessionId === undefined
? buildSessionAttributes({
@@ -137,20 +156,10 @@ export function createWorkflowRuntime(config: {
let run: Awaited<ReturnType<typeof startWorkflowPreferLatest>>;
try {
- run = await startWorkflowPreferLatest(
- workflowEntryReference,
- [
- {
- input: input.input,
- limits: input.limits,
- serializedContext,
- },
- ],
- {
- allowReservedAttributes: true,
- attributes: normalizeEveAttributes(attributes),
- },
- );
+ run = await startWorkflowPreferLatest(workflowEntryReference, [workflowInput], {
+ allowReservedAttributes: true,
+ attributes: normalizeEveAttributes(attributes),
+ });
} catch (error) {
logError(log, "failed to start workflow run", error, {
continuationToken: input.continuationToken,
diff --git a/packages/eve/src/internal/authored-definition/core.test.ts b/packages/eve/src/internal/authored-definition/core.test.ts
index 46043724a..7a6e94e7f 100644
--- a/packages/eve/src/internal/authored-definition/core.test.ts
+++ b/packages/eve/src/internal/authored-definition/core.test.ts
@@ -95,6 +95,7 @@ describe("normalizeAgentDefinition", () => {
limits: {
maxInputTokensPerSession: 200_000,
maxOutputTokensPerSession: 20_000,
+ sessionTimeoutMs: 86_400_000,
},
},
FAILURE_MESSAGE,
@@ -103,6 +104,7 @@ describe("normalizeAgentDefinition", () => {
expect(definition.limits).toEqual({
maxInputTokensPerSession: 200_000,
maxOutputTokensPerSession: 20_000,
+ sessionTimeoutMs: 86_400_000,
});
});
@@ -113,6 +115,7 @@ describe("normalizeAgentDefinition", () => {
limits: {
maxInputTokensPerSession: false,
maxOutputTokensPerSession: false,
+ sessionTimeoutMs: false,
},
},
FAILURE_MESSAGE,
@@ -121,6 +124,7 @@ describe("normalizeAgentDefinition", () => {
expect(definition.limits).toEqual({
maxInputTokensPerSession: false,
maxOutputTokensPerSession: false,
+ sessionTimeoutMs: false,
});
});
@@ -157,7 +161,11 @@ describe("normalizeAgentDefinition", () => {
["maxOutputTokensPerSession", 1.5],
["maxOutputTokensPerSession", -1],
["maxOutputTokensPerSession", "20000"],
- ])("rejects invalid session token limit %s=%j", (key, value) => {
+ ["sessionTimeoutMs", 0],
+ ["sessionTimeoutMs", 1.5],
+ ["sessionTimeoutMs", -1],
+ ["sessionTimeoutMs", "30d"],
+ ])("rejects invalid session runtime limit %s=%j", (key, value) => {
expect(() =>
normalizeAgentDefinition(
{
diff --git a/packages/eve/src/internal/authored-definition/core.ts b/packages/eve/src/internal/authored-definition/core.ts
index 688a2016a..cb762b803 100644
--- a/packages/eve/src/internal/authored-definition/core.ts
+++ b/packages/eve/src/internal/authored-definition/core.ts
@@ -162,7 +162,7 @@ function normalizeAgentModelDefinition(
} as NormalizedAgentDefinition["model"];
}
-/** `false` means "explicitly uncapped" for session token limits. */
+/** `false` explicitly disables one numeric runtime limit. */
function expectPositiveIntegerOrFalse(value: unknown, message: string): number | false {
if (value === false) {
return false;
@@ -176,9 +176,19 @@ function normalizeAgentLimitsDefinition(
message: string,
): NonNullable<NormalizedAgentDefinition["limits"]> {
const record = expectObjectRecord(value, message);
- expectOnlyKnownKeys(record, ["maxInputTokensPerSession", "maxOutputTokensPerSession"], message);
+ expectOnlyKnownKeys(
+ record,
+ ["maxInputTokensPerSession", "maxOutputTokensPerSession", "sessionTimeoutMs"],
+ message,
+ );
const normalizedDefinition: Mutable<NonNullable<NormalizedAgentDefinition["limits"]>> = {};
+ if (record.sessionTimeoutMs !== undefined) {
+ normalizedDefinition.sessionTimeoutMs = expectPositiveIntegerOrFalse(
+ record.sessionTimeoutMs,
+ message,
+ );
+ }
if (record.maxInputTokensPerSession !== undefined) {
normalizedDefinition.maxInputTokensPerSession = expectPositiveIntegerOrFalse(
record.maxInputTokensPerSession,
diff --git a/packages/eve/src/internal/testing/app-harness.ts b/packages/eve/src/internal/testing/app-harness.ts
index b58633978..4f102a71c 100644
--- a/packages/eve/src/internal/testing/app-harness.ts
+++ b/packages/eve/src/internal/testing/app-harness.ts
@@ -37,6 +37,7 @@ export interface TestAppDescriptor {
readonly limits?: {
readonly maxInputTokensPerSession?: number | false;
readonly maxOutputTokensPerSession?: number | false;
+ readonly sessionTimeoutMs?: number | false;
};
readonly model?: string;
readonly name?: string;
@@ -139,6 +140,7 @@ export function createTestRuntime(descriptor: TestAppDescriptor = {}): TestRunti
limits?: {
readonly maxInputTokensPerSession?: number | false;
readonly maxOutputTokensPerSession?: number | false;
+ readonly sessionTimeoutMs?: number | false;
};
outputSchema?: JsonObject;
tools?: readonly {
diff --git a/packages/eve/src/internal/workflow-bundle/workflow-core-shim.test.ts b/packages/eve/src/internal/workflow-bundle/workflow-core-shim.test.ts
new file mode 100644
index 000000000..3a27319ff
--- /dev/null
+++ b/packages/eve/src/internal/workflow-bundle/workflow-core-shim.test.ts
@@ -0,0 +1,31 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { sleep } from "#internal/workflow-bundle/workflow-core-shim.js";
+
+const WORKFLOW_SLEEP = Symbol.for("WORKFLOW_SLEEP");
+const workflowGlobal = globalThis as typeof globalThis & Record<symbol, unknown>;
+const originalSleep = workflowGlobal[WORKFLOW_SLEEP];
+
+afterEach(() => {
+ if (originalSleep === undefined) {
+ delete workflowGlobal[WORKFLOW_SLEEP];
+ } else {
+ workflowGlobal[WORKFLOW_SLEEP] = originalSleep;
+ }
+});
+
+describe("workflow core shim sleep", () => {
+ it("forwards durable durations to the workflow VM implementation", async () => {
+ const sleepImpl = vi.fn(async () => {});
+ workflowGlobal[WORKFLOW_SLEEP] = sleepImpl;
+
+ await expect(sleep(2_500)).resolves.toBeUndefined();
+ expect(sleepImpl).toHaveBeenCalledExactlyOnceWith(2_500);
+ });
+
+ it("rejects use outside a workflow body", () => {
+ delete workflowGlobal[WORKFLOW_SLEEP];
+
+ expect(() => sleep(2_500)).toThrow("`sleep()` can only be called inside a workflow function");
+ });
+});
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 f7efc68f1..7303b5029 100644
--- a/packages/eve/src/internal/workflow-bundle/workflow-core-shim.ts
+++ b/packages/eve/src/internal/workflow-bundle/workflow-core-shim.ts
@@ -1,6 +1,7 @@
const WORKFLOW_CONTEXT_SYMBOL = Symbol.for("WORKFLOW_CONTEXT");
const WORKFLOW_CREATE_HOOK = Symbol.for("WORKFLOW_CREATE_HOOK");
const WORKFLOW_GET_STREAM_ID = Symbol.for("WORKFLOW_GET_STREAM_ID");
+const WORKFLOW_SLEEP = Symbol.for("WORKFLOW_SLEEP");
const WORKFLOW_USE_STEP = Symbol.for("WORKFLOW_USE_STEP");
const STREAM_NAME_SYMBOL = Symbol.for("WORKFLOW_STREAM_NAME");
const workflowGlobal = globalThis as typeof globalThis & Record<symbol, unknown>;
@@ -96,8 +97,16 @@ export function defineHook<T = unknown>(): {
/**
* Sleeps from inside workflow-body code.
*/
-export function sleep(): never {
- throw new Error("`sleep()` is not available in eve workflow body bundles");
+export function sleep(duration: string | number | Date): Promise<void> {
+ const sleepFn = workflowGlobal[WORKFLOW_SLEEP] as
+ | ((sleepDuration: string | number | Date) => Promise<void>)
+ | undefined;
+
+ if (sleepFn === undefined) {
+ throw new Error("`sleep()` can only be called inside a workflow function");
+ }
+
+ return sleepFn(duration);
}
/**
diff --git a/packages/eve/src/public/definitions/exact.test.ts b/packages/eve/src/public/definitions/exact.test.ts
index 0145c2e1b..d504ad010 100644
--- a/packages/eve/src/public/definitions/exact.test.ts
+++ b/packages/eve/src/public/definitions/exact.test.ts
@@ -25,6 +25,7 @@ describe("definition helper exact inputs", () => {
limits: {
maxInputTokensPerSession: 200_000,
maxOutputTokensPerSession: 20_000,
+ sessionTimeoutMs: 86_400_000,
},
model: "anthropic/claude-sonnet-5",
});
@@ -37,6 +38,7 @@ describe("definition helper exact inputs", () => {
expect(agent.description).toBe("type-test");
expect(agent.limits.maxInputTokensPerSession).toBe(200_000);
expect(agent.limits.maxOutputTokensPerSession).toBe(20_000);
+ expect(agent.limits.sessionTimeoutMs).toBe(86_400_000);
expect(experimental_workflow({ maxSubagents: 6 }).maxSubagents).toBe(6);
expect(schedule.cron).toBe("0 9 * * *");
});
diff --git a/packages/eve/src/runtime/resolve-agent.ts b/packages/eve/src/runtime/resolve-agent.ts
index 48418b865..980068391 100644
--- a/packages/eve/src/runtime/resolve-agent.ts
+++ b/packages/eve/src/runtime/resolve-agent.ts
@@ -249,6 +249,7 @@ function createResolvedAgentConfig(manifest: CompiledAgentNodeManifest): Resolve
config.limits = {
maxInputTokensPerSession: manifest.config.limits.maxInputTokensPerSession,
maxOutputTokensPerSession: manifest.config.limits.maxOutputTokensPerSession,
+ sessionTimeoutMs: manifest.config.limits.sessionTimeoutMs,
};
}
diff --git a/packages/eve/src/shared/agent-definition.ts b/packages/eve/src/shared/agent-definition.ts
index 2d8cee7bb..7acc839d6 100644
--- a/packages/eve/src/shared/agent-definition.ts
+++ b/packages/eve/src/shared/agent-definition.ts
@@ -149,6 +149,18 @@ export interface PublicAgentCompactionDefinition {
* Configures framework-owned runtime limits for this agent's runs.
*/
export interface AgentLimitsDefinition {
+ /**
+ * Maximum lifetime of one durable session, in milliseconds.
+ *
+ * The deadline starts when the session is created and survives process
+ * restarts and redeployments. If it elapses during an active turn, eve lets
+ * that turn settle before completing the session normally.
+ *
+ * `false` disables the timeout.
+ *
+ * @default 2_592_000_000 (30 days)
+ */
+ readonly sessionTimeoutMs?: number | false;
/**
* Maximum provider-reported input tokens accumulated by one durable session.
*
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 0dac567a9..2e6cfdac5 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -726,6 +726,31 @@ importers:
specifier: 'catalog:'
version: 7.0.2
+ e2e/fixtures/agent-session-timeout:
+ dependencies:
+ '@opentelemetry/core':
+ specifier: 'catalog:'
+ version: 2.6.1(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace-base':
+ specifier: 'catalog:'
+ version: 2.6.1(@opentelemetry/[email protected])
+ '@vercel/otel':
+ specifier: 'catalog:'
+ version: 2.1.3(@opentelemetry/[email protected])(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected])([email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))
+ ai:
+ specifier: 'catalog:'
+ version: 7.0.38([email protected])
+ eve:
+ specifier: workspace:*
+ version: link:../../../packages/eve
+ devDependencies:
+ '@types/node':
+ specifier: 'catalog:'
+ version: 25.9.1
+ typescript:
+ specifier: 'catalog:'
+ version: 7.0.2
+
e2e/fixtures/agent-skills:
dependencies:
'@opentelemetry/core':