The Open Framework for Building Agents
Make session timeouts idle-based (#5119)
Andrew Barba964a41f032aa
diff --git a/.changeset/idle-session-timeout.md b/.changeset/idle-session-timeout.mdnew file mode 100644index 000000000..cdc081371--- /dev/null+++ b/.changeset/idle-session-timeout.md@@ -0,0 +1,5 @@+---+"eve": patch+---++`limits.sessionTimeoutMs` is now an idle timeout: the window restarts each time a turn settles, so a session in active use no longer ends 30 days after it was created. Idle sessions still complete when the window elapses, and the next channel message at their address starts a fresh session as before.diff --git a/docs/agent-config.md b/docs/agent-config.mdindex 1c9781558..b1aa0d4d6 100644--- a/docs/agent-config.md+++ b/docs/agent-config.md@@ -278,15 +278,20 @@ export default defineAgent({});```-`sessionTimeoutMs` sets the lifetime for every session, including delegated-sessions. It defaults to 30 days and starts at creation. Each successful-deployment handoff or legacy-session import restarts the original configured-duration. Process restarts, ordinary messages, compaction handoffs, and failed-or skipped handoffs keep the existing deadline. At the deadline, eve lets an active turn settle,-then emits `session.completed` and releases every continuation address; the next-qualifying channel message starts fresh. Set it to `false` to disable the-timeout. Session expiration follows [run-data retention](#run-data-retention);-a zero-retention session loses its stored payloads when it ends.+`sessionTimeoutMs` sets how long a session may sit idle before eve completes it,+for every session, including delegated sessions. It defaults to 30 days. The+idle window starts at creation and restarts each time a turn settles, including+turns that answer a message, clear or compact the context, or end in+cancellation. A session never expires while a turn is open, including a turn+held open while its [tasks](./tools/tasks) work or while it waits for a person+to answer; the window restarts when that turn settles. Process restarts do not+change the window. When the window elapses, eve emits `session.completed` and+releases every continuation address; the next qualifying channel message starts+fresh. To carry an earlier conversation into the fresh session, pass it as+[prior history](./channels/eve#start-from-prior-history). Set it to `false` to+disable the timeout. Session expiration follows+[run-data retention](#run-data-retention); a zero-retention session loses its+stored payloads when it ends.Input tokens, output tokens, and model token cost are checked independently.The model call that crosses a limit is allowed to finish because exact usage@@ -496,7 +501,7 @@ keeps the data. Confirm support with your World provider. See| -------------- | ------------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ || `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, and [`promptCache`](#prompt-caching) settings. |-| `limits` | `AgentLimitsDefinition` | field-specific | Framework-owned runtime limits. Sessions complete after 30 days by default; usage-limit defaults and inheritance are described above. Set a limit to `false` to disable it. |+| `limits` | `AgentLimitsDefinition` | field-specific | Framework-owned runtime limits. Sessions complete after 30 idle days by default; usage-limit defaults and inheritance are described above. Set a limit to `false` to disable it. || `experimental` | `AgentExperimentalDefinition` | unset | Unstable opt-ins. `workflow.world` selects the Workflow world package on the root agent; `workflow.modelCallsPerStep` batches sequential model calls into a wider replay unit; `workflow.retention` controls how long the durable runtime keeps run data. || `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. || `tool` | `boolean \| "deferred"` | `true` | Exposes this agent to its parent model as a tool. `"deferred"` keeps it out of the model's tool list; the model finds it with `eve__search` and calls it with `eve__tool`. On the root agent, controls the built-in `agent` tool. A subagent with `tool: false` remains callable from authored workflow tools through `ctx.agent()`. |diff --git a/docs/concepts/execution-model-and-durability.mdx b/docs/concepts/execution-model-and-durability.mdxindex cb8255be4..a1cc19ac9 100644--- a/docs/concepts/execution-model-and-durability.mdx+++ b/docs/concepts/execution-model-and-durability.mdx@@ -23,7 +23,7 @@ replay unit.The Workflow SDK is not inherently tied to Vercel. In local development and in a self-deployed `eve start` process, eve uses the SDK's local world by default; that world persists workflow runs on disk under `.eve/.workflow-data` and dispatches through the same Nitro-hosted workflow routes. On Vercel, the same workflow code runs against Vercel Workflow instead, which adds deployment-aware routing and dashboard run metadata.-When a Vercel production deployment changes, a new delivery to an idle session hands the session's settled state to the exact deployment that accepted the request. This applies whether the delivery arrives through the session ID or through any channel continuation address the session has claimed. The session keeps its original ID and event stream, while the next model turn uses that deployment's current system-role instructions, model, and tools. Static user-role instructions stay pinned in the durable conversation history and are not seeded again. A successful handoff restarts the session's original configured [`sessionTimeoutMs`](../agent-config#runtime-limits) duration; disabled timeouts stay disabled. Failed or skipped handoffs keep the existing deadline.+When a Vercel production deployment changes, a new delivery to an idle session hands the session's settled state to the exact deployment that accepted the request. This applies whether the delivery arrives through the session ID or through any channel continuation address the session has claimed. The session keeps its original ID and event stream, while the next model turn uses that deployment's current system-role instructions, model, and tools. Static user-role instructions stay pinned in the durable conversation history and are not seeded again. As with any turn, the triggering delivery restarts the session's [`sessionTimeoutMs`](../agent-config#runtime-limits) idle window, whether or not the handoff succeeds; disabled timeouts stay disabled.Before taking ownership, the target deployment upgrades the checkpoint when an older eve release wrote it, then checks that no pending work remains. A deployment accepts checkpoints from eve 0.66.0 and later, so upgrading eve does not leave long-lived sessions, such as a Slack thread, on their old deployment. An older release cannot read a newer checkpoint: after a rollback, a session that already moved to the newer deployment stays there. Extension state saved before eve 0.69 moves to its mount when exactly one mount of that extension package defines that state. State that the target deployment no longer defines, such as a removed `defineState` key, is dropped, and the target deployment's runtime logs show a `dropping unknown context key during deserialization` warning. When two or more mounts of one extension package define that state, eve cannot choose an owner, and the session stays on its current deployment. Idle subagent sessions that eve 0.66–0.68 kept for later reuse are stopped after the handoff. Authored session state remains opaque to this validation.@@ -39,7 +39,7 @@ eve does not move live work between deployments. A session with a running turn,Every workflow run records each step it executes, so a session that ran on one run for weeks would carry its whole history in that run. To bound this, eve moves a session to a fresh run on its current deployment after [compaction](./default-harness#compaction) rewrites the conversation history. This applies to automatic compaction during a turn and to a client or channel compaction request.-The move happens once the turn settles and nothing else is waiting: no queued messages, running tasks or subagents, or pending human input. The new run receives the compacted history and settled state, then waits for the next message. A message that is already waiting when the turn settles runs on the current run first, and the session moves at the next point where nothing is waiting. A message that arrives after the move starts is accepted right away and runs once, on the new run. If work is still pending, eve tries again after a later turn settles. The session keeps its ID, event stream, continuation addresses, and deadline; compaction never extends [`sessionTimeoutMs`](../agent-config#runtime-limits). If the new run cannot take ownership, the current run keeps the session, writes a `session handoff failed` warning to its runtime logs, and tries again later.+The move happens once the turn settles and nothing else is waiting: no queued messages, running tasks or subagents, or pending human input. The new run receives the compacted history and settled state, then waits for the next message. A message that is already waiting when the turn settles runs on the current run first, and the session moves at the next point where nothing is waiting. A message that arrives after the move starts is accepted right away and runs once, on the new run. If work is still pending, eve tries again after a later turn settles. The session keeps its ID, event stream, and continuation addresses, and its [`sessionTimeoutMs`](../agent-config#runtime-limits) idle window still counts from the turn that compacted. If the new run cannot take ownership, the current run keeps the session, writes a `session handoff failed` warning to its runtime logs, and tries again later.Both kinds of handoff need a Workflow world that can move a session's addresses from one run to another without releasing them, and can keep a released address reserved for a while (the `hookForceClaim` and `hookRetention` capabilities). Vercel Workflow, the local world, and `@workflow/world-postgres` 5.0.4 and later provide both. On a world without them, sessions never move between runs: deployment and compaction handoffs are skipped, and a session's run history grows for as long as the session lives. The first skipped attempt writes a `session handoff unavailable` warning to the runtime logs.@@ -138,7 +138,7 @@ The transcript is context only: tools, approvals, files, sandbox contents, authoA stranded root session ends on its next channel message, a reset, or its [session timeout](../agent-config#runtime-limits), whichever comes first. It executes nothing while it waits. When the local world or Postgres recovers active runs at startup, eve acknowledges the root session's delivery without replaying it and logs a warning naming the run and both eve versions. The run keeps its `pending` or `running` status and its addresses. A later restart skips it the same way.-The timeout is the session's own durable timer, armed for the deadline `sessionTimeoutMs` sets from the session's creation or latest deployment handoff (30 days by default; compaction handoffs keep the deadline). The timer is a separate workflow run that keeps working after the upgrade, and when it fires on a stranded session it ends the session the same way a reset does, without starting a fresh one. The next message to the address then starts an ordinary session. A session with `sessionTimeoutMs: false` has no timer, so a stranded one stays until a message or a reset, just as a healthy one would stay open.+The timeout is the session's own durable timer, which its last owner armed for the end of an idle window (30 days by default). An owner re-arms the timer only when the timer fires before the window ends, so a stranded session ends at most `sessionTimeoutMs` after its last turn settled, and possibly sooner. The timer is a separate workflow run that keeps working after the upgrade, and when it fires on a stranded session it ends the session the same way a reset does, without starting a fresh one. The next message to the address then starts an ordinary session. A session with `sessionTimeoutMs: false` has no timer, so a stranded one stays until a message or a reset, just as a healthy one would stay open.Ending a root session does not find or cancel its subagent sessions and workflow tool runs. Each one is cancelled when a delivery for it reaches the current deployment, with the cancellation reason `Run retired: its eve deployment is no longer available`, and eve logs a `Retired stranded descendant run` warning. A run that never receives a delivery, such as one parked in a dormant `eve dev` generation, can stay active; cancel it in your Workflow world if you need to. Cancellation does not run authored cleanup or lifecycle hooks, undo side effects, or stop independent external jobs, and results and approvals do not carry over to a replacement session.@@ -164,7 +164,7 @@ fresh session.Keep the original deployment available until these sessions end. Their olddrivers remain waiting to keep the original streams open; the current runtime-owns subsequent turns. Import restarts the original configured session timeout;+owns subsequent turns. Import restarts the session's idle window;disabled timeouts stay disabled. A driverthat has not reached its next turn dispatch has not migrated yet.diff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.mdindex 4dec737ba..dc82f08ac 100644--- a/docs/concepts/sessions-runs-and-streaming.md+++ b/docs/concepts/sessions-runs-and-streaming.md@@ -21,13 +21,13 @@ whichever session currently owns a platform conversation, such as a Slack threadThat identity stays behind the channel boundary and is never accepted or returnedby the eve HTTP session API. See [Custom channels](../channels/custom#channel-operations-and-session-handles).-Sessions last 30 days by default; configure `limits.sessionTimeoutMs` in-`agent.ts`, or set it to `false` to disable the deadline. A successful deployment-handoff or legacy-session import restarts the original configured duration.-Ordinary messages, compaction handoffs, and process restarts keep the existing deadline. At expiration, eve-lets an active turn settle, emits `session.completed`, and releases the-session's continuation addresses so the next qualifying channel message starts fresh. Stored-session data is not deleted. See [Agent config](../agent-config#runtime-limits).+A session completes after 30 idle days by default; configure+`limits.sessionTimeoutMs` in `agent.ts`, or set it to `false` to disable the+timeout. The idle window restarts each time a turn settles, and a session never+expires while a turn is open. At expiration, eve emits `session.completed` and+releases the session's continuation addresses 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.diff --git a/docs/tools/tasks.md b/docs/tools/tasks.mdindex 358263acb..aa5660017 100644--- a/docs/tools/tasks.md+++ b/docs/tools/tasks.md@@ -308,9 +308,10 @@ task's start and end instead. Seeand enforce per-person access inside the tool.- **Working tasks.** A session runs at most 32 working tasks at once. An idle resumable task doesn'tcount, and a call that makes it work again does.-- **No time limits.** Tasks have no timeout of their own. The session lifetime,- `limits.sessionTimeoutMs` (30 days by default), bounds all work in a session. A body that needs a- deadline races `sleep` against its work.+- **No time limits.** Tasks have no timeout of their own, and the session timeout does not bound+ them. A turn held open while its tasks work keeps the session open, and+ `limits.sessionTimeoutMs` (30 idle days by default) counts from when that turn settles. A body+ that needs a deadline races `sleep` against its work.## Upgrade from background tasksdiff --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.tsindex 8c1591104..a6244c388 100644--- 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@@ -24,7 +24,7 @@ async function postJson<T>(target: EveEvalTargetHandle, path: string, body: unknexport default defineEval({description:- "Session TTL lets an active turn settle, then the same channel thread starts a new session.",+ "Session idle timeout waits out an active turn, then the same channel thread starts a new session.",async test(t) {const threadId = crypto.randomUUID();diff --git a/packages/eve/src/execution/legacy-session/turn-workflow.ts b/packages/eve/src/execution/legacy-session/turn-workflow.tsindex dff923081..e1d080447 100644--- a/packages/eve/src/execution/legacy-session/turn-workflow.ts+++ b/packages/eve/src/execution/legacy-session/turn-workflow.ts@@ -3,7 +3,6 @@ import { sessionHookTokens } from "#execution/session/hook-tokens.js";import { sessionCommandHookToken } from "#execution/session-inbox/address.js";import { createSessionInbox } from "#execution/session-inbox/inbox.js";import { failSession, runPreparedSession } from "#execution/session/program.js";-import { sessionTimeoutDeadline } from "#execution/session/timeout.js";import { createSessionTimeoutControl } from "#execution/session/timeout-control.js";import { recordSessionOwnerStep } from "#execution/session/handoff-steps.js";import { completeLegacyDriverStep } from "./completion-step.js";@@ -45,7 +44,6 @@ export async function turnWorkflow(rawInput: unknown): Promise<void> {sessionWritable,});}- const timeoutDeadline = sessionTimeoutDeadline(prepared.sessionTimeoutMs, Date.now());const initialDeliveryKey = prepared.input.delivery?.idempotencyKey;await runPreparedSession({@@ -77,12 +75,11 @@ export async function turnWorkflow(rawInput: unknown): Promise<void> {serializedContext: interrupted.serializedContext,sessionId,sessionState: interrupted.sessionState,- sessionTimeoutControl:- timeoutDeadline === undefined- ? undefined- : createSessionTimeoutControl({ deadline: timeoutDeadline, sessionId }),+ sessionTimeoutControl: createSessionTimeoutControl({+ sessionId,+ timeoutMs: prepared.sessionTimeoutMs,+ }),sessionTimeoutMs: prepared.sessionTimeoutMs,- sessionTimeoutDeadline: timeoutDeadline,sessionWritable,},inbox,diff --git a/packages/eve/src/execution/session/entry-handoff-lifetime.integration.test.ts b/packages/eve/src/execution/session/entry-handoff-lifetime.integration.test.tsindex 1320add6f..9c9e8d5e8 100644--- a/packages/eve/src/execution/session/entry-handoff-lifetime.integration.test.ts+++ b/packages/eve/src/execution/session/entry-handoff-lifetime.integration.test.ts@@ -222,7 +222,7 @@ describe("workflowEntry integration", () => {describe("compaction handoff", () => {afterEach(() => vi.restoreAllMocks());- it("moves each compacted session to a fresh run on its deployment and keeps its deadline", async () => {+ it("moves each compacted session to a fresh run on its deployment and restarts its idle window", async () => {const output = captureConsoleOutput();const runtime = await createTestRuntime({ agent: { name: "workflow-entry-compaction" } });@@ -277,9 +277,7 @@ describe("workflowEntry integration", () => {const originalTimer = await readSessionTimer(anchor.runId);const successor = await compactTo(anchor.runId);- expect((await readSessionTimer(successor.runId)).deadline).toEqual(- originalTimer.deadline,- );+ await expectIdleWindowFromBoot(successor.runId, originalTimer.deadline);await vi.waitFor(async () =>expect((await world.runs.get(originalTimer.runId)).status).toBe("cancelled"),);@@ -339,9 +337,7 @@ describe("workflowEntry integration", () => {expect((await world.runs.get(successor.runId)).status).toBe("completed"),);expect((await world.runs.get(anchor.runId)).status).toBe("running");- expect((await readSessionTimer(nextOwner.runId)).deadline).toEqual(- originalTimer.deadline,- );+ await expectIdleWindowFromBoot(nextOwner.runId, originalTimer.deadline);await workflowRuntime.dispatchSession({command: { kind: "reset", reason: "compaction handoff test" },@@ -461,6 +457,16 @@ describe("workflowEntry integration", () => {});});+/** A successor boots right after the turn that compacted, so its window starts at boot. */+async function expectIdleWindowFromBoot(ownerRunId: string, previousDeadline: Date): Promise<void> {+ const timer = await readSessionTimer(ownerRunId);+ const owner = await (await getWorld()).runs.get(ownerRunId);+ expect(timer.deadline.getTime()).toBeGreaterThan(previousDeadline.getTime());+ expect(timer.deadline.getTime()).toBeGreaterThanOrEqual(+ (owner.startedAt ?? owner.createdAt).getTime() + 60_000,+ );+}+async function readSessionTimer(ownerRunId: string): Promise<{ runId: string; deadline: Date }> {const world = await getWorld();let timer: { runId: string; deadline: Date } | undefined;diff --git a/packages/eve/src/execution/session/entry-input.ts b/packages/eve/src/execution/session/entry-input.tsindex 65972ce72..985d20e52 100644--- a/packages/eve/src/execution/session/entry-input.ts+++ b/packages/eve/src/execution/session/entry-input.ts@@ -47,8 +47,6 @@ export type SessionHandoffStart =* successor parks until the next input arrives.*/readonly delivery?: DeliverHookPayload;- /** Compaction does not extend the session's lifetime. */- readonly sessionTimeoutDeadline?: Date;};/** A successor owner started by a previous owner during a handoff. */diff --git a/packages/eve/src/execution/session/entry.integration.test.ts b/packages/eve/src/execution/session/entry.integration.test.tsindex 9f75d0609..d6bcc99a9 100644--- a/packages/eve/src/execution/session/entry.integration.test.ts+++ b/packages/eve/src/execution/session/entry.integration.test.ts@@ -1,6 +1,6 @@import { afterEach, describe, expect, it, vi } from "vitest";-import { getWorld, resumeHook, start } from "#internal/workflow/runtime.js";-import { hydrateWorkflowArguments } from "@workflow/core/serialization";+import { cancelRun, getWorld, resumeHook, start } from "#internal/workflow/runtime.js";+import { hydrateStepReturnValue, hydrateWorkflowArguments } from "@workflow/core/serialization";import { createChannelAddress } from "#channel/channel-address.js";import { captureTurnEvents, filterEventsByType } from "#internal/testing/events.js";import { createTestRuntime } from "#internal/testing/app-harness.js";@@ -674,6 +674,50 @@ describe("workflowEntry integration", () => {});});+ it("keeps a session open when its timer fires within the idle window of its last turn", async () => {+ const runtime = await createTestRuntime({ agent: { name: "workflow-entry-idle-timeout" } });++ await runtime.run(async () => {+ const run = await startSessionOwner(workflowEntry, [+ {+ kind: "initial",+ ownerDeploymentId: "dpl_inline",+ input: { message: "hello there" },+ serializedContext: buildSerializedContext({ channelKind: "http" }),+ sessionTimeoutMs: 60_000,+ },+ ]);+ const stream = captureTurnEvents(run);+ try {+ expect((await stream.nextTurn()).at(-1)?.type).toBe("session.waiting");+ let armedAtCreation: SessionTimer | undefined;+ await vi.waitFor(async () => {+ [armedAtCreation] = await readSessionTimers(run.runId);+ expect(armedAtCreation).toBeDefined();+ });++ // Stand in for the creation timer firing early: end its run, then deliver its signal.+ await cancelRun(await getWorld(), armedAtCreation!.runId);+ await resumeHook(sessionInboxHookToken(sessionCommandHookToken(run.runId)), {+ kind: "session-timeout",+ ownerRunId: run.runId,+ });++ let timers: SessionTimer[] = [];+ await vi.waitFor(async () => {+ timers = await readSessionTimers(run.runId);+ expect(timers).toHaveLength(2);+ });+ // The first turn moved the deadline, so the replacement timer targets a later one.+ expect(timers[1]!.deadline.getTime()).toBeGreaterThan(armedAtCreation!.deadline.getTime());+ await expect(run.status).resolves.toBe("running");+ } finally {+ stream.dispose();+ await run.cancel();+ }+ });+ });+it("completes an expired conversation and lets its channel start a fresh session", async () => {const runtime = await createTestRuntime({ agent: { name: "workflow-entry-timeout" } });const continuationToken = "http:workflow-entry-timeout";@@ -1805,3 +1849,27 @@ async function resetAndRelease(run: HeldApprovalRun["run"]): Promise<void> {);await withTimeout(run.returnValue, "session release");}++interface SessionTimer {+ readonly deadline: Date;+ readonly runId: string;+}++/** Timers an owner armed, oldest first, with the deadline each one sleeps until. */+async function readSessionTimers(ownerRunId: string): Promise<SessionTimer[]> {+ const world = await getWorld();+ const steps = await world.steps.list({ runId: ownerRunId, resolveData: "all" });+ const timers: SessionTimer[] = [];+ for (const step of steps.data) {+ if (!step.stepName.endsWith("//startSessionTimeoutStep") || step.output === undefined) continue;+ const { runId } = (await hydrateStepReturnValue(step.output, ownerRunId, undefined)) as {+ runId: string;+ };+ const run = await world.runs.get(runId);+ const [input] = (await hydrateWorkflowArguments(run.input, runId, undefined)) as [+ { deadline: Date },+ ];+ timers.push({ deadline: input.deadline, runId });+ }+ return timers.sort((a, b) => a.deadline.getTime() - b.deadline.getTime());+}diff --git a/packages/eve/src/execution/session/entry.test.ts b/packages/eve/src/execution/session/entry.test.tsindex 6d0b2fbd5..a039b77c3 100644--- a/packages/eve/src/execution/session/entry.test.ts+++ b/packages/eve/src/execution/session/entry.test.ts@@ -249,7 +249,6 @@ describe("bootInitialOwner timeout startup", () => {const boot = await bootInitialOwner(initialInput({ sessionTimeoutMs: false }), "session-1");expect(boot?.session.initialTurnControl).toBeDefined();- expect(boot?.session.sessionTimeoutDeadline).toBeUndefined();expect(boot?.session.sessionTimeoutControl).toBeUndefined();expect(createTurnControl).toHaveBeenCalledOnce();expect(startSessionTimeoutStep).not.toHaveBeenCalled();diff --git a/packages/eve/src/execution/session/entry.ts b/packages/eve/src/execution/session/entry.tsindex a1d8eaf61..df6ce8f0b 100644--- a/packages/eve/src/execution/session/entry.ts+++ b/packages/eve/src/execution/session/entry.ts@@ -15,7 +15,7 @@ import {type SessionInboxPayload,} from "#execution/session-inbox/inbox.js";import { sessionHookTokens } from "#execution/session/hook-tokens.js";-import { DEFAULT_SESSION_TIMEOUT_MS, sessionTimeoutDeadline } from "#execution/session/timeout.js";+import { DEFAULT_SESSION_TIMEOUT_MS } from "#execution/session/timeout.js";import {createSessionTimeoutControl,type SessionTimeoutControl,@@ -107,8 +107,8 @@ async function prepareInitialOwner(inbox: SessionInboxHandle,input: {readonly continuationToken: string;- readonly deadline: Date | undefined;readonly sessionId: string;+ readonly sessionTimeoutMs: number | false;},): Promise<InitialOwnerPreparation> {const [stableClaim, aliasClaim] = await Promise.allSettled([@@ -124,10 +124,10 @@ async function prepareInitialOwner(}const turnControl = createTurnControl();- const timeoutControl =- input.deadline === undefined- ? undefined- : createSessionTimeoutControl({ deadline: input.deadline, sessionId: input.sessionId });+ const timeoutControl = createSessionTimeoutControl({+ sessionId: input.sessionId,+ timeoutMs: input.sessionTimeoutMs,+ });const owner: OwnedInitialSession = {kind: "owned",timeoutControl,@@ -169,8 +169,6 @@ export async function bootInitialOwner(const sessionWritable = getWritable<Uint8Array>();const inbox = createSessionInbox(sessionId);const sessionTimeoutMs = input.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;- // Workflow's clock is replay-stable; its optimistic startedAt metadata is not.- const deadline = sessionTimeoutDeadline(sessionTimeoutMs, Date.now());const continuationToken = (serializedContext["eve.continuationToken"] as string) || "";const serializedBundle = serializedContext["eve.bundle"] as {source: DurableCompiledArtifactsSource;@@ -194,8 +192,8 @@ export async function bootInitialOwner(});const ownerPreparationPromise = prepareInitialOwner(inbox, {continuationToken,- deadline,sessionId,+ sessionTimeoutMs,});const callerResolutionPromise = hasDelegatedSessionContext(serializedContext)? resolveInitialTurnCallerStep({ serializedContext })@@ -241,7 +239,6 @@ export async function bootInitialOwner(sessionState: created.state,sessionTimeoutControl: prepared.timeoutControl,sessionTimeoutMs,- sessionTimeoutDeadline: deadline,sessionWritable,},};@@ -438,12 +435,6 @@ async function startSuccessor(if (childRunIdsToStop.length > 0) {await stopUntrackedChildSessionsStep({ runIds: childRunIdsToStop, sessionId });}- const deadline =- input.reason === "compaction"- ? input.sessionTimeoutDeadline- : sessionTimeoutDeadline(checkpoint.sessionTimeoutMs, Date.now());- const timeoutControl =- deadline === undefined ? undefined : createSessionTimeoutControl({ deadline, sessionId });return {inbox,session: {@@ -459,10 +450,11 @@ async function startSuccessor(serializedContext,sessionId,sessionState: checkpoint.sessionState,- sessionTimeoutControl: timeoutControl,+ sessionTimeoutControl: createSessionTimeoutControl({+ sessionId,+ timeoutMs: checkpoint.sessionTimeoutMs,+ }),sessionTimeoutMs: checkpoint.sessionTimeoutMs,- // A deployment handoff renews the configured lifetime; compaction keeps the deadline.- sessionTimeoutDeadline: deadline,sessionWritable: input.sessionWritable,},};diff --git a/packages/eve/src/execution/session/handoff.test.ts b/packages/eve/src/execution/session/handoff.test.tsindex 76ad1631a..86f25b336 100644--- a/packages/eve/src/execution/session/handoff.test.ts+++ b/packages/eve/src/execution/session/handoff.test.ts@@ -126,17 +126,13 @@ describe("SessionHandoff", () => {it("moves a compacted session to a parked successor on this deployment", async () => {installActivation();startSuccessorStepMock.mockResolvedValue(STARTED);- const sessionTimeoutDeadline = new Date("2026-11-01T00:00:00.000Z");await expect(- createHandoff(createInbox({ takenOver: true })).tryCompactionTransfer(state(), {- sessionTimeoutDeadline,- }),+ createHandoff(createInbox({ takenOver: true })).tryCompactionTransfer(state()),).resolves.toEqual({ kind: "transferred" });const [start] = startSuccessorStepMock.mock.calls[0] as [Record<string, unknown>];expect(start).toMatchObject({reason: "compaction",- sessionTimeoutDeadline,targetDeploymentId: "deployment-a",});expect(start).not.toHaveProperty("delivery");@@ -409,9 +405,10 @@ describe("SessionHandoff", () => {kind: "retained",reason: "unsupported-world",});- await expect(- handoff.tryCompactionTransfer(state(), { sessionTimeoutDeadline: undefined }),- ).resolves.toEqual({ kind: "retained", reason: "unsupported-world" });+ await expect(handoff.tryCompactionTransfer(state())).resolves.toEqual({+ kind: "retained",+ reason: "unsupported-world",+ });expect(startSuccessorStepMock).toHaveBeenCalledTimes(1);expect(reportSessionHandoffRetainedStepMock).not.toHaveBeenCalled();});diff --git a/packages/eve/src/execution/session/handoff.ts b/packages/eve/src/execution/session/handoff.tsindex 29eb9cd42..90e1373e5 100644--- a/packages/eve/src/execution/session/handoff.ts+++ b/packages/eve/src/execution/session/handoff.ts@@ -121,11 +121,6 @@ type SessionRetainedReason =| "known-incompatible"| "unsupported-world";-/** A compaction handoff the owner owes; the successor keeps this deadline. */-export interface CompactionHandoff {- readonly sessionTimeoutDeadline: Date | undefined;-}-type SessionTransferState = Pick<SessionCheckpoint,"admittedDeliveryKeys" | "history" | "serializedContext" | "sessionState"@@ -268,16 +263,13 @@ export class SessionHandoff {/*** Attempts to move a session that compacted to a fresh run on this* deployment. The caller guarantees no input is waiting; the successor- * parks until the next one arrives and keeps the session's deadline.+ * parks until the next one arrives.*/- async tryCompactionTransfer(- state: SessionTransferState,- compaction: CompactionHandoff,- ): Promise<SessionTransferOutcome> {+ async tryCompactionTransfer(state: SessionTransferState): Promise<SessionTransferOutcome> {const { deploymentId } = this.input;if (this.incompatibleTargetDeploymentIds.has(deploymentId))return { kind: "retained", reason: "known-incompatible" };- return await this.transfer(state, deploymentId, { ...compaction, reason: "compaction" });+ return await this.transfer(state, deploymentId, { reason: "compaction" });}private async transfer(diff --git a/packages/eve/src/execution/session/program.ts b/packages/eve/src/execution/session/program.tsindex 5bdf8f8af..2585bdfaa 100644--- a/packages/eve/src/execution/session/program.ts+++ b/packages/eve/src/execution/session/program.ts@@ -21,11 +21,7 @@ import { settleCancelledTurnStep } from "#execution/settle-cancelled-turn-step.jimport { finalizeSession, type SessionTerminalOutcome } from "#execution/session/finalization.js";import { type SessionInboxHandle } from "#execution/session-inbox/inbox.js";import type { SessionTimeoutControl } from "#execution/session/timeout-control.js";-import {- type CompactionHandoff,- SessionHandoff,- sessionAnchorToken,-} from "#execution/session/handoff.js";+import { SessionHandoff, sessionAnchorToken } from "#execution/session/handoff.js";import { signalSessionAnchorStep } from "#execution/session/handoff-steps.js";import type { WorkflowEntryResult } from "#execution/session/entry-input.js";@@ -72,7 +68,6 @@ export interface SessionBoot {readonly sessionId: string;readonly sessionState: DurableSessionState;readonly sessionTimeoutControl?: SessionTimeoutControl;- readonly sessionTimeoutDeadline?: Date;readonly sessionTimeoutMs: number | false;readonly sessionWritable: WritableStream<Uint8Array>;}@@ -247,6 +242,11 @@ async function runSessionLoop(await cancelWorkingTasks(cursor, "turn_cancelled");continue;}+ if (next.kind === "expired" && sessionTimeout !== undefined) {+ // Input accepted behind the timer's signal would be lost if the session ended now.+ if (queue.pendingCount > 0 || inbox.hasPending()) sessionTimeout.recordActivity();+ if ((await sessionTimeout.handleTimerElapsed()) === "extended") continue;+ }return next;}};@@ -263,6 +263,7 @@ async function runSessionLoop(turnControl = undefined;progress.turnId = `turn_${String(turnIndex++)}`;const outcome = await execution.runTurn(payload, { caller, control });+ sessionTimeout?.recordActivity();if (outcome.caller !== undefined) progress.caller = outcome.caller;if (outcome.compacted === true) compactionHandoffDue = true;return outcome;@@ -273,12 +274,10 @@ async function runSessionLoop(serializedContext: cursor.serializedContext,sessionState: cursor.sessionState,});- const dueCompactionHandoff = (): CompactionHandoff | undefined =>+ const compactionHandoffReady = (): boolean =>compactionHandoffDue &&progress.caller === undefined &&- workingTasks(sessionTaskTable(cursor)).length === 0- ? { sessionTimeoutDeadline: boot.sessionTimeoutDeadline }- : undefined;+ workingTasks(sessionTaskTable(cursor)).length === 0;/*** Hands a session that compacted to a fresh run on this deployment while* nothing is waiting. Input that is already waiting runs here first, and@@ -286,9 +285,8 @@ async function runSessionLoop(* move has started runs on the successor.*/const tryCompactionHandoff = async (): Promise<SessionLoopOutcome | undefined> => {- const compaction = dueCompactionHandoff();- if (compaction === undefined || queue.pendingCount > 0 || inbox.hasPending()) return undefined;- const transfer = await handoff.tryCompactionTransfer(transferState(), compaction);+ if (!compactionHandoffReady() || queue.pendingCount > 0 || inbox.hasPending()) return undefined;+ const transfer = await handoff.tryCompactionTransfer(transferState());return transfer.kind === "transferred" ? transfer : undefined;};const runDeliveredTurn = async (@@ -398,6 +396,7 @@ async function runSessionLoop(case "cancel-turn":await execution.cancelTurnWork();await settleCancelledTurn(false);+ sessionTimeout?.recordActivity();// Cancellation consumes any outstanding caller; do not report the prior turn.action = { ...action, settled: undefined };continue;diff --git a/packages/eve/src/execution/session/timeout-control.test.ts b/packages/eve/src/execution/session/timeout-control.test.tsindex 1eda7d219..87b6030de 100644--- a/packages/eve/src/execution/session/timeout-control.test.ts+++ b/packages/eve/src/execution/session/timeout-control.test.ts@@ -1,6 +1,9 @@-import { afterEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { createSessionTimeoutControl } from "#execution/session/timeout-control.js";+import {+ createSessionTimeoutControl,+ type SessionTimeoutControl,+} from "#execution/session/timeout-control.js";import {cancelSessionTimeoutStep,startSessionTimeoutStep,@@ -15,30 +18,73 @@ vi.mock("#compiled/@workflow/core/index.js", () => ({getWorkflowMetadata: () => ({ workflowRunId: "owner-1" }),}));+const BOOT = new Date("2026-02-01T00:00:00.000Z");+const TIMEOUT_MS = 60_000;++function createControl(): SessionTimeoutControl {+ const control = createSessionTimeoutControl({ sessionId: "wrun_1", timeoutMs: TIMEOUT_MS });+ if (control === undefined) throw new Error("expected a timeout control");+ return control;+}++beforeEach(() => {+ vi.useFakeTimers({ toFake: ["Date"] });+ vi.setSystemTime(BOOT);+});+afterEach(() => {+ vi.useRealTimers();vi.clearAllMocks();});describe("createSessionTimeoutControl", () => {- it("starts one absolute deadline against the stable command inbox", async () => {- const deadline = new Date("2026-02-01T00:00:00.000Z");+ it("arms one timer for the idle window against the stable command inbox", async () => {vi.mocked(startSessionTimeoutStep).mockResolvedValue({ runId: "timer-run" });- const control = createSessionTimeoutControl({- deadline,- sessionId: "wrun_1",- });+ const control = createControl();await control.start();await control.start();expect(startSessionTimeoutStep).toHaveBeenCalledOnce();expect(startSessionTimeoutStep).toHaveBeenCalledWith({- deadline,+ deadline: new Date(BOOT.getTime() + TIMEOUT_MS),ownerRunId: "owner-1",token: "eve:session:wrun_1:inbox",});});+ it("extends the deadline from the latest activity instead of expiring", async () => {+ vi.mocked(startSessionTimeoutStep)+ .mockResolvedValueOnce({ runId: "timer-1" })+ .mockResolvedValueOnce({ runId: "timer-2" });+ const control = createControl();+ await control.start();++ vi.setSystemTime(BOOT.getTime() + 40_000);+ control.recordActivity();+ vi.setSystemTime(BOOT.getTime() + TIMEOUT_MS);++ await expect(control.handleTimerElapsed()).resolves.toBe("extended");+ expect(startSessionTimeoutStep).toHaveBeenLastCalledWith(+ expect.objectContaining({ deadline: new Date(BOOT.getTime() + 40_000 + TIMEOUT_MS) }),+ );+ // The elapsed timer already ended; only its replacement is cancelled.+ await control.dispose();+ expect(cancelSessionTimeoutStep).toHaveBeenCalledOnce();+ expect(cancelSessionTimeoutStep).toHaveBeenCalledWith({ runId: "timer-2" });+ });++ it("expires once the session has been idle for the whole window", async () => {+ vi.mocked(startSessionTimeoutStep).mockResolvedValue({ runId: "timer-run" });+ const control = createControl();+ await control.start();++ vi.setSystemTime(BOOT.getTime() + TIMEOUT_MS);++ await expect(control.handleTimerElapsed()).resolves.toBe("expired");+ expect(startSessionTimeoutStep).toHaveBeenCalledOnce();+ });+it("shares in-progress startup across concurrent start calls", async () => {let resolveStartup!: (value: { runId: string }) => void;vi.mocked(startSessionTimeoutStep).mockReturnValue(@@ -46,10 +92,7 @@ describe("createSessionTimeoutControl", () => {resolveStartup = resolve;}),);- const control = createSessionTimeoutControl({- deadline: new Date("2026-02-01T00:00:00.000Z"),- sessionId: "wrun_1",- });+ const control = createControl();const first = control.start();const second = control.start();@@ -67,10 +110,7 @@ describe("createSessionTimeoutControl", () => {resolveStartup = resolve;}),);- const control = createSessionTimeoutControl({- deadline: new Date("2026-02-01T00:00:00.000Z"),- sessionId: "wrun_1",- });+ const control = createControl();const startup = control.start();const disposal = control.dispose();@@ -83,10 +123,7 @@ describe("createSessionTimeoutControl", () => {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"),- sessionId: "wrun_1",- });+ const control = createControl();await control.start();await control.dispose();@@ -100,10 +137,7 @@ describe("createSessionTimeoutControl", () => {const failure = new Error("timer startup failed");vi.mocked(startSessionTimeoutStep).mockRejectedValue(failure);- const control = createSessionTimeoutControl({- deadline: new Date("2026-02-01T00:00:00.000Z"),- sessionId: "wrun_1",- });+ const control = createControl();await expect(control.start()).rejects.toBe(failure);await expect(control.start()).rejects.toBe(failure);diff --git a/packages/eve/src/execution/session/timeout-control.ts b/packages/eve/src/execution/session/timeout-control.tsindex 734d88012..75d6c7cfb 100644--- a/packages/eve/src/execution/session/timeout-control.ts+++ b/packages/eve/src/execution/session/timeout-control.ts@@ -6,20 +6,51 @@ import {} from "#execution/session/timeout-steps.js";import { sessionCommandHookToken } from "#execution/session-inbox/address.js";-/** Workflow-body handle that targets a durable deadline at the stable command inbox. */+/**+ * Workflow-body handle for one owner's idle timeout. Activity moves the+ * deadline only in memory; when the durable timer fires before the session+ * has been idle for the whole window, the owner re-arms it for the new+ * deadline. An active session therefore costs one timer per window, not one+ * per turn.+ */export interface SessionTimeoutControl {dispose(): Promise<void>;+ /**+ * Answers this owner's elapsed timer: `expired` once the session has been+ * idle for the whole window, otherwise `extended` after arming a timer for+ * the deadline that the latest activity set.+ */+ handleTimerElapsed(): Promise<"expired" | "extended">;+ /** Restarts the idle window from now. */+ recordActivity(): void;start(): Promise<void>;}-/** Creates a timer controller for one stable session command inbox. */+/** Creates the idle timeout for one owner run, or `undefined` when timeouts are disabled. */export function createSessionTimeoutControl(input: {- readonly deadline: Date;readonly sessionId: string;-}): SessionTimeoutControl {+ readonly timeoutMs: number | false;+}): SessionTimeoutControl | undefined {+ const { sessionId, timeoutMs } = input;+ if (timeoutMs === false) return undefined;+ // Workflow's clock is replay-stable. An owner boots right after activity:+ // the session's creation, the delivery a successor runs, or the turn that+ // compacted before a successor took over.+ let lastActivityAt = Date.now();let active: { readonly runId: string } | undefined;let startup: Promise<void> | undefined;+ const arm = async (): Promise<void> => {+ startup ??= (async () => {+ active = await startSessionTimeoutStep({+ deadline: new Date(lastActivityAt + timeoutMs),+ ownerRunId: getWorkflowMetadata().workflowRunId,+ token: sessionCommandHookToken(sessionId),+ });+ })();+ await startup;+ };+return {async dispose(): Promise<void> {try {@@ -33,15 +64,19 @@ export function createSessionTimeoutControl(input: {await cancelSessionTimeoutStep({ runId: current.runId });},- async start(): Promise<void> {- startup ??= (async () => {- active = await startSessionTimeoutStep({- deadline: input.deadline,- ownerRunId: getWorkflowMetadata().workflowRunId,- token: sessionCommandHookToken(input.sessionId),- });- })();- await startup;+ async handleTimerElapsed(): Promise<"expired" | "extended"> {+ if (Date.now() >= lastActivityAt + timeoutMs) return "expired";+ // The timer that fired has already ended, so there is nothing to cancel.+ active = undefined;+ startup = undefined;+ await arm();+ return "extended";+ },++ recordActivity(): void {+ lastActivityAt = Date.now();},++ start: arm,};}diff --git a/packages/eve/src/execution/session/timeout.ts b/packages/eve/src/execution/session/timeout.tsindex f16d06f13..f98db90f4 100644--- a/packages/eve/src/execution/session/timeout.ts+++ b/packages/eve/src/execution/session/timeout.ts@@ -1,9 +1,2 @@-/** Default lifetime from creation or the latest successful ownership handoff. */+/** Default time a session may sit idle before it completes. */export const DEFAULT_SESSION_TIMEOUT_MS = 30 * 24 * 60 * 60 * 1_000;--export function sessionTimeoutDeadline(- timeoutMs: number | false,- startedAtMs: number,-): Date | undefined {- return timeoutMs === false ? undefined : new Date(startedAtMs + timeoutMs);-}diff --git a/packages/eve/src/shared/agent-definition.ts b/packages/eve/src/shared/agent-definition.tsindex f1abfab8c..15793dd79 100644--- a/packages/eve/src/shared/agent-definition.ts+++ b/packages/eve/src/shared/agent-definition.ts@@ -172,12 +172,11 @@ export interface PublicAgentCompactionDefinition {*/export interface AgentLimitsDefinition {/**- * Session lifetime from creation or the latest ownership handoff, in milliseconds.+ * How long a session may sit idle before eve completes it, in milliseconds.*- * A successful deployment handoff or legacy-session import restarts the- * original configured duration. Process restarts and failed or skipped- * handoffs preserve the deadline. If it elapses during an active turn, eve lets- * that turn settle before completing the session normally.+ * The idle window starts at creation and restarts each time a turn settles.+ * A session never expires while a turn is open, including a turn held open+ * for working tasks or human input.** `false` disables the timeout.*diff --git a/research/atomic-session-handoff.md b/research/atomic-session-handoff.mdindex 690ba062c..ee158654a 100644--- a/research/atomic-session-handoff.md+++ b/research/atomic-session-handoff.md@@ -1,7 +1,7 @@---issue: TBDstatus: in-progress-last_updated: "2026-10-19"+last_updated: "2026-10-20"---# Atomic session handoff@@ -234,8 +234,9 @@ and B, watching A, stops waiting and exits without writing to the stream.it cannot deadlock on B; if A ends first, the counterpart watch opens the gate with nothingrestored. Once no hookremains the gate can never open, so it is ignored and leftovers stay drainable.-5. **Session timeout.** Unchanged: a deployment handoff renews the deadline, a compaction handoff- keeps it, and the timer starts concurrently with the first turn.+5. **Session timeout.** The timeout is idle-based: B starts its idle window at boot, right after+ the delivery or compacting turn that moved the session, and arms its timer concurrently with+ the first turn.`handover` is a runtime-only inbox payload, like `session-failure`. A sends it through the stablesession address, so the SDK's redirect delivers it to B. Channel request bodies cannot constructdiff --git a/research/eve-tasks.md b/research/eve-tasks.mdindex 3bb11bc48..a8255fb32 100644--- a/research/eve-tasks.md+++ b/research/eve-tasks.md@@ -1,7 +1,7 @@---issue: https://github.com/vercel/eve/issues/1084status: draft-last_updated: "2026-10-01"+last_updated: "2026-10-20"---# eve tasks@@ -475,9 +475,9 @@ turn can continue an idle task by `taskId` with its own caller's auth. Anonymousprincipal. Queued messages from one principal share a turn even when their claims differ, and theturn runs with the latest claims.-**No task time limits.** `defineAgent`'s `limits.sessionTimeoutMs` keeps its meaning, the-session lifetime (default 30 days), and bounds all work in the session; with `false`, tasks are-unbounded. A body that needs a limit races `sleep` against its work. A person who wants an update asks, and the model decides whether to keep+**No task time limits.** `defineAgent`'s `limits.sessionTimeoutMs` is an idle timeout (default 30+days) and does not bound tasks: a turn held open while its tasks work keeps the session open, and+the window counts from when that turn settles. A body that needs a limit races `sleep` against its work. A person who wants an update asks, and the model decides whether to keepwaiting or cancel.**Cap.** At most 32 working tasks per session (`TOO_MANY_TASKS`), a worst-case backstop normal use