The Open Framework for Building Agents
[eve] Add experimental.workflow.retention (#3236)
Peter Wielander09df32cab308
diff --git a/.changeset/plain-mice-retention.md b/.changeset/plain-mice-retention.mdnew file mode 100644index 000000000..0347ac697--- /dev/null+++ b/.changeset/plain-mice-retention.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Adds `experimental.workflow.retention` to `defineAgent`, which forwards a run's data-retention preference to the durable runtime. Set it to `0` to have a run's payloads, streams, and event log deleted as soon as the run finishes instead of kept for the world's default period.diff --git a/docs/agent-config.md b/docs/agent-config.mdindex 48e88a1a0..841748617 100644--- a/docs/agent-config.md+++ b/docs/agent-config.md@@ -283,18 +283,52 @@ disappear in any release. See [Execution model anddurability](./concepts/execution-model-and-durability#resuming-after-a-crash)for the retry behavior.+## Run data retention++The runtime keeps each run's data after the run finishes: model and tool+payloads, streamed output, and the event log eve replays from. How long it keeps+them is the World's decision, and on Vercel that follows your team's plan. Set+`experimental.workflow.retention` to `0` to have it deleted as soon as the run+finishes instead:++```ts title="agent/agent.ts"+import { defineAgent } from "eve";++export default defineAgent({+ model: "anthropic/claude-opus-4.8",+ experimental: {+ workflow: {+ retention: 0,+ },+ },+});+```++This will be applied to the session run and every turn run the session+dispatches, as well as the run that collects session activity. Runs eve+starts for other purposes keep the world's default: session timeouts,+background tasks, and [workflow tools](./tools/workflows).++The value applies per agent. A [subagent](./subagents) that runs its own session+uses its own value, unlike `experimental.workflow.world`, which is root-only.++Custom Worlds used with eve might not support this feature, in which case+it falls back to the World's default retention period.++> ⚠️ **At `0`, a finished session's output is usually gone before you can read it.** Since data is deleted immediately before it can be read back, results and transcripts become unreadable and a client polling for a finished session's output can see it disappear.+## Other defineAgent fields`defineAgent` takes a few more fields, all optional. For the exported types, see the [TypeScript API Reference](./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. Sessions complete after 30 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. |-| `outputSchema` | Standard Schema or a JSON Schema object | none | Structured return type for function-like invocations such as a subagent turn, schedule, or remote job. Ordinary interactive 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; 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. |+| `outputSchema` | Standard Schema or a JSON Schema object | none | Structured return type for function-like invocations such as a subagent turn, schedule, or remote job. Ordinary interactive 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/reference/typescript-api.md b/docs/reference/typescript-api.mdindex 67345c775..37a871582 100644--- a/docs/reference/typescript-api.md+++ b/docs/reference/typescript-api.md@@ -57,7 +57,7 @@ export default defineTool({Tool-wide authoring helpers and types such as `defineTool`, `defineWorkflowTool`, `defineDurableCallback`, `defineDynamic`, `disableTool`, and `ToolLabelDefinition` come from `eve/tools`. Capability-specific definitions and helpers use their own subpaths (see [Built-in tools](../concepts/built-in-tools)): reusable definitions such as `bash` and `glob` come from `eve/tools/<name>`, `webSearch` comes from `eve/tools/web_search`, `experimental_workflow` comes from `eve/tools/workflow`, `sleep` comes from `eve/tools/sleep`, and approval policies and types come from `eve/tools/approval`. The route verbs `GET`/`HEAD`/`POST`/`PUT`/`PATCH`/`DELETE`/`OPTIONS`/`WS` plus `disableRoute` come from `eve/channels`, and the channel auth helpers `localDev`/`vercelOidc`/`placeholderAuth` come from `eve/channels/auth`.-`AgentReasoningDefinition` is exported from `eve` for the top-level `defineAgent({ reasoning })` setting. `AgentLimitsDefinition` is exported for `defineAgent({ limits })`. `AgentWorkflowDefinition` and `AgentWorkflowWorldDefinition` are exported from `eve` for the `defineAgent({ experimental: { workflow } })` config shape. `ExperimentalWorkflowToolInput` is exported from `eve/tools/workflow`; `WebSearchToolInput` and `WebSearchProvider` are exported from `eve/tools/web_search`.+`AgentReasoningDefinition` is exported from `eve` for the top-level `defineAgent({ reasoning })` setting. `AgentLimitsDefinition` is exported for `defineAgent({ limits })`. `AgentWorkflowDefinition`, `AgentWorkflowRetentionDefinition`, and `AgentWorkflowWorldDefinition` are exported from `eve` for the `defineAgent({ experimental: { workflow } })` config shape. `ExperimentalWorkflowToolInput` is exported from `eve/tools/workflow`; `WebSearchToolInput` and `WebSearchProvider` are exported from `eve/tools/web_search`.`defineInstructions` accepts `{ content: string, role?: "system" | "user" }`; omitted `role` means `"system"`. Its `eve/instructions` version of `defineDynamic` accepts only `session.started` and `turn.started` handlers returning `defineInstructions(...)` or `null`. The legacy `{ markdown: string }` definition remains available as a deprecated system-role form.diff --git a/packages/eve/extension-contracts/compatibility/subagent/v11.ts b/packages/eve/extension-contracts/compatibility/subagent/v11.tsnew file mode 100644index 000000000..009ea6733--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/subagent/v11.ts@@ -0,0 +1,16 @@+import { defineAgent } from "#public/index.js";++/**+ * Epoch 11 predates `experimental.workflow.retention`, so a subagent authored+ * against it never sets the field. It must keep compiling now that the field+ * exists.+ */+export default defineAgent({+ description: "Delegate research tasks.",+ experimental: {+ workflow: {+ modelCallsPerStep: 4,+ },+ },+ model: "anthropic/claude-sonnet-5",+});diff --git a/packages/eve/extension-contracts/reports/subagent/v12.json b/packages/eve/extension-contracts/reports/subagent/v12.jsonnew file mode 100644index 000000000..b06ff181e--- /dev/null+++ b/packages/eve/extension-contracts/reports/subagent/v12.json@@ -0,0 +1,20 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "subagent",+ "epoch": 12,+ "sha256": "7f07d10be3fec39a593493d3e36fe5431ea822d8cc992b27c9610508478fe36d",+ "exports": [+ "AgentCompactionDefinition",+ "AgentDefinition",+ "AgentModelDefinition",+ "AgentStaticModelDefinition",+ "DefinedAgent",+ "DynamicLocalSubagentDefinition",+ "DynamicSubagentDefinition",+ "RemoteAgentDefinition",+ "RemoteAgentDefinitionInput",+ "defineAgent",+ "defineDynamic",+ "defineRemoteAgent"+ ]+}diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.tsindex 4d7b937cc..e5be98a34 100644--- a/packages/eve/src/compiler/extension-compatibility.ts+++ b/packages/eve/src/compiler/extension-compatibility.ts@@ -71,8 +71,8 @@ const EXTENSION_CAPABILITY_CONTRACTS = {},},subagent: {- current: 11,- supported: [3, 4, 6, 7, 8, 9, 10, 11],+ current: 12,+ supported: [3, 4, 6, 7, 8, 9, 10, 11, 12],dropped: {1: "Persistent subagent sessions are now the default and the experimental opt-in was removed",2: "Persistent subagent sessions are now the default and the experimental opt-in was removed",diff --git a/packages/eve/src/compiler/manifest.test.ts b/packages/eve/src/compiler/manifest.test.tsindex e4477528a..eee553ef2 100644--- a/packages/eve/src/compiler/manifest.test.ts+++ b/packages/eve/src/compiler/manifest.test.ts@@ -15,7 +15,7 @@ describe("compiled agent manifest v48", () => {it("round-trips a real compiled graph through the serialized schema", async () => {const { manifest } = await compileFromMemory({agent: {- experimental: { workflow: { modelCallsPerStep: 4 } },+ experimental: { workflow: { modelCallsPerStep: 4, retention: 0 } },limits: { maxTokenCostUsdPerSession: 1.5 },model: "openai/gpt-5.4",},@@ -26,6 +26,8 @@ describe("compiled agent manifest v48", () => {const parsed = compiledAgentManifestSchema.parse(JSON.parse(JSON.stringify(manifest)));expect(parsed.version).toBe(COMPILED_AGENT_MANIFEST_VERSION);expect(parsed.config.experimental?.workflow?.modelCallsPerStep).toBe(4);+ // `0` is falsy: a truthiness-based copy anywhere on the manifest path drops it.+ expect(parsed.config.experimental?.workflow?.retention).toBe(0);expect(parsed.config.limits?.maxTokenCostUsdPerSession).toBe(1.5);expect(() => validateCompiledAgentManifest(parsed)).not.toThrow();});diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.tsindex 39467ceb5..4d1564d7f 100644--- a/packages/eve/src/compiler/manifest.ts+++ b/packages/eve/src/compiler/manifest.ts@@ -20,12 +20,13 @@ import type {SkillPackageSourceRef,} from "#shared/source-ref.js";import type { NamedSkillDefinition } from "#shared/skill-definition.js";-import type {- InternalAgentDefinition,- InternalAgentModelDefinition,- InternalAgentCompactionDefinition,- AgentBuildDefinition,- ModelRouting,+import {+ AGENT_WORKFLOW_RETENTION_VALUES,+ type InternalAgentDefinition,+ type InternalAgentModelDefinition,+ type InternalAgentCompactionDefinition,+ type AgentBuildDefinition,+ type ModelRouting,} from "#shared/agent-definition.js";import type { InternalToolDefinition } from "#tools/definition.js";import type { CompiledToolBehavior } from "#tools/behavior.js";@@ -570,6 +571,7 @@ const compiledAgentWorkflowWorldDefinitionSchema = z.string();const compiledAgentWorkflowDefinitionSchema = z.object({modelCallsPerStep: z.number().int().positive().optional(),+ retention: z.literal(AGENT_WORKFLOW_RETENTION_VALUES).optional(),world: compiledAgentWorkflowWorldDefinitionSchema.optional(),}).strict();@@ -1216,6 +1218,7 @@ function cloneCompiledAgentDefinition(config: CompiledAgentDefinition): Compiled? undefined: {modelCallsPerStep: config.experimental.workflow.modelCallsPerStep,+ retention: config.experimental.workflow.retention,world: config.experimental.workflow.world,},},diff --git a/packages/eve/src/compiler/normalize-agent-config.ts b/packages/eve/src/compiler/normalize-agent-config.tsindex 145fbdd50..19a83b4b7 100644--- a/packages/eve/src/compiler/normalize-agent-config.ts+++ b/packages/eve/src/compiler/normalize-agent-config.ts@@ -189,6 +189,7 @@ function normalizeExperimentalDefinition(if (experimental.workflow !== undefined) {compiledExperimental.workflow = {modelCallsPerStep: experimental.workflow.modelCallsPerStep,+ retention: experimental.workflow.retention,world: experimental.workflow.world,};}diff --git a/packages/eve/src/execution/dispatch-turn-step.ts b/packages/eve/src/execution/dispatch-turn-step.tsindex 2f0ed8a8c..d970a5207 100644--- a/packages/eve/src/execution/dispatch-turn-step.ts+++ b/packages/eve/src/execution/dispatch-turn-step.ts@@ -22,6 +22,7 @@ export async function dispatchTurnStep(readAcceptedDeploymentId(input.delivery),{allowReservedAttributes: true,+ experimental_retention: input.retention,attributes: normalizeEveAttributes(buildTurnAttributes({parentSessionId: input.sessionState.sessionId,diff --git a/packages/eve/src/execution/durable-session-migrations/turn-workflow.ts b/packages/eve/src/execution/durable-session-migrations/turn-workflow.tsindex a50238d77..d9b41bce8 100644--- a/packages/eve/src/execution/durable-session-migrations/turn-workflow.ts+++ b/packages/eve/src/execution/durable-session-migrations/turn-workflow.ts@@ -17,6 +17,7 @@ import type {} from "#channel/types.js";import type { DurableSessionState } from "#execution/durable-session-store.js";import type { RuntimeActionResult } from "#shared/action-types.js";+import type { AgentWorkflowRetentionDefinition } from "#shared/agent-definition.js";import type { RunMode } from "#shared/run-mode.js";import type { DurableStepResult } from "#execution/next-driver-action.js";import type { TurnCancelPayload } from "#execution/turn-cancellation-token.js";@@ -95,6 +96,12 @@ export interface TurnWorkflowDispatchInput {readonly initialStep?: InitialTurnStep;readonly initialCancellation?: TurnCancelPayload;readonly parentWritable: WritableStream<Uint8Array>;+ /**+ * Dispatch-only. `dispatchTurnStep` passes it to `start()`; the turn body+ * never reads it, so it is deliberately absent from {@link TurnWorkflowInput}+ * and does not participate in the versioned wire shape.+ */+ readonly retention?: AgentWorkflowRetentionDefinition;readonly serializedContext: Record<string, unknown>;readonly sessionState: DurableSessionState;}diff --git a/packages/eve/src/execution/turn-dispatch.ts b/packages/eve/src/execution/turn-dispatch.tsindex e757e56f1..e517882a6 100644--- a/packages/eve/src/execution/turn-dispatch.ts+++ b/packages/eve/src/execution/turn-dispatch.ts@@ -12,6 +12,7 @@ import type { SessionCommandInbox } from "#execution/session-command-inbox.js";import { SessionStateCursor } from "#execution/session-state-cursor.js";import type { TurnCancelPayload } from "#execution/turn-cancellation-token.js";import type { TurnDriverAction } from "#execution/turn-control-receiver.js";+import type { AgentWorkflowRetentionDefinition } from "#shared/agent-definition.js";import type { RunMode } from "#shared/run-mode.js";import { activeTurnId } from "#harness/active-turn-id.js";import { runTurnOwnedWorkflow } from "#execution/turn-workflow.js";@@ -41,6 +42,7 @@ interface TurnDispatchInput {readonly commandInbox: SessionCommandInbox;readonly mode: RunMode;readonly parentWritable: WritableStream<Uint8Array>;+ readonly retention?: AgentWorkflowRetentionDefinition;readonly serializedContext: Record<string, unknown>;readonly seenTaskDeliveries?: Set<string>;readonly sessionState: DurableSessionState;@@ -94,6 +96,7 @@ async function runAndAwaitTurn(initialStep: input.initialStep,mode: input.mode,parentWritable: input.parentWritable,+ retention: input.retention,serializedContext: input.serializedContext,sessionState: input.sessionState,} satisfies TurnWorkflowDispatchInput;diff --git a/packages/eve/src/execution/workflow-entry-crash.ts b/packages/eve/src/execution/workflow-entry-crash.tsnew file mode 100644index 000000000..03106d193--- /dev/null+++ b/packages/eve/src/execution/workflow-entry-crash.ts@@ -0,0 +1,90 @@+import type { TurnCaller } from "#channel/types.js";+import type { DurableSessionState } from "#execution/durable-session-store.js";+import { resolveInitialTurnCallerStep } from "#subagents/parent-notification.js";++const SAFE_OUTER_WORKFLOW_FAILURE_MESSAGE =+ "Agent workflow failed. Inspect the private session trace for details.";++/**+ * Write-through cell owned by `workflowEntry`: written+ * unconditionally by the driver loop as turns advance, read only by the+ * outer catch. When the loop throws, its locals are unreachable, so this+ * cell is the crash path's only view of values that changed after turn 1.+ *+ * Reach for this cell only when all three hold for a value:+ * 1. it is produced or replaced inside the driver loop, so the entry+ * function's own locals go stale;+ * 2. it travels by value inside Workflow step results — there is no+ * store the catch could re-read it from at crash time;+ * 3. the crash path needs its latest value to discharge a cleanup+ * obligation.+ * If any of the three fails, read the value from where it already lives+ * instead of mirroring it here.+ */+export interface CrashCleanupState {+ // The caller whose awaited reply is still unsettled, so the catch can+ // reject it with the error instead of leaving it parked forever.+ // Populated for every session; only conversation-mode paths read it.+ caller: TurnCaller | undefined;+ // Whether `resolveInitialTurnCallerStep` has run. `caller: undefined` is+ // ambiguous on its own: it also means "resolved and later cleared because+ // its reply settled". This flag lets the crash path tell that apart from+ // "crashed before the caller was ever resolved", where a delegated caller+ // may still be parked on this session's reply.+ callerResolved: boolean;+ // The latest snapshot the driver has received, so the catch can+ // terminate children adopted after turn 1. Honest staleness window: the+ // driver only sees state at turn boundaries, so children dispatched by a+ // turn that crashed mid-flight are absent from this snapshot and escape+ // crash cleanup.+ lastSessionState: DurableSessionState | undefined;+ // The latest context adopted from a completed turn, which carries provider+ // and trace state needed by terminal instrumentation.+ serializedContext: Record<string, unknown>;+ // Whether the session already emitted a terminal protocol and instrumentation+ // event (set here on the crash path, or by the finalization steps via+ // `terminalState`), so later callback or teardown failures cannot contradict it.+ terminalEmitted: boolean;+ // The most recently dispatched turn, derived from the dispatch index so the+ // durable workflow body does not import the harness. Never cleared on settle:+ // a crash between turns is attributed to the last dispatched turn.+ turnId?: string;+}++export function hasDelegatedCallerContext(serializedContext: Record<string, unknown>): boolean {+ if (serializedContext["eve.sessionCallback"] !== undefined) return true;+ const channel = serializedContext["eve.channel"];+ return (+ typeof channel === "object" && channel !== null && Reflect.get(channel, "kind") === "subagent"+ );+}++/**+ * Caller to reject from the crash path. Normally the resolved cell value —+ * including `undefined` after a settled reply cleared it, when there is+ * nothing left to notify. When the crash happened before+ * `resolveInitialTurnCallerStep` ever ran (e.g. `createSessionStep` threw),+ * the cell is empty even though a delegated caller may be parked on this+ * session's reply, so the caller is re-resolved from the serialized context+ * — which needs nothing from the failed steps. Best-effort: when resolution+ * fails again there is no reachable caller to notify.+ */+export async function resolveCallerForCrash(+ state: CrashCleanupState,+ serializedContext: Record<string, unknown>,+): Promise<TurnCaller | undefined> {+ if (state.callerResolved) {+ return state.caller;+ }+ try {+ return await resolveInitialTurnCallerStep({ serializedContext });+ } catch {+ return undefined;+ }+}++export function createSafeOuterWorkflowError(): Error {+ const error = new Error(SAFE_OUTER_WORKFLOW_FAILURE_MESSAGE);+ error.name = "EveWorkflowFailure";+ return error;+}diff --git a/packages/eve/src/execution/workflow-entry.ts b/packages/eve/src/execution/workflow-entry.tsindex d3cfb0bd3..ee769869c 100644--- a/packages/eve/src/execution/workflow-entry.ts+++ b/packages/eve/src/execution/workflow-entry.ts@@ -7,9 +7,15 @@ import type {RunInput,SessionCommand,SessionCapabilities,- TurnCaller,} from "#channel/types.js";import { readChannelRequestId, readRootSessionId } from "#execution/eve-workflow-attributes.js";+import {+ createSafeOuterWorkflowError,+ type CrashCleanupState,+ hasDelegatedCallerContext,+ resolveCallerForCrash,+} from "#execution/workflow-entry-crash.js";+import type { AgentWorkflowRetentionDefinition } from "#shared/agent-definition.js";import type { RunMode } from "#shared/run-mode.js";import type { DurableCompiledArtifactsSource } from "#runtime/durable-compiled-artifacts-source.js";import {@@ -50,9 +56,6 @@ import {SESSION_INBOX_WIRE_VERSION,} from "#execution/wire/session-inbox-contract.js";-const SAFE_OUTER_WORKFLOW_FAILURE_MESSAGE =- "Agent workflow failed. Inspect the private session trace for details.";-// workflow-entry.ts is the durable workflow body — the bundler rejects// node built-ins here, so `internal/logging.ts` cannot be imported.// Error logging happens inside `emitTerminalSessionFailureStep`.@@ -67,6 +70,7 @@ export interface WorkflowEntryInput {readonly continuationConflictCommand?: Extract<SessionCommand, { readonly kind: "send" }>;readonly input: RunInput["input"];readonly limits?: RunInput["limits"];+ readonly retention?: AgentWorkflowRetentionDefinition;readonly sessionTimeoutMs?: number | false;readonly serializedContext: Record<string, unknown>;readonly taskId?: string;@@ -87,52 +91,6 @@ type DriverLoopOutcome =readonly result: WorkflowEntryResult;};-/**- * Write-through cell owned by {@link workflowEntry}: written- * unconditionally by the driver loop as turns advance, read only by the- * outer catch. When the loop throws, its locals are unreachable, so this- * cell is the crash path's only view of values that changed after turn 1.- *- * Reach for this cell only when all three hold for a value:- * 1. it is produced or replaced inside the driver loop, so the entry- * function's own locals go stale;- * 2. it travels by value inside Workflow step results — there is no- * store the catch could re-read it from at crash time;- * 3. the crash path needs its latest value to discharge a cleanup- * obligation.- * If any of the three fails, read the value from where it already lives- * instead of mirroring it here.- */-interface CrashCleanupState {- // The caller whose awaited reply is still unsettled, so the catch can- // reject it with the error instead of leaving it parked forever.- // Populated for every session; only conversation-mode paths read it.- caller: TurnCaller | undefined;- // Whether `resolveInitialTurnCallerStep` has run. `caller: undefined` is- // ambiguous on its own: it also means "resolved and later cleared because- // its reply settled". This flag lets the crash path tell that apart from- // "crashed before the caller was ever resolved", where a delegated caller- // may still be parked on this session's reply.- callerResolved: boolean;- // The latest snapshot the driver has received, so the catch can- // terminate children adopted after turn 1. Honest staleness window: the- // driver only sees state at turn boundaries, so children dispatched by a- // turn that crashed mid-flight are absent from this snapshot and escape- // crash cleanup.- lastSessionState: DurableSessionState | undefined;- // The latest context adopted from a completed turn, which carries provider- // and trace state needed by terminal instrumentation.- serializedContext: Record<string, unknown>;- // Whether the session already emitted a terminal protocol and instrumentation- // event (set here on the crash path, or by the finalization steps via- // `terminalState`), so later callback or teardown failures cannot contradict it.- terminalEmitted: boolean;- // The most recently dispatched turn, derived from the dispatch index so the- // durable workflow body does not import the harness. Never cleared on settle:- // a crash between turns is attributed to the last dispatched turn.- turnId?: string;-}-/*** Long-lived workflow entrypoint. Handles both root sessions and* delegated child sessions: root sessions expose only parent@@ -277,6 +235,7 @@ export async function workflowEntry(input: WorkflowEntryInput): Promise<Workflow},crashCleanupState,mode,+ retention: input.retention,serializedContext: input.serializedContext,sessionState,sessionTimeoutDeadline:@@ -345,45 +304,6 @@ export async function workflowEntry(input: WorkflowEntryInput): Promise<Workflowthrow createSafeOuterWorkflowError();}}--function hasDelegatedCallerContext(serializedContext: Record<string, unknown>): boolean {- if (serializedContext["eve.sessionCallback"] !== undefined) return true;- const channel = serializedContext["eve.channel"];- return (- typeof channel === "object" && channel !== null && Reflect.get(channel, "kind") === "subagent"- );-}--/**- * Caller to reject from the crash path. Normally the resolved cell value —- * including `undefined` after a settled reply cleared it, when there is- * nothing left to notify. When the crash happened before- * `resolveInitialTurnCallerStep` ever ran (e.g. `createSessionStep` threw),- * the cell is empty even though a delegated caller may be parked on this- * session's reply, so the caller is re-resolved from the serialized context- * — which needs nothing from the failed steps. Best-effort: when resolution- * fails again there is no reachable caller to notify.- */-async function resolveCallerForCrash(- state: CrashCleanupState,- serializedContext: Record<string, unknown>,-): Promise<TurnCaller | undefined> {- if (state.callerResolved) {- return state.caller;- }- try {- return await resolveInitialTurnCallerStep({ serializedContext });- } catch {- return undefined;- }-}--function createSafeOuterWorkflowError(): Error {- const error = new Error(SAFE_OUTER_WORKFLOW_FAILURE_MESSAGE);- error.name = "EveWorkflowFailure";- return error;-}-async function runDriverLoop(input: {readonly capabilities?: SessionCapabilities;readonly commandInbox: SessionCommandInbox;@@ -391,6 +311,7 @@ async function runDriverLoop(input: {readonly initialInput: HookPayload;readonly crashCleanupState: CrashCleanupState;readonly mode: RunMode;+ readonly retention?: AgentWorkflowRetentionDefinition;readonly serializedContext: Record<string, unknown>;readonly sessionState: DurableSessionState;readonly sessionTimeoutDeadline?: Date;@@ -514,6 +435,7 @@ async function runDriverLoop(input: {delivery,mode: input.mode,parentWritable: input.driverWritable,+ retention: input.retention,serializedContext,seenTaskDeliveries,sessionState: stateCursor.sessionState,diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.tsindex 03b47463b..b63f1f849 100644--- a/packages/eve/src/execution/workflow-runtime.ts+++ b/packages/eve/src/execution/workflow-runtime.ts@@ -155,6 +155,9 @@ export function createWorkflowRuntime(config: {parentTraceContext: input.parentTraceContext,});const sessionTimeoutMs = effectiveAgent.limits?.sessionTimeoutMs;+ // Retention is always the authored value: `experimental` cannot be+ // selected by a dynamic subagent config, so there is nothing to resolve.+ const retention = bundle.resolvedAgent.config?.experimental?.workflow?.retention;let collectorRunId: string | undefined;let activityObserver = input.activityObserver;if (@@ -178,6 +181,7 @@ export function createWorkflowRuntime(config: {const collector = await startWorkflowOnCurrentDeployment(activityCollectorWorkflowReference,[collectorInput],+ { experimental_retention: retention },);collectorRunId = collector.runId;const fallbackOrigin = process.env.VERCEL_URL@@ -217,6 +221,9 @@ export function createWorkflowRuntime(config: {if (sessionTimeoutMs !== undefined) {workflowInput.sessionTimeoutMs = sessionTimeoutMs;}+ if (retention !== undefined) {+ workflowInput.retention = retention;+ }const sessionAttributes =parentLineage.sessionId === undefined? buildSessionAttributes({@@ -243,6 +250,7 @@ export function createWorkflowRuntime(config: {run = await startWorkflowOnCurrentDeployment(workflowEntryReference, [workflowInput], {allowReservedAttributes: true,attributes: normalizeEveAttributes(attributes),+ experimental_retention: retention,});} catch (error) {await cancelActivityCollector(collectorRunId);diff --git a/packages/eve/src/internal/authored-definition/core.test.ts b/packages/eve/src/internal/authored-definition/core.test.tsindex 3d9903b65..af5dc6473 100644--- a/packages/eve/src/internal/authored-definition/core.test.ts+++ b/packages/eve/src/internal/authored-definition/core.test.ts@@ -296,6 +296,38 @@ describe("normalizeAgentDefinition", () => {).toThrow('"experimental.workflow.world" must be a non-empty package name');});+ it.each([0, "default"] as const)("accepts workflow retention %j", (value) => {+ const definition = normalizeAgentDefinition(+ {+ model: "openai/gpt-5.5",+ experimental: {+ workflow: {+ retention: value,+ },+ },+ },+ FAILURE_MESSAGE,+ );++ expect(definition.experimental?.workflow?.retention).toBe(value);+ });++ it.each(["none", "0", 1, true, null])("rejects invalid workflow retention %j", (value) => {+ expect(() =>+ normalizeAgentDefinition(+ {+ model: "openai/gpt-5.5",+ experimental: {+ workflow: {+ retention: value,+ },+ },+ },+ FAILURE_MESSAGE,+ ),+ ).toThrow('"experimental.workflow.retention" must be 0 or "default"');+ });+it.each([true, false])("rejects the removed subagentPersistentSessions flag", (value) => {expect(() =>normalizeAgentDefinition(diff --git a/packages/eve/src/internal/authored-definition/core.ts b/packages/eve/src/internal/authored-definition/core.tsindex f3e41287f..afecf9499 100644--- a/packages/eve/src/internal/authored-definition/core.ts+++ b/packages/eve/src/internal/authored-definition/core.ts@@ -15,7 +15,10 @@ import {expectString,getOptionalStringRecordProperty,} from "#internal/authored-module.js";-import type { PublicAgentStaticModelDefinition } from "#shared/agent-definition.js";+import {+ AGENT_WORKFLOW_RETENTION_VALUES,+ type PublicAgentStaticModelDefinition,+} from "#shared/agent-definition.js";import {isDynamicSentinel,type DynamicEvents,@@ -258,7 +261,7 @@ function normalizeAgentWorkflowDefinition(message: string,): AgentWorkflowDefinition {const record = expectObjectRecord(value, message);- expectOnlyKnownKeys(record, ["modelCallsPerStep", "world"], message);+ expectOnlyKnownKeys(record, ["modelCallsPerStep", "retention", "world"], message);const normalizedDefinition: Mutable<AgentWorkflowDefinition> = {};if (record.modelCallsPerStep !== undefined) {@@ -268,6 +271,13 @@ function normalizeAgentWorkflowDefinition();}+ if (record.retention !== undefined) {+ normalizedDefinition.retention = normalizeAgentWorkflowRetentionDefinition(+ record.retention,+ message,+ );+ }+if (record.world !== undefined) {normalizedDefinition.world = normalizeAgentWorkflowWorldDefinition(record.world, message);}@@ -275,6 +285,21 @@ function normalizeAgentWorkflowDefinition(return normalizedDefinition;}+function normalizeAgentWorkflowRetentionDefinition(+ value: unknown,+ message: string,+): NonNullable<AgentWorkflowDefinition["retention"]> {+ const match = AGENT_WORKFLOW_RETENTION_VALUES.find((accepted) => accepted === value);+ if (match === undefined) {+ const accepted = AGENT_WORKFLOW_RETENTION_VALUES.map((entry) => JSON.stringify(entry)).join(+ " or ",+ );+ throw new Error(`${message} "experimental.workflow.retention" must be ${accepted}.`);+ }++ return match;+}+function normalizeAgentWorkflowWorldDefinition(value: unknown,message: string,diff --git a/packages/eve/src/public/definitions/agent.ts b/packages/eve/src/public/definitions/agent.tsindex 04fe99066..ecc1a2427 100644--- a/packages/eve/src/public/definitions/agent.ts+++ b/packages/eve/src/public/definitions/agent.ts@@ -22,6 +22,7 @@ export type {AgentLimitsDefinition,PublicAgentModelSelectionDefinition as AgentModelSelectionDefinition,AgentWorkflowDefinition,+ AgentWorkflowRetentionDefinition,AgentWorkflowWorldDefinition,PublicAgentModelDefinition as AgentModelDefinition,PublicAgentStaticModelDefinition as AgentStaticModelDefinition,diff --git a/packages/eve/src/public/definitions/exact.test.ts b/packages/eve/src/public/definitions/exact.test.tsindex b4490cc9a..bc0074d1c 100644--- a/packages/eve/src/public/definitions/exact.test.ts+++ b/packages/eve/src/public/definitions/exact.test.ts@@ -40,6 +40,7 @@ describe("definition helper exact inputs", () => {experimental: {workflow: {modelCallsPerStep: 4,+ retention: 0,},},limits: {@@ -58,6 +59,7 @@ describe("definition helper exact inputs", () => {expect(agent.description).toBe("type-test");expect(agent.experimental.workflow.modelCallsPerStep).toBe(4);+ expect(agent.experimental.workflow.retention).toBe(0);expect(agent.limits.maxInputTokensPerSession).toBe(200_000);expect(agent.limits.maxOutputTokensPerSession).toBe(20_000);expect(agent.limits.maxTokenCostUsdPerSession).toBe(1.5);diff --git a/packages/eve/src/public/index.ts b/packages/eve/src/public/index.tsindex 3e0191e24..f1b318c57 100644--- a/packages/eve/src/public/index.ts+++ b/packages/eve/src/public/index.ts@@ -12,6 +12,7 @@ export {type AgentReasoningDefinition,type AgentStaticModelDefinition,type AgentWorkflowDefinition,+ type AgentWorkflowRetentionDefinition,type AgentWorkflowWorldDefinition,type DefinedAgent,type DynamicSubagentDefinition,diff --git a/packages/eve/src/runtime/resolve-agent.ts b/packages/eve/src/runtime/resolve-agent.tsindex e3dd94557..5ab92b695 100644--- a/packages/eve/src/runtime/resolve-agent.ts+++ b/packages/eve/src/runtime/resolve-agent.ts@@ -247,6 +247,7 @@ function createResolvedAgentConfig(? undefined: {modelCallsPerStep: manifest.config.experimental.workflow.modelCallsPerStep,+ retention: manifest.config.experimental.workflow.retention,world: manifest.config.experimental.workflow.world,},};diff --git a/packages/eve/src/shared/agent-definition.drift.test.ts b/packages/eve/src/shared/agent-definition.drift.test.tsnew file mode 100644index 000000000..49465605a--- /dev/null+++ b/packages/eve/src/shared/agent-definition.drift.test.ts@@ -0,0 +1,30 @@+import { RETENTION_DEFAULT, RETENTION_ZERO } from "@workflow/world";+import { describe, expect, it } from "vitest";++import { AGENT_WORKFLOW_RETENTION_VALUES } from "#shared/agent-definition.js";++/**+ * Guards eve's authored retention values against drift from the Workflow+ * SDK's `RunRetention`.+ *+ * eve declares its own tuple rather than aliasing the SDK type, so the+ * authored surface stays eve-owned and the same list can drive the zod+ * schema and the normalizer. That independence is the reason this guard+ * exists: nothing else would notice if the SDK grew or renamed a value.+ *+ * The assertion is deliberately a runtime one. `pnpm typecheck` excludes+ * test files, so a type-level `satisfies` here would never be checked.+ *+ * `@workflow/world` encodes retention on the wire as strings, hence the+ * `Number()` around `RETENTION_ZERO`. If this fails after a `@workflow/*`+ * bump, the SDK changed its accepted values: update+ * `AGENT_WORKFLOW_RETENTION_VALUES`, the docs page, and the docstring on+ * `AgentWorkflowDefinition["retention"]` together.+ */+describe("AGENT_WORKFLOW_RETENTION_VALUES drift guard", () => {+ it("matches the values @workflow/world accepts", () => {+ expect([...AGENT_WORKFLOW_RETENTION_VALUES].sort()).toEqual(+ [Number(RETENTION_ZERO), RETENTION_DEFAULT].sort(),+ );+ });+});diff --git a/packages/eve/src/shared/agent-definition.ts b/packages/eve/src/shared/agent-definition.tsindex 8ec938e78..4acb31da7 100644--- a/packages/eve/src/shared/agent-definition.ts+++ b/packages/eve/src/shared/agent-definition.ts@@ -254,6 +254,23 @@ export interface AgentBuildDefinition {*/export type AgentWorkflowWorldDefinition = string;+/**+ * Accepted values for `experimental.workflow.retention`.+ *+ * Declared as eve's own tuple so the authored type, the manifest schema, and+ * the authored-definition normalizer share one source of truth. A drift test+ * keeps it aligned with what the Workflow SDK accepts.+ */+export const AGENT_WORKFLOW_RETENTION_VALUES = [0, "default"] as const;++/**+ * How long the durable runtime keeps a run's data after the run finishes.+ *+ * The value is a duration, and zero is currently the only one besides the+ * world's default.+ */+export type AgentWorkflowRetentionDefinition = (typeof AGENT_WORKFLOW_RETENTION_VALUES)[number];+/*** Advanced durable-runtime configuration for eve's Workflow SDK integration.*/@@ -268,6 +285,26 @@ export interface AgentWorkflowDefinition {* @default 1*/readonly modelCallsPerStep?: number;+ /**+ * How long the agent's run data is kept after the run finishes.+ * Applied to both the session run and every turn run.+ *+ * - `"default"`: same as omission. The Workflow SDK World decides.+ * On Vercel this follows your team's plan.+ * - `0`: the world deletes run payloads and stream chunks as soon as the run+ * completes or fails. Metadata such as run IDs, status, and timestamps may+ * persist up to the default period.+ *+ * The World you are using with the Workflow SDK might not support every+ * option. A World that does not recognize the value keeps the data.+ *+ * Note that with retention set to `0`, data deletion can race reads of a finished+ * run, so results and transcripts of completed sessions generally become+ * unreadable. Persist anything you need to keep from inside a tool.+ *+ * @default "default"+ */+ readonly retention?: AgentWorkflowRetentionDefinition;/*** Workflow world module used for durable workflow storage, queueing, hooks,* and streaming.diff --git a/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts b/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.tsindex 73a3e1c88..cabb4fc63 100644--- a/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts+++ b/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts@@ -6,6 +6,7 @@ import { dirname, join, relative } from "node:path";import { afterEach, describe, expect, it } from "vitest";import { compileAgent } from "../../src/compiler/compile-agent.js";+import { EXTENSION_CAPABILITY_VERSIONS } from "../../src/compiler/extension-compatibility.js";import {buildExtensionPackage,tryReadExtensionBuildConfig,@@ -249,7 +250,13 @@ describe("mounted extension installed under node_modules", () => {);expect(JSON.parse(extensionFiles[`node_modules/${PACKAGE_NAME}/dist/extension/_manifest.json`]!),- ).toMatchObject({ requires: { channel: 19, schedule: 11, subagent: 11 } });+ ).toMatchObject({+ requires: {+ channel: EXTENSION_CAPABILITY_VERSIONS.channel,+ schedule: EXTENSION_CAPABILITY_VERSIONS.schedule,+ subagent: EXTENSION_CAPABILITY_VERSIONS.subagent,+ },+ });const app = await scenarioApp({name: "mounted-extension-installed",installDependencies: true,