The Open Framework for Building Agents
Align Workflow retention with trace capture policies (#4909)
Chad Hietala3fea287bc76f
diff --git a/.changeset/trace-policy-workflow-retention.md b/.changeset/trace-policy-workflow-retention.mdnew file mode 100644index 000000000..24bcf0181--- /dev/null+++ b/.changeset/trace-policy-workflow-retention.md@@ -0,0 +1,5 @@+---+"eve": minor+---++Dropped traces and policies excluding either content direction now request Workflow data deletion when the run ends; set `experimental.workflow.retention: "default"` to retain completed transcripts independently of tracing. Expired session-history reads return `410 session_expired` before streaming, including when the World retains purged chunk records.diff --git a/docs/agent-config.md b/docs/agent-config.mdindex f9387f5a8..5593ed4f7 100644--- a/docs/agent-config.md+++ b/docs/agent-config.md@@ -263,7 +263,8 @@ duration. Process restarts, ordinary messages, compaction handoffs, and failedor 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 nextqualifying channel message starts fresh. Set it to `false` to disable the-timeout. Expiration does not delete stored session data.+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@@ -409,11 +410,24 @@ 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:+By default, eve derives run-data retention from the session's resolved+[OpenTelemetry trace policy](./observability/otel#configure-opentelemetry):++- When the policy allows both inputs and outputs, eve uses the World's default+ retention period.+- When the policy drops the trace or excludes either content direction, eve+ requests deletion as soon as the run ends with Workflow's+ `experimental_retention: 0`. Workflow cannot delete inputs and outputs separately.++Without a custom policy, public conversations and development sessions use the+World's default. Private and unknown-audience sessions outside development request+`0`, even when no OpenTelemetry destination is installed. This decision is made+when the session starts; destination export filters and lifecycle-provider+policies do not change it.++Set `experimental.workflow.retention` explicitly to override this behavior.+Use `0` to request deletion regardless of the tracing policy, or `"default"` to+keep run data for the World's default period regardless of the tracing policy:```ts title="agent/agent.ts"import { defineAgent } from "eve";@@ -428,18 +442,29 @@ export default defineAgent({});```-This applies to every run that owns the session, including successor owners+The resolved value applies to every run that owns the session, including successor ownersstarted after a deployment handoff, and to the run that collects sessionactivity. Runs eve starts for other purposes keep the world's default: sessiontimeouts 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.+uses its own explicit value or derives retention from its resolved trace decision,+including any inherited content ceiling. `experimental.workflow.world` is root-only.++At `0`, supporting Worlds delete run and step inputs, outputs, and errors;+event payloads; and stream contents when the run reaches a terminal state. The+data remains available while the session is active. Run, step, and event records+remain for the World's default period, including IDs, timestamps, statuses,+step names, and attributes. Attributes can contain content, including eve's+session title. This option does not delete local traces, exported telemetry, or+data stored by tools, channels, or model providers.++The Workflow World enforces deletion, not eve or the SDK. A World older than+spec version 4 rejects `0`; a spec version 4 World without retention support+keeps the data. Confirm support with your World provider. See+[Workflow data retention](https://workflow-sdk.dev/docs/observability/retention).++> ⚠️ **At `0`, completed session transcripts become unreadable.** Deletion races reads of finished runs. Depending on the World, reading deleted session history returns either an empty stream or `410` with `code: "session_expired"`. Persist anything you need to keep from inside a tool, or set `retention: "default"` to preserve completed-session reads independently of tracing.## Other defineAgent fieldsdiff --git a/docs/guides/instrumentation/otel.mdx b/docs/guides/instrumentation/otel.mdxindex 8814a36e2..8679147d7 100644--- a/docs/guides/instrumentation/otel.mdx+++ b/docs/guides/instrumentation/otel.mdx@@ -38,6 +38,16 @@ does not affect lifecycle instrumentation created with `defineInstrumentation()`See [Audience](../channels/overview#audience) for how channels classify theconversation passed to this policy.+The session's resolved capture decision also selects its default+[Workflow run-data retention](/docs/agent-config#run-data-retention). Allowing+both inputs and outputs uses the World's default; dropping the trace or excluding+either direction requests deletion of durable payloads and streams when the run+ends. This makes completed private and unknown-audience transcripts unreadable+under the default policy outside development. Set+`experimental.workflow.retention: "default"` on the agent to retain completed+sessions independently of tracing. Destination `exportPolicy` filters do not+change Workflow retention, and Workflow deletion does not delete exported traces.+## Instrument Node.js dependenciesPass OpenTelemetry instrumentation instances to `otel({ instrumentations })`.diff --git a/e2e/fixtures/agent-basic-runtime/agent/channels/eve.ts b/e2e/fixtures/agent-basic-runtime/agent/channels/eve.tsindex 485c0ceac..96fc1af45 100644--- a/e2e/fixtures/agent-basic-runtime/agent/channels/eve.ts+++ b/e2e/fixtures/agent-basic-runtime/agent/channels/eve.ts@@ -24,7 +24,17 @@ const authenticateB: AuthFn<Request> = (request) =>const authenticateMember: AuthFn<Request> = (request) =>authenticateWorkspaceMember(request.headers.get("authorization"));const authenticateEvalDriver: AuthFn<Request> = () => principal("eval-driver");+const authenticateRetentionCheck: AuthFn<Request> = (request) =>+ request.headers.get("authorization") === "Bearer e2e-metadata-retention"+ ? { ...principal("retention-check"), principalType: "metadata-only" }+ : null;export default eveChannel({- auth: [authenticateA, authenticateB, authenticateMember, authenticateEvalDriver],+ auth: [+ authenticateA,+ authenticateB,+ authenticateMember,+ authenticateRetentionCheck,+ authenticateEvalDriver,+ ],});diff --git a/e2e/fixtures/agent-basic-runtime/agent/instrumentation/otel.ts b/e2e/fixtures/agent-basic-runtime/agent/instrumentation/otel.tsindex f540bdf8a..00bbb8a27 100644--- a/e2e/fixtures/agent-basic-runtime/agent/instrumentation/otel.ts+++ b/e2e/fixtures/agent-basic-runtime/agent/instrumentation/otel.ts@@ -2,5 +2,9 @@ import { otel } from "eve/instrumentation/otel";export default otel({instrumentations: ["fetch"],- tracePolicy: () => ({ emit: true, recordInputs: true, recordOutputs: true }),+ tracePolicy: ({ principalType }) => ({+ emit: true,+ recordInputs: principalType !== "metadata-only",+ recordOutputs: principalType !== "metadata-only",+ }),});diff --git a/e2e/fixtures/agent-basic-runtime/evals/runtime/workflow-retention.eval.ts b/e2e/fixtures/agent-basic-runtime/evals/runtime/workflow-retention.eval.tsnew file mode 100644index 000000000..97fea56e2--- /dev/null+++ b/e2e/fixtures/agent-basic-runtime/evals/runtime/workflow-retention.eval.ts@@ -0,0 +1,74 @@+import { defineEval } from "eve/evals";+import { equals, satisfies } from "eve/evals/expect";++export default defineEval({+ description:+ "Metadata-only sessions lose their durable transcript after reset, while full-capture sessions retain it.",+ async test(t) {+ const message =+ "Alice has finished reviewing her notes. Greet her briefly without calling tools.";+ for (const metadataOnly of [false, true]) {+ const headers: Record<string, string> = metadataOnly+ ? { authorization: "Bearer e2e-metadata-retention" }+ : {};+ const turn = await t.send(message, { headers });+ turn.expectOk();+ turn.event("message.completed", { count: 1 });+ const sessionPath = `/eve/v1/session/${encodeURIComponent(turn.sessionId)}`;+ const readHistory = () =>+ t.target.fetch(`${sessionPath}/stream?follow=false&startIndex=0`, {+ headers,+ signal: t.signal,+ });+ const live = await readHistory();+ await t.require(live.status, equals(200));+ await t.require((await live.text()).includes(message), equals(true));++ const reset = await t.target.fetch(`${sessionPath}/reset`, {+ headers,+ method: "POST",+ signal: t.signal,+ });+ await t.require(reset.status, equals(200));+ await reset.body?.cancel();+ if (!metadataOnly) {+ const retained = await readHistory();+ await t.require(retained.status, equals(200));+ await t.require((await retained.text()).includes(message), equals(true));+ continue;+ }++ let purged = false;+ for (const delayMs of [0, 50, 100, 200, 400, 800, 1_600, 3_200]) {+ await t.sleep(delayMs);+ const history = await readHistory();+ if (history.status === 410) {+ await t.require((await history.json()).code, equals("session_expired"));+ purged = true;+ break;+ }+ await t.require(history.status, equals(200));+ let body: string;+ try {+ body = await history.text();+ } catch (error) {+ // A purge can interrupt a read after the server commits its 200 response.+ if (!(error instanceof TypeError)) throw error;+ t.signal.throwIfAborted();+ continue;+ }+ if (body.trim().length === 0) {+ purged = true;+ break;+ }+ }+ await t.require(+ purged,+ satisfies(+ (value: boolean) => value,+ "metadata-only session history is expired or empty after reset",+ ),+ );+ }+ },+});diff --git a/e2e/fixtures/agent-workflow-tools/agent/subagents/workflow-marker/agent.ts b/e2e/fixtures/agent-workflow-tools/agent/subagents/workflow-marker/agent.tsindex 9875d0b13..cfdecc83d 100644--- a/e2e/fixtures/agent-workflow-tools/agent/subagents/workflow-marker/agent.ts+++ b/e2e/fixtures/agent-workflow-tools/agent/subagents/workflow-marker/agent.ts@@ -5,4 +5,6 @@ export default defineAgent({description: "Return deterministic markers for workflow-subagent e2e coverage.",model: mockModel(({ lastUserMessage }) => `WORKFLOW-CHILD:${lastUserMessage ?? ""}`),modelContextWindowTokens: 1_000_000,+ // Fanout evals read ended child histories to verify their trace relationships.+ experimental: { workflow: { retention: "default" } },});diff --git a/packages/eve/src/execution/session-event-stream.test.ts b/packages/eve/src/execution/session-event-stream.test.tsindex 3daaefed0..a0d72bad0 100644--- a/packages/eve/src/execution/session-event-stream.test.ts+++ b/packages/eve/src/execution/session-event-stream.test.ts@@ -1,13 +1,16 @@-import { afterEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { RunExpiredError } from "#compiled/@workflow/errors/index.js";import { TEST_USAGE, stampTestEvent } from "#internal/testing/events.js";import { createSessionWaitingEvent, type MessageStreamEvent } from "#protocol/message.js";import { sessions } from "#public/server/index.js";const getRunMock = vi.fn();+const getRunMetadataMock = vi.fn();vi.mock("#compiled/@workflow/core/runtime.js", () => ({getRun: (...args: unknown[]) => getRunMock(...args),+ getWorld: async () => ({ runs: { get: getRunMetadataMock } }),}));const encoder = new TextEncoder();@@ -55,11 +58,45 @@ async function collect(iterable: AsyncIterable<MessageStreamEvent>) {return events;}+beforeEach(() => {+ getRunMetadataMock.mockResolvedValue({ status: "running" });+});+afterEach(() => {getRunMock.mockReset();+ getRunMetadataMock.mockReset();});describe("sessions.attach().stream()", () => {+ it("rejects expired run data even when the World still reports stored stream chunks", async () => {+ const stream = mockSessionStream(storedEvents(2));+ const expiredAt = new Date("2020-01-01T00:00:00.000Z");+ getRunMetadataMock.mockResolvedValue({ status: "completed", expiredAt });++ const read = collect(sessions.attach("wrun_1").stream({ follow: false }));+ await expect(read).rejects.toBeInstanceOf(RunExpiredError);+ await expect(read).rejects.toMatchObject({+ runId: "wrun_1",+ runStatus: "completed",+ expiredAt,+ });+ expect(stream.startIndexes).toEqual([]);+ expect(getRunMetadataMock).toHaveBeenCalledWith("wrun_1", { resolveData: "none" });+ });++ it("keeps completed history readable until its retention deadline", async () => {+ const stored = storedEvents(2);+ mockSessionStream(stored);+ getRunMetadataMock.mockResolvedValue({+ status: "completed",+ expiredAt: new Date("2100-01-01T00:00:00.000Z"),+ });++ await expect(collect(sessions.attach("wrun_1").stream({ follow: false }))).resolves.toEqual(+ stored,+ );+ });+it("ends a bounded read at the tail observed when it opens", async () => {const stored = storedEvents(3);const stream = mockSessionStream(stored, { open: true });diff --git a/packages/eve/src/execution/session-event-stream.ts b/packages/eve/src/execution/session-event-stream.tsindex dd568a274..5b3593967 100644--- a/packages/eve/src/execution/session-event-stream.ts+++ b/packages/eve/src/execution/session-event-stream.ts@@ -1,5 +1,6 @@import { parseNdjsonStream } from "#execution/ndjson-stream.js";-import { getRun } from "#internal/workflow/runtime.js";+import { RunExpiredError } from "#compiled/@workflow/errors/index.js";+import { getRun, getWorld } from "#internal/workflow/runtime.js";import type { MessageStreamEvent } from "#protocol/message.js";import {normalizePersistedMessageStreamEvent,@@ -65,7 +66,21 @@ export async function readSessionStreamTailIndex(sessionId: string): Promise<num// The readable is never consumed; cancel it so the unread source does not linger.const readable = getRun(sessionId).getReadable();try {- return await readable.getTailIndex();+ const world = await getWorld();+ const [run, tailIndex] = await Promise.all([+ world.runs.get(sessionId, { resolveData: "none" }),+ readable.getTailIndex(),+ ]);+ // Purging can leave chunk records behind; their count does not imply readable data.+ if (run.expiredAt !== undefined && run.expiredAt.getTime() <= Date.now()) {+ throw new RunExpiredError(+ "Session history is no longer available.",+ sessionId,+ run.status,+ run.expiredAt,+ );+ }+ return tailIndex;} finally {await readable.cancel().catch(() => {});}diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.tsindex b1a03e2e5..58e8f0192 100644--- a/packages/eve/src/execution/workflow-runtime.test.ts+++ b/packages/eve/src/execution/workflow-runtime.test.ts@@ -31,7 +31,8 @@ import { AgentSpanIdGenerator } from "#compiled/@eve/tracing/index.js";import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";import { markAgentTraceContext } from "#tracing/eve/agent-trace-context.js";-import type { TraceCaptureContext } from "#shared/trace-policy.js";+import type { TraceCaptureContext, TraceCapturePolicy } from "#shared/trace-policy.js";+import type { AgentWorkflowRetentionDefinition } from "#shared/agent-definition.js";import { captureLogRecords } from "#internal/testing/log-records.js";const getHookByTokenMock = vi.fn();@@ -154,50 +155,55 @@ describe("session owner starts", () => {expect(startMock).not.toHaveBeenCalled();});- it("starts a successor on the accepted deployment with the original stream", async () => {- const sessionWritable = new WritableStream<Uint8Array>();- getRunMock.mockReturnValue({ getWritable: () => sessionWritable });- startMock.mockResolvedValue({ runId: "owner-2" });- const checkpoint = {- version: 10,- serializedContext: {},- sessionState: { continuationToken: "continuation-1", sessionId: "session-1" },- sessionTimeoutMs: 60_000,- } as never;- const delivery = { kind: "deliver", payloads: [{ message: "hello" }] } as const;+ it.each([undefined, 0, "default"] as const)(+ "starts a successor with the original stream and retention=%s",+ async (retention) => {+ const sessionWritable = new WritableStream<Uint8Array>();+ getRunMock.mockReturnValue({ getWritable: () => sessionWritable });+ startMock.mockResolvedValue({ runId: "owner-2" });+ const checkpoint = {+ version: 10,+ serializedContext: {},+ sessionState: { continuationToken: "continuation-1", sessionId: "session-1" },+ sessionTimeoutMs: 60_000,+ retention,+ } as never;+ const delivery = { kind: "deliver", payloads: [{ message: "hello" }] } as const;- await expect(- startSessionOwnerStep({- activationToken: "owner-1:handoff",- anchorRunId: "anchor-1",- checkpoint,- delivery,- targetDeploymentId: "deployment-b",- }),- ).resolves.toBeUndefined();-- expect(getRunMock).toHaveBeenCalledWith("anchor-1");- expect(startMock).toHaveBeenCalledWith(- workflowEntryReference,- [- expect.objectContaining({+ await expect(+ startSessionOwnerStep({activationToken: "owner-1:handoff",+ anchorRunId: "anchor-1",checkpoint,delivery,- handoffVersion: 2,- kind: "handoff",- ownerDeploymentId: "deployment-b",- sessionWritable,- sessionId: "anchor-1",+ targetDeploymentId: "deployment-b",}),- ],- {- deploymentId: "deployment-b",- allowReservedAttributes: true,- attributes: { "$eve.version": resolveInstalledPackageInfo().version },- },- );- });+ ).resolves.toBeUndefined();++ expect(getRunMock).toHaveBeenCalledWith("anchor-1");+ expect(startMock).toHaveBeenCalledWith(+ workflowEntryReference,+ [+ expect.objectContaining({+ activationToken: "owner-1:handoff",+ checkpoint,+ delivery,+ handoffVersion: 2,+ kind: "handoff",+ ownerDeploymentId: "deployment-b",+ sessionWritable,+ sessionId: "anchor-1",+ }),+ ],+ expect.objectContaining({+ deploymentId: "deployment-b",+ allowReservedAttributes: true,+ attributes: { "$eve.version": resolveInstalledPackageInfo().version },+ }),+ );+ expect(startMock.mock.calls[0]?.[2].experimental_retention).toBe(retention);+ },+ );});describe("createWorkflowRuntime command dispatch", () => {@@ -624,6 +630,7 @@ describe("createWorkflowRuntime#createSession", () => {kind: "initial",ownerDeploymentId: "dpl_current",input: { message: "hello" },+ retention: 0,serializedContext: expect.objectContaining({"eve.bundle": { source: compiledArtifactsSource },"eve.stateLayout": 1,@@ -643,6 +650,7 @@ describe("createWorkflowRuntime#createSession", () => {"$eve.version": resolveInstalledPackageInfo().version,},deploymentId: "dpl_current",+ experimental_retention: 0,},);});@@ -798,6 +806,7 @@ describe("createWorkflowRuntime#createSession", () => {kind: "initial",ownerDeploymentId: "dpl_current",input: { message: "hello" },+ retention: 0,serializedContext: expect.objectContaining({[ChannelRequestIdKey.name]: "req_run",}),@@ -815,6 +824,7 @@ describe("createWorkflowRuntime#createSession", () => {"$eve.version": resolveInstalledPackageInfo().version,},deploymentId: "dpl_current",+ experimental_retention: 0,},);});@@ -861,6 +871,7 @@ describe("createWorkflowRuntime#createSession", () => {"$eve.version": resolveInstalledPackageInfo().version,},deploymentId: "dpl_current",+ experimental_retention: 0,});});@@ -887,6 +898,7 @@ describe("createWorkflowRuntime#createSession", () => {"$eve.version": resolveInstalledPackageInfo().version,},deploymentId: "dpl_current",+ experimental_retention: 0,});});@@ -982,10 +994,10 @@ describe("createWorkflowRuntime#createSession trace seed allocation", () => {return createWorkflowRuntime({ compiledArtifactsSource: {} as RuntimeCompiledArtifactsSource });}- function mockBundleAndRun(): void {+ function mockBundleAndRun(retention?: AgentWorkflowRetentionDefinition): void {vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({compiledArtifactsSource: {},- resolvedAgent: { config: {} },+ resolvedAgent: { config: { experimental: { workflow: { retention } } } },turnAgent: {id: "test-agent",instructions: [],@@ -1007,7 +1019,7 @@ describe("createWorkflowRuntime#createSession trace seed allocation", () => {function installAgentOtelRuntime(idGenerator: AgentSpanIdGenerator,- tracePolicy: () => boolean,+ tracePolicy: TraceCapturePolicy,): void {registerInstrumentationRuntime({forceFlush: async () => undefined,@@ -1030,6 +1042,96 @@ describe("createWorkflowRuntime#createSession trace seed allocation", () => {delete global[Symbol.for("eve.instrumentation-runtime")];});+ it.each<{+ name: string;+ policy: TraceCapturePolicy;+ retention: AgentWorkflowRetentionDefinition | undefined;+ }>([+ { name: "full capture", policy: () => true, retention: undefined },+ { name: "dropped trace", policy: () => false, retention: 0 },+ {+ name: "metadata-only capture",+ policy: () => ({ emit: true, recordInputs: false, recordOutputs: false }),+ retention: 0,+ },+ {+ name: "input-only capture",+ policy: () => ({ emit: true, recordInputs: true, recordOutputs: false }),+ retention: 0,+ },+ {+ name: "output-only capture",+ policy: () => ({ emit: true, recordInputs: false, recordOutputs: true }),+ retention: 0,+ },+ {+ name: "throwing policy",+ policy: () => {+ throw new Error("Policy unavailable");+ },+ retention: 0,+ },+ ])(+ "derives Workflow retention from $name without reevaluating the policy",+ async ({ policy, retention }) => {+ const tracePolicy = vi.fn(policy);+ installAgentOtelRuntime(new AgentSpanIdGenerator(), tracePolicy);+ mockBundleAndRun();+ startMock.mockResolvedValue({ runId: "owner-run" });++ await buildRuntime().createSession({ adapter, auth: null, input: { message: "hello" } });++ const [, [workflowInput], options] = startMock.mock.calls[0]!;+ expect(options.experimental_retention).toBe(retention);+ expect(workflowInput.retention).toBe(retention);+ expect(tracePolicy).toHaveBeenCalledOnce();+ },+ );++ it.each([+ { authored: 0, capture: true },+ { authored: "default", capture: false },+ ] as const)(+ "honors explicit retention $authored over capture=$capture",+ async ({ authored, capture }) => {+ installAgentOtelRuntime(new AgentSpanIdGenerator(), () => capture);+ mockBundleAndRun(authored);+ startMock.mockResolvedValue({ runId: "owner-run" });++ await buildRuntime().createSession({ adapter, auth: null, input: { message: "hello" } });++ const [, [workflowInput], options] = startMock.mock.calls[0]!;+ expect(options.experimental_retention).toBe(authored);+ expect(workflowInput.retention).toBe(authored);+ },+ );++ it.each([+ { audience: "public", development: false, retention: undefined },+ { audience: "private", development: false, retention: 0 },+ { audience: "unknown", development: false, retention: 0 },+ { audience: "private", development: true, retention: undefined },+ ] as const)(+ "uses audience=$audience development=$development without OTel",+ async ({ audience, development, retention }) => {+ vi.stubEnv("EVE_DEV", development ? "1" : "");+ vi.stubEnv("VERCEL_ENV", "production");+ mockBundleAndRun();+ startMock.mockResolvedValue({ runId: "owner-run" });++ await buildRuntime().createSession({+ adapter: { kind: "http", instrumentation: { audience: () => audience } },+ auth: null,+ input: { message: "hello" },+ });++ const [, [workflowInput], options] = startMock.mock.calls[0]!;+ expect(options.experimental_retention).toBe(retention);+ expect(workflowInput.retention).toBe(retention);+ expect(workflowInput.serializedContext["eve.sessionTraceSeed"]).toBeUndefined();+ },+ );+it("allocates a sampled trace seed when the policy is sampled", async () => {const idGenerator = new AgentSpanIdGenerator();const tracePolicy = vi.fn(() => true);@@ -1155,6 +1257,8 @@ describe("createWorkflowRuntime#createSession trace seed allocation", () => {expect(seed!.traceId).toBe(parentTrace.traceId);expect(seed!.spanId).not.toBe(parentTrace.spanId);expect(serialized["eve.parentTraceContext"]).toEqual(parentTrace);+ expect(workflowInput[0].retention).toBe(0);+ expect(startMock.mock.calls[0]?.[2].experimental_retention).toBe(0);expect(serialized["eve.otelTraceEnabled"]).toBe(true);expect(startMock.mock.calls[0]?.[2].attributes["$eve.is_otel_trace_enabled"]).toBe("true");expect(tracePolicy).not.toHaveBeenCalled();diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.tsindex ef6aa4de9..5a3a36eb2 100644--- a/packages/eve/src/execution/workflow-runtime.ts+++ b/packages/eve/src/execution/workflow-runtime.ts@@ -161,14 +161,19 @@ export function createWorkflowRuntime(config: {});if (predecessor !== undefined) ctx.set(SessionPredecessorKey, predecessor);const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);- initializeSessionInstrumentation({+ const traceDecision = initializeSessionInstrumentation({agentName: effectiveAgent.turnAgent.id,ctx,});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;+ // Workflow cannot purge inputs and outputs independently.+ const retention =+ bundle.resolvedAgent.config?.experimental?.workflow?.retention ??+ (traceDecision.action === "record" &&+ traceDecision.recordInputs &&+ traceDecision.recordOutputs+ ? undefined+ : 0);const serializedContext = serializeContext(ctx);const parentLineage = readParentLineage(serializedContext);const workflowInput: {diff --git a/packages/eve/src/instrumentation/session-init.ts b/packages/eve/src/instrumentation/session-init.tsindex ce2500a2f..ac04ad8cf 100644--- a/packages/eve/src/instrumentation/session-init.ts+++ b/packages/eve/src/instrumentation/session-init.ts@@ -24,6 +24,7 @@ import {import {intersectInstrumentationDecisions,readInstrumentationDecision,+ type InstrumentationDecision,} from "#shared/instrumentation-decision.js";import {isSampledTrace,@@ -39,7 +40,7 @@ const log = createLogger("instrumentation.session-init");export function initializeSessionInstrumentation(input: {readonly agentName: string;readonly ctx: ContextContainer;-}): void {+}): InstrumentationDecision {const runtime = getInstrumentationRuntime();const parentTraceContext = input.ctx.get(ParentTraceContextKey);const forwardedTracePolicy = readForwardedTraceAssertion(@@ -87,6 +88,13 @@ export function initializeSessionInstrumentation(input: {}}input.ctx.set(OtelTraceEnabledKey, runtime?.prepareSessionTrace !== undefined);+ return (+ traceSeed?.decision ??+ resolveTracePolicy(runtime?.otelSettings?.tracePolicy, {+ agentName: input.agentName,+ ...conversation,+ })+ );}function allocateSessionTraceSeed(input: {diff --git a/packages/eve/src/shared/agent-definition.ts b/packages/eve/src/shared/agent-definition.tsindex addc6bd95..f1abfab8c 100644--- a/packages/eve/src/shared/agent-definition.ts+++ b/packages/eve/src/shared/agent-definition.ts@@ -302,20 +302,28 @@ export interface AgentWorkflowDefinition {* Applied to every run that owns the session, including successors created* by deployment handoff.*- * - `"default"`: same as omission. The Workflow SDK World decides.+ * When omitted, eve uses the session's resolved OTel trace decision: full+ * input and output capture keeps the World's default; dropped traces or+ * either excluded content direction request `0`. Destination export filters+ * and lifecycle-provider policies do not affect this choice.+ *+ * An explicit value overrides this automatic choice:+ * - `"default"`: the Workflow SDK World decides, regardless of tracing.* 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.+ * The World enforces deletion. Worlds older than spec version 4 reject `0`;+ * spec version 4 Worlds without retention support keep the data. Run, step,+ * and event metadata and attributes remain for the default period. Exported+ * traces are not deleted.** 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"+ * @default Derived from the session's resolved trace policy.*/readonly retention?: AgentWorkflowRetentionDefinition;/**diff --git a/packages/eve/src/tracing/eve/otel-declaration.ts b/packages/eve/src/tracing/eve/otel-declaration.tsindex 7efb6a21b..e08e43be5 100644--- a/packages/eve/src/tracing/eve/otel-declaration.ts+++ b/packages/eve/src/tracing/eve/otel-declaration.ts@@ -69,6 +69,11 @@ export interface OtelOptions {* lifecycle providers. The policy may be invoked more than once* while a new session is being prepared, so it must be deterministic for* consistent results.+ * Unless `experimental.workflow.retention` is explicit, the session's+ * resolved decision also selects Workflow retention: both content directions+ * use the World's default; dropped traces or either excluded direction+ * request deletion on completion. This also removes completed transcripts,+ * but does not delete exported traces.*/readonly tracePolicy?: TraceCapturePolicy;/**diff --git a/research/channel-audience-content-policy.md b/research/channel-audience-content-policy.mdindex 85e785278..b7912b517 100644--- a/research/channel-audience-content-policy.md+++ b/research/channel-audience-content-policy.md@@ -1,7 +1,7 @@---issue: https://github.com/vercel/eve/issues/2331status: implemented-last_updated: "2026-09-17"+last_updated: "2026-10-15"---# Audience-aware trace content policy@@ -213,6 +213,35 @@ There is no implicit content redaction after a custom trace policy admits an audPolicies fail closed at their boundary: a throwing trace policy rejects the trace, a throwing span policy drops the span, a malformed or directionless redaction decision drops the span, and a throwing or malformed attribute policy drops the attribute. Missing, malformed, or conflicting audience evidence normalizes to `unknown`.+## Workflow retention alignment++At session creation, the resolved process-wide trace decision also determines+the default Workflow retention preference. Full input and output capture leaves+the World's default unchanged; dropped traces, metadata-only capture, and+directional capture request `experimental_retention: 0`. Workflow cannot purge+directions independently. The audience-aware default applies even without an+installed OTel destination.++An explicit `experimental.workflow.retention` overrides this derivation:+`"default"` preserves completed-session reads independently of tracing, and `0`+always requests deletion. The resolved value travels in session state and owner+checkpoints, so handoff does not recompute it under a later deployment's policy.+Subagents derive their own value from their resolved inherited trace decision+unless they author an override. Destination export policies and lifecycle+providers remain independent.++This requests World-enforced deletion at the terminal run boundary, not+redaction while running. It removes durable session payloads and streams, so+completed transcripts can return `410 session_expired`. Records and attributes+(including session titles), external telemetry, and tool-owned storage remain.+Worlds older than spec version 4 reject `0`; version 4 Worlds without retention+support keep the data.++Before serving a session stream, eve checks the run's payload-free expiry+metadata alongside its stream tail. A World can retain chunk records after+purging their contents, so a nonempty tail alone cannot establish readability.+Expired metadata produces `410 session_expired` before response headers are sent.+## CompatibilityInstrumentation providers deprecate the experimental `capture` field in favor