The Open Framework for Building Agents
fix(eve): trace background actions through task settlement (#3183)
Chad Hietala9381078c9d4e
diff --git a/.changeset/trace-background-action-lifetime.md b/.changeset/trace-background-action-lifetime.mdnew file mode 100644index 000000000..897bbebed--- /dev/null+++ b/.changeset/trace-background-action-lifetime.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Keep `agent.action` spans for background tools and subagents open until their tasks complete, fail, or are cancelled, and record the task's final outcome and policy-controlled error details instead of treating its receipt as completion.diff --git a/docs/guides/instrumentation.md b/docs/guides/instrumentation.mdindex 98e707d01..5789b2776 100644--- a/docs/guides/instrumentation.md+++ b/docs/guides/instrumentation.md@@ -152,6 +152,16 @@ The legacy `instrumentation.ts` layout still uses its authored OTel setup.| `agent.approval` | Approval waiting beneath its action || `agent.channel.request` | Optional HTTP request span in the provider layout |+For background tools and subagents, the AI SDK's `execute_tool` span ends when+the model receives the task receipt. The enclosing `agent.action` span remains+open until the background task completes, fails, or is cancelled. Its duration,+outcome, and usage describe the background task rather than the receipt.+Background tool results follow the output-content policy. Recorded task failure+details become bounded exception and status messages; redacted spans retain only+the failure outcome, error status, and error type. The initiating turn can+finish or be cancelled while the action remains open. Ending the session closes+an action whose task never reported a terminal result.+Schema v4 removes the session-long `agent.session` root and duplicate agent session and lineage attributes. Every eve span carries `agent.trace.schema.version=4` and `gen_ai.conversation.id`; Vercel deployments additionally carry `vercel.session_id`.Only activations use the `invoke_agent` operation. Dispatch lifecycle spans use`agent.action` with `agent.invocation.role=caller`; the built-in `agent` tooldiff --git a/packages/eve/src/execution/cancelled-model-call-batch.ts b/packages/eve/src/execution/cancelled-model-call-batch.tsindex 975f3323d..07c612207 100644--- a/packages/eve/src/execution/cancelled-model-call-batch.ts+++ b/packages/eve/src/execution/cancelled-model-call-batch.ts@@ -8,6 +8,7 @@ import type { DurableStepResult } from "#execution/next-driver-action.js";import { readRetainedBackgroundToolResult } from "#execution/tasks/parent/tool-execution.js";import type { HarnessSession, StepInput, StepResult } from "#harness/types.js";import { preserveSerializedInstrumentationState } from "#instrumentation/state.js";+import { preserveSerializedBackgroundTaskObservabilityState } from "#shared/serialized-observability-state.js";import { preserveSerializedAgentTraceState } from "#tracing/agent-trace-context-store.js";export interface CompletedModelCallCheckpoint {@@ -46,6 +47,11 @@ export async function createCancelledModelCallBatchResult(input: {...(backgroundTaskSession === undefined || backgroundTasks === undefined? {}: {+ backgroundTaskContext: preserveSerializedBackgroundTaskObservabilityState(+ input.beforeBatchContext,+ interruptedContext,+ backgroundTasks,+ ),backgroundTaskState: createDurableSessionState({ session: cancelledSession }),backgroundTasks,}),diff --git a/packages/eve/src/execution/next-driver-action.ts b/packages/eve/src/execution/next-driver-action.tsindex 2ed457345..4e1539e93 100644--- a/packages/eve/src/execution/next-driver-action.ts+++ b/packages/eve/src/execution/next-driver-action.ts@@ -17,6 +17,8 @@ import type { SettledTurn, StepResult } from "#harness/types.js";import type { TokenUsage } from "#shared/token-usage.js";interface DurableStepResultFields {+ /** Pre-step context plus only the observability continuation owned by background tasks. */+ readonly backgroundTaskContext?: Record<string, unknown>;readonly backgroundTaskState?: DurableSessionState;readonly backgroundTasks?: StepResult["backgroundTasks"];/** The guarded inline step deferred before mutating state. */diff --git a/packages/eve/src/execution/route-child-delivery.test.ts b/packages/eve/src/execution/route-child-delivery.test.tsindex 5e9ea6c73..0f3833d72 100644--- a/packages/eve/src/execution/route-child-delivery.test.ts+++ b/packages/eve/src/execution/route-child-delivery.test.ts@@ -5,7 +5,10 @@ import {emitRecordedTaskInputRequestStep,runProxySubagentEventStep,} from "#subagents/event-proxy-step.js";-import { recordTaskInputRequestStep } from "#execution/tasks/parent/hitl-proxy-steps.js";+import {+ recordTaskInputRequestStep,+ recordTerminalTaskViewsStep,+} from "#execution/tasks/parent/hitl-proxy-steps.js";import { acceptTaskAuthorizationEventStep } from "#execution/tools/subagent/accept-event-step.js";import { routeProxiedDeliverStep } from "#execution/proxied-deliver-step.js";import type { DurableSessionState } from "#execution/durable-session-store.js";@@ -18,6 +21,7 @@ vi.mock("#subagents/event-proxy-step.js", () => ({}));vi.mock("#execution/tasks/parent/hitl-proxy-steps.js", () => ({recordTaskInputRequestStep: vi.fn(),+ recordTerminalTaskViewsStep: vi.fn(),}));vi.mock("#execution/tools/subagent/accept-event-step.js", () => ({acceptTaskAuthorizationEventStep: vi.fn(),@@ -98,6 +102,42 @@ describe("task HITL delivery routing", () => {);});+ it("adopts instrumentation context returned with terminal task views", async () => {+ const recordedState = state(false);+ const view = {+ lastOutput: { data: "done", type: "result" as const },+ metadata: { kind: "tool", name: "publish" },+ status: "completed" as const,+ taskId: "task-1",+ };+ vi.mocked(recordTerminalTaskViewsStep).mockResolvedValue({+ serializedContext: { trace: "settled" },+ sessionState: recordedState,+ });++ const result = await routeDeliverToChildren({+ delivery: {+ kind: "deliver",+ payloads: [{ task: { views: [view] } }],+ },+ parentWritable: new WritableStream<Uint8Array>(),+ serializedContext: { trace: "open" },+ sessionState: state(false),+ });++ expect(recordTerminalTaskViewsStep).toHaveBeenCalledWith({+ serializedContext: { trace: "open" },+ sessionState: state(false),+ views: [view],+ });+ expect(result).toEqual({+ kind: "continue",+ remainder: undefined,+ serializedContext: { trace: "settled" },+ sessionState: recordedState,+ });+ });+it("drops an unowned task envelope before it can reach the parent model", async () => {vi.mocked(recordTaskInputRequestStep).mockResolvedValue({accepted: false,diff --git a/packages/eve/src/execution/route-child-delivery.ts b/packages/eve/src/execution/route-child-delivery.tsindex 51b48136f..e910036cb 100644--- a/packages/eve/src/execution/route-child-delivery.ts+++ b/packages/eve/src/execution/route-child-delivery.ts@@ -85,10 +85,13 @@ export async function routeDeliverToChildren(input: {// and is enqueued before the task's terminal view. Preserve that ordering// when several task deliveries are coalesced into one parent turn.if ((payload.task?.views?.length ?? 0) > 0) {- sessionState = await recordTerminalTaskViewsStep({+ const recorded = await recordTerminalTaskViewsStep({+ serializedContext,sessionState,views: payload.task?.views ?? [],});+ serializedContext = recorded.serializedContext;+ sessionState = recorded.sessionState;}const ordinaryPayloads: DeliverPayload[] = [];diff --git a/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.test.ts b/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.test.tsindex bf577aae9..48d9ebb55 100644--- a/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.test.ts+++ b/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.test.ts@@ -1,18 +1,33 @@import { beforeEach, describe, expect, it, vi } from "vitest";+import { ContextContainer } from "#context/container.js";+import { serializeContext } from "#context/serialize.js";import { readDurableSession } from "#execution/durable-session-store.js";import {recordTerminalTaskViewsStep,recordTaskInputRequestStep,} from "#execution/tasks/parent/hitl-proxy-steps.js";import { readLatestTaskView } from "#execution/tasks/parent/run-parent.js";+import { bindSessionInstrumentation } from "#instrumentation/runtime.js";+import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";+import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";import { getAgentHandleStore, setAgentHandleStore } from "#subagents/handles/store.js";import { getProxyInputRequests } from "#harness/proxy-input-requests.js";import { getSessionTaskIndex } from "#tasks/session-index.js";+const flushInstrumentation = vi.hoisted(() => vi.fn());+const publishBackgroundTaskSettlements = vi.hoisted(() => vi.fn());+vi.mock("#execution/durable-session-store.js", () => ({ readDurableSession: vi.fn() }));vi.mock("#execution/tasks/parent/run-parent.js", () => ({ readLatestTaskView: vi.fn() }));-vi.mock("#shared/input.js", () => ({+vi.mock("#instrumentation/runtime.js", () => ({+ bindSessionInstrumentation: vi.fn(),+}));+vi.mock("#runtime/sessions/compiled-agent-cache.js", () => ({+ getCompiledRuntimeAgentBundle: vi.fn(),+}));+vi.mock("#shared/input.js", async (importOriginal) => ({+ ...(await importOriginal<typeof import("#shared/input.js")>()),isInputRequest: vi.fn((value: unknown) =>typeof value === "object" &&@@ -173,6 +188,14 @@ describe("recordTaskInputRequestStep", () => {});describe("recordTerminalTaskViewsStep", () => {+ beforeEach(() => {+ vi.resetAllMocks();+ vi.mocked(bindSessionInstrumentation).mockReturnValue({+ flush: flushInstrumentation,+ publishBackgroundTaskSettlements,+ } as never);+ });+it("caches an owned terminal view and releases the task's agent lease", async () => {vi.mocked(readDurableSession).mockResolvedValue({agent: { system: "" },@@ -218,12 +241,74 @@ describe("recordTerminalTaskViewsStep", () => {taskId: "task-1",};- const result = await recordTerminalTaskViewsStep({ sessionState, views: [view] });- const state = result.snapshot?.session.state;+ const result = await recordTerminalTaskViewsStep({+ serializedContext: {},+ sessionState,+ views: [view],+ });+ const state = result.sessionState.snapshot?.session.state;expect(getSessionTaskIndex(state)[0]?.terminalView).toEqual(view);expect(getAgentHandleStore(state)?.handles).toEqual([expect.objectContaining({ phase: "available" }),]);+ expect(result.serializedContext).toEqual({});+ });++ it("settles instrumentation from an accepted terminal task view", async () => {+ const bundle = {+ compiledArtifactsSource: { kind: "bundled" },+ nodeId: "__root__",+ turnAgent: { id: "parent-agent" },+ } as never;+ vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(bundle);+ const context = new ContextContainer();+ context.set(BundleKey, bundle);+ const serializedContext = serializeContext(context);+ vi.mocked(readDurableSession).mockResolvedValue({+ agent: { system: "" },+ continuationToken: "parent-token",+ history: [],+ sessionId: "parent-session",+ state: {+ "eve.tasks": {+ tasks: [+ {+ createdByTurnId: "turn-1",+ metadata: { kind: "tool", name: "export" },+ taskId: "task-1",+ taskInboxToken: "task-token",+ taskRunId: "task-run",+ },+ ],+ version: 2,+ },+ },+ });+ const view = {+ lastOutput: { data: "done", type: "result" as const },+ metadata: { kind: "tool", name: "export" },+ status: "completed" as const,+ taskId: "task-1",+ };++ const result = await recordTerminalTaskViewsStep({+ serializedContext,+ sessionState,+ views: [view],+ });++ expect(bindSessionInstrumentation).toHaveBeenCalledWith({+ agentName: "parent-agent",+ ctx: expect.any(ContextContainer),+ rootSessionId: "parent-session",+ sessionId: "parent-session",+ });+ expect(publishBackgroundTaskSettlements).toHaveBeenCalledWith({+ acceptedAtMs: expect.any(Number),+ views: [view],+ });+ expect(flushInstrumentation).toHaveBeenCalledOnce();+ expect(result.serializedContext).not.toBe(serializedContext);});});diff --git a/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.ts b/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.tsindex e67aa1fa3..5ef2e907f 100644--- a/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.ts+++ b/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.ts@@ -1,3 +1,5 @@+import { contextStorage } from "#context/container.js";+import { deserializeContext, serializeContext } from "#context/serialize.js";import { type DurableSessionState, readDurableSession } from "#execution/durable-session-store.js";import { readLatestTaskView } from "#execution/tasks/parent/run-parent.js";import { createTaskInputCapabilityToken } from "#execution/task-input-capability.js";@@ -7,6 +9,9 @@ import {upsertProxyInputRequestState,type ProxyInputRequest,} from "#harness/proxy-input-requests.js";+import { bindSessionInstrumentation } from "#instrumentation/runtime.js";+import { createLogger } from "#internal/logging.js";+import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";import { isInputRequest } from "#shared/input.js";import { getAgentHandleStore } from "#subagents/handles/store.js";import { applyTaskAgentHandleCommand } from "#subagents/handles/transitions.js";@@ -14,6 +19,8 @@ import { createEveTaskInputRoutePath } from "#protocol/routes.js";import { cacheTerminalTaskView, findSessionTaskEntry } from "#tasks/session-index.js";import type { TaskInputRequestDelivery, TaskView } from "#tasks/types.js";+const log = createLogger("execution.tasks.parent");+/** Validates and records a generic task-owned workflow request. */export async function recordTaskInputRequestStep(input: {readonly request: TaskInputRequestDelivery;@@ -100,27 +107,79 @@ export async function recordTaskInputRequestStep(input: {/** Caches terminal task views before their workflow runs expire. */export async function recordTerminalTaskViewsStep(input: {+ readonly serializedContext: Record<string, unknown>;readonly sessionState: DurableSessionState;readonly views: readonly TaskView[];-}): Promise<DurableSessionState> {+}): Promise<{+ readonly serializedContext: Record<string, unknown>;+ readonly sessionState: DurableSessionState;+}> {"use step";const durableSession = await readDurableSession(input.sessionState);let session = durableSession;+ const acceptedViews: TaskView[] = [];for (const view of input.views) {if (findSessionTaskEntry(session.state, view.taskId) === undefined) continue;const state = cacheTerminalTaskView(session.state, view);if (state !== session.state) session = { ...session, state };+ acceptedViews.push(view);session = applyTaskAgentHandleCommand(session, {kind: "release-owner",ownerId: view.taskId,}).session;}- if (session === durableSession) return input.sessionState;- return {- ...input.sessionState,- snapshot: {- session,- version: input.sessionState.version,- },- };+ const serializedContext = await settleBackgroundTaskActions({+ serializedContext: input.serializedContext,+ session,+ views: acceptedViews,+ });+ const sessionState =+ session === durableSession+ ? input.sessionState+ : {+ ...input.sessionState,+ snapshot: {+ session,+ version: input.sessionState.version,+ },+ };+ return { serializedContext, sessionState };+}++async function settleBackgroundTaskActions(input: {+ readonly serializedContext: Record<string, unknown>;+ readonly session: Awaited<ReturnType<typeof readDurableSession>>;+ readonly views: readonly TaskView[];+}): Promise<Record<string, unknown>> {+ if (input.views.length === 0) return input.serializedContext;+ try {+ const ctx = await deserializeContext(input.serializedContext);+ const bundle = ctx.get(BundleKey);+ if (bundle === undefined) return input.serializedContext;+ const instrumentation = bindSessionInstrumentation({+ agentName: bundle.turnAgent.id,+ ctx,+ rootSessionId: input.session.rootSessionId ?? input.session.sessionId,+ sessionId: input.session.sessionId,+ });+ if (instrumentation === undefined) return input.serializedContext;+ try {+ await contextStorage.run(ctx, () =>+ instrumentation.publishBackgroundTaskSettlements({+ acceptedAtMs: Date.now(),+ views: input.views,+ }),+ );+ } finally {+ await instrumentation.flush();+ }+ return serializeContext(ctx);+ } catch (error) {+ log.warn("failed to settle background task instrumentation", {+ error,+ sessionId: input.session.sessionId,+ taskIds: input.views.map((view) => view.taskId),+ });+ return input.serializedContext;+ }}diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.ts b/packages/eve/src/execution/tasks/parent/tool-execution.tsindex 0716e708f..14cc5d339 100644--- a/packages/eve/src/execution/tasks/parent/tool-execution.ts+++ b/packages/eve/src/execution/tasks/parent/tool-execution.ts@@ -55,6 +55,7 @@ import { cancelBackgroundAgentTask } from "#execution/tools/subagent/task-cancelconst IN_PROCESS_WORKFLOW_EXECUTOR = { data: {}, kind: "workflow-task" } as const;interface BackgroundToolExecutionRecord {+ readonly callId: string;claim?: {readonly operationId: string;readonly taskId: string;@@ -248,16 +249,21 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {private resultFields(): BackgroundToolStepResult | undefined {const tasks = this.records.flatMap((record) =>- record.settled && record.task !== undefined ? [record.task] : [],+ record.settled && record.task !== undefined+ ? [+ {+ callId: record.callId,+ taskInboxToken: record.task.taskInboxToken,+ taskId: record.task.taskId,+ taskRunId: record.task.taskRunId,+ },+ ]+ : [],);if (tasks.length === 0 && !this.agentHandlesChanged) return undefined;return {backgroundTaskSession: this.apply(this.initialSession),- backgroundTasks: tasks.map(({ taskInboxToken, taskId, taskRunId }) => ({- taskInboxToken,- taskId,- taskRunId,- })),+ backgroundTasks: tasks,};}@@ -267,7 +273,10 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {readonly options: ToolExecuteOptions;readonly toolInput: unknown;}): Promise<unknown> {- const record: BackgroundToolExecutionRecord = { settled: false };+ const record: BackgroundToolExecutionRecord = {+ callId: input.options.toolCallId,+ settled: false,+ };this.records.push(record);const emission = getHarnessEmissionState(this.initialSession.state);const ctx = loadContext();diff --git a/packages/eve/src/execution/turn-workflow.test.ts b/packages/eve/src/execution/turn-workflow.test.tsindex 9e26ee219..693bf8fea 100644--- a/packages/eve/src/execution/turn-workflow.test.ts+++ b/packages/eve/src/execution/turn-workflow.test.ts@@ -15,6 +15,7 @@ import {type TurnWorkflowInput,} from "#execution/durable-session-migrations/turn-workflow.js";import { routeDeliverToChildren } from "#execution/route-child-delivery.js";+import { TurnExecutionCursor } from "#execution/turn-execution-cursor.js";import { turnStep } from "#execution/workflow-steps.js";import { AGENT_HANDLES_STATE_KEY } from "#subagents/handles/store.js";import type { HarnessSession } from "#harness/types.js";@@ -426,6 +427,13 @@ describe("turnWorkflow", () => {it("commits and releases background tasks before settling a cancelled turn", async () => {const initialState = createSessionState({ continuationToken: "http:parent" });const backgroundState = createSessionState({ continuationToken: "http:parent:background" });+ const backgroundContext = {+ "eve.harness.agentTrace": { actions: { "action-1": {} }, sessions: {}, turns: {} },+ "eve.harness.instrumentationActionScopes": {+ "action-1": { scope: { turnId: "turn-1" }, taskId: "task-1" },+ },+ "eve.harness.instrumentationState": { "sink\0action-1": { value: "open" } },+ };const backgroundTasks = [{taskId: "task-1",@@ -433,12 +441,14 @@ describe("turnWorkflow", () => {taskRunId: "task-run-1",},];+ const adopt = vi.spyOn(TurnExecutionCursor.prototype, "adopt");installInbox([]);vi.mocked(turnStep).mockResolvedValueOnce({action: "cancelled",+ backgroundTaskContext: { ...backgroundContext, state: "start" },backgroundTaskState: backgroundState,backgroundTasks,- serializedContext: { state: "cancelled" },+ serializedContext: { ...backgroundContext, state: "cancelled" },sessionState: initialState,});@@ -450,10 +460,15 @@ describe("turnWorkflow", () => {await turnWorkflow(input);expect(acknowledgeDelegatedTasksStep).toHaveBeenCalledWith({ tasks: backgroundTasks });+ expect(adopt.mock.calls[0]?.[0]).toEqual({+ serializedContext: { ...backgroundContext, state: "start" },+ sessionState: backgroundState,+ });expect(cancelDescendantTurnsStep).toHaveBeenCalledWith({- serializedContext: { state: "cancelled" },+ serializedContext: { ...backgroundContext, state: "cancelled" },sessionState: backgroundState,});+ adopt.mockRestore();});it("checkpoints a durable turn step that finishes as cancellation arrives", async () => {@@ -496,6 +511,65 @@ describe("turnWorkflow", () => {);});+ it("checkpoints background task observability when cancellation arrives after a step", async () => {+ const sessionState = createSessionState();+ const backgroundState = createSessionState({ continuationToken: "http:background" });+ const backgroundTasks = [+ {+ taskId: "task-1",+ taskInboxToken: "task-inbox-1",+ taskRunId: "task-run-1",+ },+ ];+ const backgroundContext = {+ "eve.harness.agentTrace": { actions: { "action-1": {} }, sessions: {}, turns: {} },+ "eve.harness.instrumentationActionScopes": {+ "action-1": { scope: { turnId: "turn-1" }, taskId: "task-1" },+ },+ };+ const completedContext = { ...backgroundContext, state: "completed" };+ installInbox([], { cancelPayloads: [{}] });+ vi.mocked(turnStep).mockImplementationOnce(async (stepInput) => {+ await vi.waitFor(() => expect(stepInput.abortSignal?.aborted).toBe(true));+ return {+ action: "done",+ backgroundTaskContext: { ...backgroundContext, state: "start" },+ backgroundTaskState: backgroundState,+ backgroundTasks,+ output: "must not complete",+ serializedContext: completedContext,+ sessionState,+ };+ });++ const { input } = createInput({+ driverCapabilities: { cancelledTurnSettle: true, turnInbox: true },+ sessionState,+ });+ await turnWorkflow(input);++ expect(cancelDescendantTurnsStep).toHaveBeenCalledWith({+ serializedContext: completedContext,+ sessionState: backgroundState,+ });+ expect(resumeHookMock).toHaveBeenCalledWith("turn-token", {+ action: {+ cancelled: true,+ kind: "park",+ serializedContext: completedContext,+ sessionState: backgroundState,+ },+ kind: "turn-result",+ });+ expect(acknowledgeDelegatedTasksStep).toHaveBeenCalledWith({ tasks: backgroundTasks });+ expect(resumeHookMock).not.toHaveBeenCalledWith(+ "turn-token",+ expect.objectContaining({+ action: expect.objectContaining({ kind: "done" }),+ }),+ );+ });+it("runs uncancellable when the session cancel token is claimed by another run", async () => {const sessionState = createSessionState();installInbox([], { cancelConflict: { runId: "wrun_stale_prior_turn" } });diff --git a/packages/eve/src/execution/turn-workflow.ts b/packages/eve/src/execution/turn-workflow.tsindex 68710bf54..7cce16c55 100644--- a/packages/eve/src/execution/turn-workflow.ts+++ b/packages/eve/src/execution/turn-workflow.ts@@ -143,7 +143,7 @@ export async function runTurnOwnedWorkflow(throw new Error("Background tasks were returned without their committed session state.");}await cursor.adopt({- serializedContext: beforeStep.serializedContext,+ serializedContext: result.backgroundTaskContext ?? beforeStep.serializedContext,sessionState: result.backgroundTaskState,});await acknowledgeDelegatedTasksStep({ tasks: result.backgroundTasks ?? [] });diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.tsindex 802b012dc..ac8d8a193 100644--- a/packages/eve/src/execution/workflow-steps.ts+++ b/packages/eve/src/execution/workflow-steps.ts@@ -41,6 +41,7 @@ import {} from "#harness/emission.js";import { bindSessionInstrumentation } from "#instrumentation/runtime.js";import { RuntimeActionSettlementTimesKey } from "#harness/runtime-action-settlement-state.js";+import { preserveSerializedBackgroundTaskObservabilityState } from "#shared/serialized-observability-state.js";import * as agentTraceState from "#tracing/agent-trace-context-store.js";import { matchAuthorizationCallbacks } from "#execution/authorization-callback-match.js";import { isTurnCancellation, throwIfTurnAborted } from "#harness/turn-cancellation.js";@@ -82,7 +83,10 @@ import {resolveInitiatingTaskContext,resolveTaskDeliveryContext,} from "#tasks/delivery-context.js";-import { runBackgroundStep } from "#execution/tasks/parent/tool-execution.js";+import {+ readRetainedBackgroundToolResult,+ runBackgroundStep,+} from "#execution/tasks/parent/tool-execution.js";import { TASK_UPDATE_SESSION_INSTRUCTION } from "#tools/framework/task-update.js";import { prepareWorkflowPreambleTrace } from "#execution/workflow-trace-context.js";import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";@@ -580,6 +584,8 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResuthrow error;}writer.releaseLock();+ const retained = readRetainedBackgroundToolResult(ctx);+ instrumentation?.rememberBackgroundTasks(retained?.backgroundTasks ?? []);return createCancelledModelCallBatchResult({beforeBatchContext: input.serializedContext,checkpoint: completedModelCall,@@ -589,6 +595,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu});}+ instrumentation?.rememberBackgroundTasks(stepResult.backgroundTasks ?? []);// Re-stamp if a handler called `session.continuation.rekey(...)` (eg. Slack auto-anchor).const rekeyed = reconcileSessionContinuationToken(ctx, stepResult.session);agentTraceState.pruneAgentTraceState(ctx, rekeyed.sessionId, rekeyed.state);@@ -600,6 +607,11 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResustepResult.backgroundTasks === undefined || stepResult.backgroundTaskSession === undefined? {}: {+ backgroundTaskContext: preserveSerializedBackgroundTaskObservabilityState(+ input.serializedContext,+ nextSerializedContext,+ stepResult.backgroundTasks,+ ),backgroundTaskState: createDurableSessionState({session: stepResult.backgroundTaskSession,}),diff --git a/packages/eve/src/harness/types.ts b/packages/eve/src/harness/types.tsindex e778f9b70..5987fc37a 100644--- a/packages/eve/src/harness/types.ts+++ b/packages/eve/src/harness/types.ts@@ -222,6 +222,7 @@ export interface StepResult {readonly backgroundTaskSession?: HarnessSession;/** Durable tasks started by background tools and awaiting the parent commit barrier. */readonly backgroundTasks?: readonly {+ readonly callId?: string;readonly taskInboxToken: string;readonly taskId: string;readonly taskRunId: string;diff --git a/packages/eve/src/instrumentation/background-task-runtime.ts b/packages/eve/src/instrumentation/background-task-runtime.tsnew file mode 100644index 000000000..ec282f9f5--- /dev/null+++ b/packages/eve/src/instrumentation/background-task-runtime.ts@@ -0,0 +1,37 @@+import { contextStorage, type ContextContainer } from "#context/container.js";+import type { InstrumentationHooks } from "#instrumentation/lifecycle.js";+import { publishBackgroundTaskSettlements } from "#instrumentation/native-events.js";+import { rememberInstrumentationBackgroundTaskForCall } from "#instrumentation/state.js";+import type { TaskView } from "#tasks/types.js";++export interface BackgroundTaskInstrumentation {+ readonly publishBackgroundTaskSettlements: (input: {+ readonly acceptedAtMs?: number;+ readonly views: readonly TaskView[];+ }) => Promise<void>;+ readonly rememberBackgroundTasks: (+ tasks: readonly { readonly callId?: string; readonly taskId: string }[],+ ) => void;+}++export function createBackgroundTaskInstrumentation(input: {+ readonly ctx: ContextContainer;+ readonly hooks: () => InstrumentationHooks;+ readonly sessionId: string;+}): BackgroundTaskInstrumentation {+ return {+ publishBackgroundTaskSettlements: (settlements) =>+ publishBackgroundTaskSettlements({+ ...settlements,+ hooks: input.hooks(),+ }),+ rememberBackgroundTasks: (tasks) => {+ contextStorage.run(input.ctx, () => {+ for (const task of tasks) {+ if (task.callId === undefined) continue;+ rememberInstrumentationBackgroundTaskForCall(input.sessionId, task.callId, task.taskId);+ }+ });+ },+ };+}diff --git a/packages/eve/src/instrumentation/lifecycle.test.ts b/packages/eve/src/instrumentation/lifecycle.test.tsindex 6cd61cc48..1e9344fcd 100644--- a/packages/eve/src/instrumentation/lifecycle.test.ts+++ b/packages/eve/src/instrumentation/lifecycle.test.ts@@ -21,6 +21,8 @@ import {findInstrumentationActionScopeForCall,instrumentationStateSlot,rememberInstrumentationActionScope,+ rememberInstrumentationBackgroundTask,+ takeInstrumentationActionScopeForTask,} from "#instrumentation/state.js";const { logDebug, logWarn } = vi.hoisted(() => ({ logDebug: vi.fn(), logWarn: vi.fn() }));@@ -312,6 +314,55 @@ describe("provider state lifecycle", () => {type: "action.failed",});});++ it("keeps an admitted background action open when its initiating turn is cancelled", async () => {+ const actionKey = actionIdempotencyKey(scope.sessionId, scope.turnId, "call-1");+ const completed = vi.fn();+ const failed = vi.fn();+ const hooks = createInstrumentationHooks([+ {+ events: {+ "action.completed": completed,+ "action.failed": failed,+ "action.started": (_event, ctx) => ctx.state.set("open"),+ },+ name: "sink",+ },+ ]);+ await contextStorage.run(new ContextContainer(), async () => {+ rememberInstrumentationActionScope(actionKey, scope);+ await hooks.publish({+ callId: "call-1",+ idempotencyKey: actionKey,+ input: {},+ kind: "tool-call",+ name: "tool",+ scope,+ type: "action.started",+ });+ rememberInstrumentationBackgroundTask("task-1", { idempotencyKey: actionKey, scope });+ await hooks.publish({+ idempotencyKey: turnIdempotencyKey(scope.sessionId, scope.turnId),+ sessionId: scope.sessionId,+ turnId: scope.turnId,+ type: "turn.cancelled",+ });++ expect(failed).not.toHaveBeenCalled();+ expect(instrumentationStateSlot("sink", actionKey).get()).toBe("open");+ const correlation = takeInstrumentationActionScopeForTask("task-1");+ expect(correlation).toEqual({ idempotencyKey: actionKey, scope });+ await hooks.publish({+ idempotencyKey: correlation!.idempotencyKey,+ outcome: "completed",+ output: { output: "done", type: "result" },+ scope: correlation!.scope,+ type: "action.completed",+ });+ expect(instrumentationStateSlot("sink", actionKey).get()).toBeUndefined();+ });+ expect(completed).toHaveBeenCalledOnce();+ });});describe("provider handler deadlines", () => {diff --git a/packages/eve/src/instrumentation/native-events-background-tasks.test.ts b/packages/eve/src/instrumentation/native-events-background-tasks.test.tsnew file mode 100644index 000000000..285206ed5--- /dev/null+++ b/packages/eve/src/instrumentation/native-events-background-tasks.test.ts@@ -0,0 +1,173 @@+import { describe, expect, it } from "vitest";++import { ContextContainer, contextStorage } from "#context/container.js";+import { deserializeContext, serializeContext } from "#context/serialize.js";+import type {+ InstrumentationAttemptScope,+ InstrumentationEvent,+ InstrumentationHooks,+} from "#instrumentation/lifecycle.js";+import { actionIdempotencyKey } from "#instrumentation/lifecycle.js";+import {+ createInstrumentationHandleEvent,+ publishBackgroundTaskSettlements,+} from "#instrumentation/native-events.js";+import { rememberInstrumentationBackgroundTaskForCall } from "#instrumentation/state.js";+import { createActionResultEvent, createActionsRequestedEvent } from "#protocol/message.js";+import { preserveSerializedBackgroundTaskObservabilityState } from "#shared/serialized-observability-state.js";+import { deriveTaskId } from "#tasks/task-id.js";++const scope: InstrumentationAttemptScope = {+ attemptId: "session-1:turn-1:0:0",+ attemptIndex: 0,+ sessionId: "session-1",+ stepIndex: 0,+ turnId: "turn-1",+};++function recordingHooks(events: InstrumentationEvent[]): InstrumentationHooks {+ return {+ capturesContent: true,+ publish: async (event) => void events.push(event),+ };+}++async function emitBackgroundReceipt(+ context: ContextContainer,+ events: InstrumentationEvent[],+): Promise<string> {+ const taskId = deriveTaskId({+ callId: "workflow-1",+ parentSessionId: scope.sessionId,+ parentTurnId: scope.turnId,+ });+ await contextStorage.run(context, async () => {+ const handleEvent = createInstrumentationHandleEvent({+ getAttemptScope: () => scope,+ handleEvent: async () => {},+ hooks: recordingHooks(events),+ sessionId: scope.sessionId,+ })!;+ await handleEvent(+ createActionsRequestedEvent({+ actions: [+ {+ callId: "workflow-1",+ input: { report: "weekly" },+ kind: "workflow-tool-call",+ toolName: "publish",+ workflowId: "publish-workflow",+ },+ ],+ sequence: 0,+ stepIndex: 0,+ turnId: scope.turnId,+ }),+ );+ await handleEvent(+ createActionResultEvent({+ result: {+ callId: "workflow-1",+ kind: "tool-result",+ output: { status: "working", taskId },+ toolName: "publish",+ },+ sequence: 0,+ stepIndex: 0,+ turnId: scope.turnId,+ }),+ );+ rememberInstrumentationBackgroundTaskForCall(scope.sessionId, "workflow-1", taskId);+ });+ return taskId;+}++describe("background task action instrumentation", () => {+ it("keeps the action open until its terminal task view arrives", async () => {+ const events: InstrumentationEvent[] = [];+ const context = new ContextContainer();+ const taskId = await emitBackgroundReceipt(context, events);+ expect(events.map((event) => event.type)).toEqual(["action.started"]);++ const restored = await deserializeContext(+ preserveSerializedBackgroundTaskObservabilityState({}, serializeContext(context), [+ { taskId },+ ]),+ );+ await contextStorage.run(restored, async () => {+ await publishBackgroundTaskSettlements({+ acceptedAtMs: 1_234,+ hooks: recordingHooks(events),+ views: [+ {+ lastOutput: { data: { reportId: "report-1" }, type: "result" },+ metadata: { kind: "tool", name: "publish" },+ status: "completed",+ taskId,+ usage: {+ cacheReadTokens: 3,+ cacheWriteTokens: 4,+ inputTokens: 10,+ outputTokens: 5,+ },+ },+ ],+ });+ });++ expect(events[1]).toEqual({+ acceptedAtMs: 1_234,+ idempotencyKey: actionIdempotencyKey(scope.sessionId, scope.turnId, "workflow-1"),+ outcome: "completed",+ output: { output: { reportId: "report-1" }, type: "result" },+ scope,+ type: "action.completed",+ usage: {+ inputTokenDetails: { cacheReadTokens: 3, cacheWriteTokens: 4 },+ inputTokens: 10,+ outputTokens: 5,+ },+ });+ });++ it.each([+ {+ error: "publish failed",+ errorCode: "BACKGROUND_TASK_FAILED",+ status: "failed" as const,+ view: {+ lastOutput: { data: "publish failed", type: "error" as const },+ metadata: { kind: "tool", name: "publish" },+ status: "failed" as const,+ },+ },+ {+ error: expect.any(Error),+ errorCode: "BACKGROUND_TASK_CANCELLED",+ status: "cancelled" as const,+ view: {+ metadata: { kind: "tool", name: "publish" },+ status: "cancelled" as const,+ },+ },+ ])("settles the action when its task is $status", async (input) => {+ const events: InstrumentationEvent[] = [];+ const context = new ContextContainer();+ const taskId = await emitBackgroundReceipt(context, events);+ await contextStorage.run(context, async () => {+ await publishBackgroundTaskSettlements({+ acceptedAtMs: 1_234,+ hooks: recordingHooks(events),+ views: [{ ...input.view, taskId }],+ });+ });++ expect(events[1]).toMatchObject({+ acceptedAtMs: 1_234,+ error: input.error,+ errorCode: input.errorCode,+ outcome: input.status,+ type: "action.failed",+ });+ });+});diff --git a/packages/eve/src/instrumentation/native-events.ts b/packages/eve/src/instrumentation/native-events.tsindex 5deb31ca9..27154f245 100644--- a/packages/eve/src/instrumentation/native-events.ts+++ b/packages/eve/src/instrumentation/native-events.ts@@ -20,9 +20,11 @@ import {turnIdempotencyKey,} from "#instrumentation/lifecycle.js";import {+ findInstrumentationActionScopeForCall,rememberInstrumentationActionScope,rememberInstrumentationInputScope,takeInstrumentationActionScopeForCall,+ takeInstrumentationActionScopeForTask,takeInstrumentationInputScope,} from "#instrumentation/state.js";import type { ResolvedInputBatch } from "#harness/input-requests.js";@@ -30,6 +32,8 @@ import { RuntimeActionSettlementTimesKey } from "#harness/runtime-action-settlemimport type { HandleEventFn } from "#harness/types.js";import type { RuntimeActionRequest, RuntimeActionResult } from "#shared/action-types.js";import type { ChannelAudience } from "#shared/channel-audience.js";+import { deriveTaskId } from "#tasks/task-id.js";+import type { TaskUsage, TaskView } from "#tasks/types.js";export interface CreateInstrumentationHandleEventInput {readonly agentName?: string;@@ -219,11 +223,16 @@ async function publishActionTerminal(input: CreateInstrumentationHandleEventInput,hooks: InstrumentationHooks,): Promise<void> {- const correlation = takeInstrumentationActionScopeForCall(+ const correlation = findInstrumentationActionScopeForCall(input.sessionId,event.data.result.callId,);if (correlation === undefined) return;+ const backgroundTask = readBackgroundTaskReceipt(event.data.result, correlation);+ if (event.data.status === "completed" && backgroundTask !== undefined) {+ return;+ }+ takeInstrumentationActionScopeForCall(input.sessionId, event.data.result.callId);const { idempotencyKey, scope } = correlation;const capturesOutputs = hooks.capturesOutputs ?? hooks.capturesContent;@@ -268,6 +277,85 @@ async function publishActionTerminal();}+/** Settles actions whose model-facing result was an admitted background-task receipt. */+export async function publishBackgroundTaskSettlements(input: {+ readonly acceptedAtMs?: number;+ readonly hooks: InstrumentationHooks;+ readonly views: readonly TaskView[];+}): Promise<void> {+ const capturesOutputs = input.hooks.capturesOutputs ?? input.hooks.capturesContent;+ const acceptedAtMs = input.acceptedAtMs ?? Date.now();+ for (const view of input.views) {+ if (view.status !== "completed" && view.status !== "failed" && view.status !== "cancelled") {+ continue;+ }+ const correlation = takeInstrumentationActionScopeForTask(view.taskId);+ if (correlation === undefined) continue;+ if (view.status === "completed") {+ await input.hooks.publish(+ Object.freeze({+ acceptedAtMs,+ idempotencyKey: correlation.idempotencyKey,+ outcome: "completed",+ output: Object.freeze(+ capturesOutputs ? { output: view.lastOutput.data, type: "result" } : { type: "result" },+ ),+ scope: correlation.scope,+ type: "action.completed",+ usage: instrumentationUsage(view.usage),+ }),+ );+ continue;+ }+ await input.hooks.publish(+ Object.freeze({+ acceptedAtMs,+ error:+ view.status === "failed"+ ? capturesOutputs+ ? view.lastOutput.data+ : undefined+ : new Error("The background task was cancelled."),+ errorCode:+ view.status === "failed" ? "BACKGROUND_TASK_FAILED" : "BACKGROUND_TASK_CANCELLED",+ idempotencyKey: correlation.idempotencyKey,+ outcome: view.status,+ scope: correlation.scope,+ type: "action.failed",+ } satisfies InstrumentationActionFailedEvent),+ );+ }+}++function readBackgroundTaskReceipt(+ result: RuntimeActionResult,+ correlation: { readonly scope: InstrumentationAttemptScope },+): { readonly taskId: string } | undefined {+ const output = result.output;+ if (typeof output !== "object" || output === null || Array.isArray(output)) return undefined;+ if (Reflect.get(output, "status") !== "working") return undefined;+ const taskId = Reflect.get(output, "taskId");+ if (typeof taskId !== "string") return undefined;+ const expectedTaskId = deriveTaskId({+ callId: result.callId,+ parentSessionId: correlation.scope.sessionId,+ parentTurnId: correlation.scope.turnId,+ });+ return taskId === expectedTaskId ? { taskId } : undefined;+}++function instrumentationUsage(usage: TaskUsage | undefined): InstrumentationUsage | undefined {+ if (usage === undefined) return undefined;+ return {+ inputTokenDetails: {+ cacheReadTokens: usage.cacheReadTokens,+ cacheWriteTokens: usage.cacheWriteTokens,+ },+ inputTokens: usage.inputTokens,+ outputTokens: usage.outputTokens,+ };+}+function actionUsage(result: RuntimeActionResult): InstrumentationUsage | undefined {if (result.kind !== "subagent-result" ||diff --git a/packages/eve/src/instrumentation/runtime.ts b/packages/eve/src/instrumentation/runtime.tsindex 4711169d9..9590ce096 100644--- a/packages/eve/src/instrumentation/runtime.ts+++ b/packages/eve/src/instrumentation/runtime.ts@@ -29,6 +29,10 @@ import {publishInputResolutions,type CreateInstrumentationHandleEventInput,} from "#instrumentation/native-events.js";+import {+ createBackgroundTaskInstrumentation,+ type BackgroundTaskInstrumentation,+} from "#instrumentation/background-task-runtime.js";import type { ResolvedInputBatch } from "#harness/input-requests.js";import type { HandleEventFn } from "#harness/types.js";import {@@ -179,7 +183,7 @@ export interface SessionInstrumentation {) => Promise<TResult>;}-export interface ExecutionInstrumentation {+export interface ExecutionInstrumentation extends BackgroundTaskInstrumentation {readonly createHandleEvent: (input: {readonly handleEvent?: HandleEventFn;readonly turnId?: string;@@ -470,6 +474,11 @@ export function bindInstrumentationRuntime(};};return {+ ...createBackgroundTaskInstrumentation({+ ctx,+ hooks: () => bindHooks(readSessionContext()),+ sessionId: boundSession.sessionId,+ }),createHandleEvent: (input) => {const sessionContext = readSessionContext();return createInstrumentationHandleEvent({diff --git a/packages/eve/src/instrumentation/state.test.ts b/packages/eve/src/instrumentation/state.test.tsindex 3672409b7..d34ca19f4 100644--- a/packages/eve/src/instrumentation/state.test.ts+++ b/packages/eve/src/instrumentation/state.test.ts@@ -8,14 +8,20 @@ import {} from "#instrumentation/lifecycle.js";import {abandonInstrumentationState,+ findInstrumentationActionScopeForCall,instrumentationStateSlot,isInstrumentationStateAbandoned,rememberInstrumentationActionScope,+ rememberInstrumentationBackgroundTaskForCall,releaseAllInstrumentationAttemptState,releaseAllInstrumentationState,+ releaseAllInstrumentationTurnState,+ takeInstrumentationActionScopeForTask,takeInstrumentationActionScopeForCall,+ takeInstrumentationActionScopes,} from "#instrumentation/state.js";import { preserveSerializedInstrumentationState } from "#instrumentation/state.js";+import { preserveSerializedBackgroundTaskObservabilityState } from "#shared/serialized-observability-state.js";describe("instrumentation state", () => {it("survives a serialized step boundary", async () => {@@ -73,6 +79,65 @@ describe("instrumentation state", () => {});});+ it("keeps a background action across turn cleanup until its task settles", async () => {+ const actionKey = actionIdempotencyKey("session-1", "turn-1", "call-1");+ const scope: InstrumentationAttemptScope = {+ attemptId: "session-1:turn-1:0:0",+ attemptIndex: 0,+ sessionId: "session-1",+ stepIndex: 0,+ turnId: "turn-1",+ };+ const context = new ContextContainer();+ await contextStorage.run(context, async () => {+ rememberInstrumentationActionScope(actionKey, scope);+ rememberInstrumentationBackgroundTaskForCall(scope.sessionId, "call-1", "task-1");+ instrumentationStateSlot("sink", actionKey, {+ sessionId: scope.sessionId,+ turnId: scope.turnId,+ }).set("open");+ });++ const serialized = await serializeContext(context);+ expect(serialized["eve.harness.instrumentationActionScopes"]).toEqual({+ [actionKey]: { scope, taskId: "task-1" },+ });+ expect(serialized).not.toHaveProperty("eve.harness.instrumentationBackgroundTasks");+ const restored = await deserializeContext(serialized);+ contextStorage.run(restored, () => {+ expect(takeInstrumentationActionScopes(scope.sessionId, scope.turnId)).toEqual([]);+ releaseAllInstrumentationTurnState(scope.sessionId, scope.turnId);+ expect(instrumentationStateSlot("sink", actionKey).get()).toBe("open");+ expect(findInstrumentationActionScopeForCall(scope.sessionId, "call-1")).toBeDefined();+ expect(takeInstrumentationActionScopeForTask("task-1")).toEqual({+ idempotencyKey: actionKey,+ scope,+ });+ expect(findInstrumentationActionScopeForCall(scope.sessionId, "call-1")).toBeUndefined();+ });+ });++ it("deserializes the previous scope-only action state", async () => {+ const scope: InstrumentationAttemptScope = {+ attemptId: "session-1:turn-1:0:0",+ attemptIndex: 0,+ sessionId: "session-1",+ stepIndex: 0,+ turnId: "turn-1",+ };+ const actionKey = actionIdempotencyKey(scope.sessionId, scope.turnId, "call-1");+ const restored = await deserializeContext({+ "eve.harness.instrumentationActionScopes": { [actionKey]: scope },+ });++ contextStorage.run(restored, () => {+ expect(findInstrumentationActionScopeForCall(scope.sessionId, "call-1")).toEqual({+ idempotencyKey: actionKey,+ scope,+ });+ });+ });+it("rejects values that cannot survive serialization", () => {contextStorage.run(new ContextContainer(), () => {expect(() => instrumentationStateSlot("sink", "turn:1").set(new Date() as never)).toThrow(@@ -134,6 +199,116 @@ describe("instrumentation state", () => {});});+ it("preserves only observability state owned by committed background tasks", () => {+ const existingAction = "action:session-1:turn-0:existing";+ const backgroundAction = "action:session-1:turn-1:background";+ const unrelatedAction = "action:session-1:turn-1:unrelated";+ const original = {+ authored: "original",+ "eve.activeChannelDeliveries": { existing: true },+ "eve.harness.agentTrace": {+ actionAnchors: { [existingAction]: { callId: "existing", trace: "existing" } },+ actions: { [existingAction]: { callId: "existing", trace: "existing" } },+ invocations: {+ "invocation-existing": {+ callId: "existing-child",+ parentActionCallId: "existing",+ },+ },+ sessions: { "session-1": { trace: "session" } },+ turns: { "session-1\0turn-0": { trace: "turn" } },+ },+ "eve.harness.instrumentationActionScopes": {+ [existingAction]: { scope: { turnId: "turn-0" }, taskId: "task-existing" },+ },+ "eve.harness.instrumentationInputScopes": { existing: { turnId: "turn-0" } },+ "eve.harness.instrumentationState": {+ [`sink\0${existingAction}`]: { value: "existing" },+ },+ };+ const completed = {+ authored: "completed",+ "eve.activeChannelDeliveries": { unrelated: true },+ "eve.harness.agentTrace": {+ actionAnchors: {+ [backgroundAction]: { callId: "background", trace: "background" },+ [unrelatedAction]: { callId: "unrelated", trace: "unrelated" },+ },+ actions: {+ [backgroundAction]: { callId: "background", trace: "background" },+ [unrelatedAction]: { callId: "unrelated", trace: "unrelated" },+ },+ invocations: {+ "invocation-background": {+ callId: "background-child",+ parentActionCallId: "background",+ },+ "invocation-background-nested": {+ callId: "background-grandchild",+ parentActionCallId: "background-child",+ },+ "invocation-unrelated": {+ callId: "unrelated-child",+ parentActionCallId: "unrelated",+ },+ },+ sessions: { "session-2": { trace: "unrelated" } },+ turns: { "session-1\0turn-1": { trace: "unrelated" } },+ },+ "eve.harness.instrumentationActionScopes": {+ [backgroundAction]: { scope: { turnId: "turn-1" }, taskId: "task-1" },+ [unrelatedAction]: { scope: { turnId: "turn-1" }, taskId: "task-2" },+ },+ "eve.harness.instrumentationInputScopes": { unrelated: { turnId: "turn-1" } },+ "eve.harness.instrumentationState": {+ [`sink\0${backgroundAction}`]: { value: "background" },+ [`sink\0${unrelatedAction}`]: { value: "unrelated" },+ },+ };++ expect(+ preserveSerializedBackgroundTaskObservabilityState(original, completed, [+ { taskId: "task-1" },+ ]),+ ).toEqual({+ ...original,+ "eve.harness.agentTrace": {+ actionAnchors: {+ [existingAction]: { callId: "existing", trace: "existing" },+ [backgroundAction]: { callId: "background", trace: "background" },+ },+ actions: {+ [existingAction]: { callId: "existing", trace: "existing" },+ [backgroundAction]: { callId: "background", trace: "background" },+ },+ invocations: {+ "invocation-existing": {+ callId: "existing-child",+ parentActionCallId: "existing",+ },+ "invocation-background": {+ callId: "background-child",+ parentActionCallId: "background",+ },+ "invocation-background-nested": {+ callId: "background-grandchild",+ parentActionCallId: "background-child",+ },+ },+ sessions: { "session-1": { trace: "session" } },+ turns: { "session-1\0turn-0": { trace: "turn" } },+ },+ "eve.harness.instrumentationActionScopes": {+ [existingAction]: { scope: { turnId: "turn-0" }, taskId: "task-existing" },+ [backgroundAction]: { scope: { turnId: "turn-1" }, taskId: "task-1" },+ },+ "eve.harness.instrumentationState": {+ [`sink\0${existingAction}`]: { value: "existing" },+ [`sink\0${backgroundAction}`]: { value: "background" },+ },+ });+ });+it("persists abandonment across serialization", async () => {const context = new ContextContainer();contextStorage.run(context, () => {diff --git a/packages/eve/src/instrumentation/state.ts b/packages/eve/src/instrumentation/state.tsindex 53a17d559..3faea97ce 100644--- a/packages/eve/src/instrumentation/state.ts+++ b/packages/eve/src/instrumentation/state.ts@@ -1,8 +1,10 @@import { contextStorage, loadContext } from "#context/container.js";import { ContextKey } from "#context/key.js";-import { ActiveChannelDeliveriesKey } from "#context/keys.js";import { type JsonValue, parseJsonValue } from "#shared/json.js";import type { InstrumentationAttemptScope } from "#instrumentation/lifecycle.js";+import { SERIALIZED_INSTRUMENTATION_STATE_KEYS } from "#shared/serialized-observability-state.js";++export { preserveSerializedInstrumentationState } from "#shared/serialized-observability-state.js";/*** What every provider has staged, flattened into one durable slot.@@ -26,6 +28,11 @@ export interface InstrumentationStateOwner {}type InstrumentationStateMap = Readonly<Record<string, InstrumentationStateRecord>>;+interface InstrumentationActionState {+ readonly scope: InstrumentationAttemptScope;+ readonly taskId?: string;+}+type InstrumentationActionStateMap = Readonly<Record<string, InstrumentationActionState>>;type InstrumentationScopeMap = Readonly<Record<string, InstrumentationAttemptScope>>;/**@@ -34,7 +41,7 @@ type InstrumentationScopeMap = Readonly<Record<string, InstrumentationAttemptSco* `action.completed` runs in another.*/const InstrumentationStateKey = new ContextKey<InstrumentationStateMap>(- "eve.harness.instrumentationState",+ SERIALIZED_INSTRUMENTATION_STATE_KEYS.providerState,{codec: {deserialize: deserializeState,@@ -43,18 +50,18 @@ const InstrumentationStateKey = new ContextKey<InstrumentationStateMap>(},);-const InstrumentationActionScopeKey = new ContextKey<InstrumentationScopeMap>(- "eve.harness.instrumentationActionScopes",+const InstrumentationActionStateKey = new ContextKey<InstrumentationActionStateMap>(+ SERIALIZED_INSTRUMENTATION_STATE_KEYS.actionScopes,{codec: {- deserialize: deserializeScopes,+ deserialize: deserializeActionStates,serialize: (state) => state,},},);const InstrumentationInputScopeKey = new ContextKey<InstrumentationScopeMap>(- "eve.harness.instrumentationInputScopes",+ SERIALIZED_INSTRUMENTATION_STATE_KEYS.inputScopes,{codec: {deserialize: deserializeScopes,@@ -63,24 +70,6 @@ const InstrumentationInputScopeKey = new ContextKey<InstrumentationScopeMap>(},);-/** Keeps only provider state needed to settle an interrupted operation. */-export function preserveSerializedInstrumentationState(- original: Record<string, unknown>,- interrupted: Record<string, unknown>,-): Record<string, unknown> {- let preserved = original;- for (const key of [- InstrumentationStateKey,- InstrumentationActionScopeKey,- InstrumentationInputScopeKey,- ActiveChannelDeliveriesKey,- ]) {- const state = interrupted[key.name];- if (state !== undefined) preserved = { ...preserved, [key.name]: state };- }- return preserved;-}-/** One provider's view of its own state for one operation. */export interface InstrumentationStateSlot {get(): JsonValue | undefined;@@ -174,9 +163,13 @@ export function releaseAllInstrumentationAttemptState(attemptId: string): void {}export function releaseAllInstrumentationTurnState(sessionId: string, turnId?: string): void {+ const protectedActions =+ turnId === undefined ? new Set<string>() : backgroundActionKeys(sessionId, turnId);releaseMatchingInstrumentationState(- (_key, record) =>- record.sessionId === sessionId && (turnId === undefined || record.turnId === turnId),+ (key, record) =>+ record.sessionId === sessionId &&+ (turnId === undefined || record.turnId === turnId) &&+ !protectedActions.has(instrumentationStateOperationId(key)),);}@@ -204,10 +197,13 @@ export function rememberInstrumentationActionScope(idempotencyKey: string,scope: InstrumentationAttemptScope,): void {- writeContextKey(InstrumentationActionScopeKey, (state) => ({- ...state,- [idempotencyKey]: scope,- }));+ writeContextKey(InstrumentationActionStateKey, (state) => {+ const taskId = state[idempotencyKey]?.taskId;+ return {+ ...state,+ [idempotencyKey]: taskId === undefined ? { scope } : { scope, taskId },+ };+ });}/** Remembers where a durable input request originated. */@@ -240,16 +236,40 @@ export interface InstrumentationActionCorrelation {readonly scope: InstrumentationAttemptScope;}+/** Binds an admitted background task to the action that started it. */+export function rememberInstrumentationBackgroundTask(+ taskId: string,+ correlation: InstrumentationActionCorrelation,+): void {+ writeContextKey(InstrumentationActionStateKey, (state) => ({+ ...state,+ [correlation.idempotencyKey]: {+ scope: state[correlation.idempotencyKey]?.scope ?? correlation.scope,+ taskId,+ },+ }));+}++/** Binds a background task when its executor admits the originating call. */+export function rememberInstrumentationBackgroundTaskForCall(+ sessionId: string,+ callId: string,+ taskId: string,+): void {+ const correlation = findInstrumentationActionScopeForCall(sessionId, callId);+ if (correlation !== undefined) rememberInstrumentationBackgroundTask(taskId, correlation);+}+export function findInstrumentationActionScopeForCall(sessionId: string,callId: string,): InstrumentationActionCorrelation | undefined {- const scopes = contextStorage.getStore()?.get(InstrumentationActionScopeKey);- if (scopes === undefined) return undefined;- for (const candidate of Object.values(scopes)) {- const idempotencyKey = `action:${sessionId}:${candidate.turnId}:${callId}`;- const scope = scopes[idempotencyKey];- if (scope !== undefined) return { idempotencyKey, scope };+ const actions = contextStorage.getStore()?.get(InstrumentationActionStateKey);+ if (actions === undefined) return undefined;+ for (const candidate of Object.values(actions)) {+ const idempotencyKey = `action:${sessionId}:${candidate.scope.turnId}:${callId}`;+ const action = actions[idempotencyKey];+ if (action !== undefined) return { idempotencyKey, scope: action.scope };}return undefined;}@@ -261,30 +281,42 @@ export function takeInstrumentationActionScopeForCall(): InstrumentationActionCorrelation | undefined {const correlation = findInstrumentationActionScopeForCall(sessionId, callId);if (correlation === undefined) return undefined;- writeContextKey(InstrumentationActionScopeKey, (state) => {- const next = { ...state };- delete next[correlation.idempotencyKey];- return next;- });+ releaseInstrumentationActionCorrelation(correlation.idempotencyKey);return correlation;}+/** Reads and releases the action correlation owned by a terminal background task. */+export function takeInstrumentationActionScopeForTask(+ taskId: string,+): InstrumentationActionCorrelation | undefined {+ const actions = contextStorage.getStore()?.get(InstrumentationActionStateKey);+ if (actions === undefined) return undefined;+ for (const [idempotencyKey, action] of Object.entries(actions)) {+ if (action.taskId !== taskId) continue;+ releaseInstrumentationActionCorrelation(idempotencyKey);+ return { idempotencyKey, scope: action.scope };+ }+ return undefined;+}+/** Takes every still-open action owned by one session or turn. */export function takeInstrumentationActionScopes(sessionId: string,turnId?: string,): readonly InstrumentationActionCorrelation[] {- const current = contextStorage.getStore()?.get(InstrumentationActionScopeKey);+ const current = contextStorage.getStore()?.get(InstrumentationActionStateKey);if (current === undefined) return [];const correlations = Object.entries(current).filter(- ([, scope]) =>- scope.sessionId === sessionId && (turnId === undefined || scope.turnId === turnId),+ ([, action]) =>+ action.scope.sessionId === sessionId &&+ (turnId === undefined || action.scope.turnId === turnId) &&+ (turnId === undefined || action.taskId === undefined),)- .map(([idempotencyKey, scope]) => ({ idempotencyKey, scope }));+ .map(([idempotencyKey, action]) => ({ idempotencyKey, scope: action.scope }));if (correlations.length === 0) return [];const keys = new Set(correlations.map((correlation) => correlation.idempotencyKey));- writeContextKey(InstrumentationActionScopeKey, (state) => {+ writeContextKey(InstrumentationActionStateKey, (state) => {const next = { ...state };for (const key of keys) delete next[key];return next;@@ -292,6 +324,28 @@ export function takeInstrumentationActionScopes(return correlations;}+function releaseInstrumentationActionCorrelation(idempotencyKey: string): void {+ writeContextKey(InstrumentationActionStateKey, (state) => {+ const next = { ...state };+ delete next[idempotencyKey];+ return next;+ });+}++function backgroundActionKeys(sessionId: string, turnId: string): ReadonlySet<string> {+ const actions = contextStorage.getStore()?.get(InstrumentationActionStateKey);+ if (actions === undefined) return new Set();+ return new Set(+ Object.entries(actions).flatMap(([idempotencyKey, action]) =>+ action.taskId !== undefined &&+ action.scope.sessionId === sessionId &&+ action.scope.turnId === turnId+ ? [idempotencyKey]+ : [],+ ),+ );+}+function writeSlot(state: InstrumentationStateMap,key: string,@@ -330,6 +384,10 @@ function stateKey(provider: string, idempotencyKey: string): string {return `${provider}\0${idempotencyKey}`;}+function instrumentationStateOperationId(key: string): string {+ return key.slice(key.indexOf("\0") + 1);+}+function deserializeState(data: unknown): InstrumentationStateMap {if (typeof data !== "object" || data === null || Array.isArray(data)) return {};const state: Record<string, InstrumentationStateRecord> = {};@@ -369,3 +427,21 @@ function deserializeScopes(data: unknown): InstrumentationScopeMap {if (typeof data !== "object" || data === null || Array.isArray(data)) return {};return data as InstrumentationScopeMap;}++function deserializeActionStates(data: unknown): InstrumentationActionStateMap {+ if (typeof data !== "object" || data === null || Array.isArray(data)) return {};+ const actions: Record<string, InstrumentationActionState> = {};+ for (const [idempotencyKey, value] of Object.entries(data)) {+ if (typeof value !== "object" || value === null || Array.isArray(value)) continue;+ const record = value as Record<string, unknown>;+ const scope =+ typeof record["scope"] === "object" &&+ record["scope"] !== null &&+ !Array.isArray(record["scope"])+ ? (record["scope"] as InstrumentationAttemptScope)+ : (value as InstrumentationAttemptScope);+ const taskId = typeof record["taskId"] === "string" ? record["taskId"] : undefined;+ actions[idempotencyKey] = taskId === undefined ? { scope } : { scope, taskId };+ }+ return actions;+}diff --git a/packages/eve/src/shared/serialized-observability-state.ts b/packages/eve/src/shared/serialized-observability-state.tsnew file mode 100644index 000000000..19b92c47b--- /dev/null+++ b/packages/eve/src/shared/serialized-observability-state.ts@@ -0,0 +1,150 @@+export const SERIALIZED_INSTRUMENTATION_STATE_KEYS = {+ activeChannelDeliveries: "eve.activeChannelDeliveries",+ actionScopes: "eve.harness.instrumentationActionScopes",+ inputScopes: "eve.harness.instrumentationInputScopes",+ providerState: "eve.harness.instrumentationState",+} as const;++const SERIALIZED_AGENT_TRACE_STATE_KEY = "eve.harness.agentTrace";++/** Keeps instrumentation state needed to settle operations opened by a discarded step. */+export function preserveSerializedInstrumentationState(+ original: Record<string, unknown>,+ interrupted: Record<string, unknown>,+): Record<string, unknown> {+ let preserved = original;+ for (const key of Object.values(SERIALIZED_INSTRUMENTATION_STATE_KEYS)) {+ const state = interrupted[key];+ if (state !== undefined) preserved = { ...preserved, [key]: state };+ }+ return preserved;+}++/** Keeps only the observability state a retained background task needs before readiness. */+export function preserveSerializedBackgroundTaskObservabilityState(+ original: Record<string, unknown>,+ completed: Record<string, unknown>,+ tasks: readonly { readonly taskId: string }[],+): Record<string, unknown> {+ const taskIds = new Set(tasks.map((task) => task.taskId));+ const completedActions = asRecord(completed[SERIALIZED_INSTRUMENTATION_STATE_KEYS.actionScopes]);+ const actions = Object.fromEntries(+ Object.entries(completedActions).filter(([, value]) => {+ const action = asRecord(value);+ return typeof action["taskId"] === "string" && taskIds.has(action["taskId"]);+ }),+ );+ const actionIds = new Set(Object.keys(actions));+ if (actionIds.size === 0) return original;++ let preserved = mergeSerializedRecord(+ original,+ SERIALIZED_INSTRUMENTATION_STATE_KEYS.actionScopes,+ actions,+ );+ const providerState = Object.fromEntries(+ Object.entries(asRecord(completed[SERIALIZED_INSTRUMENTATION_STATE_KEYS.providerState])).filter(+ ([key]) => {+ const separator = key.indexOf("\0");+ return separator >= 0 && actionIds.has(key.slice(separator + 1));+ },+ ),+ );+ preserved = mergeSerializedRecord(+ preserved,+ SERIALIZED_INSTRUMENTATION_STATE_KEYS.providerState,+ providerState,+ );++ const completedTrace = asRecord(completed[SERIALIZED_AGENT_TRACE_STATE_KEY]);+ const traceActionAnchors = selectEntries(completedTrace["actionAnchors"], actionIds);+ const traceActions = Object.fromEntries(+ Object.entries(asRecord(completedTrace["actions"])).filter(([key]) => actionIds.has(key)),+ );+ const retainedCallIds = new Set<string>();+ for (const value of [...Object.values(traceActionAnchors), ...Object.values(traceActions)]) {+ const callId = asRecord(value)["callId"];+ if (typeof callId === "string") retainedCallIds.add(callId);+ }+ const traceInvocations = selectOwnedInvocations(+ completedTrace["invocations"],+ actionIds,+ retainedCallIds,+ );+ if (+ Object.keys(traceActionAnchors).length === 0 &&+ Object.keys(traceActions).length === 0 &&+ Object.keys(traceInvocations).length === 0+ ) {+ return preserved;+ }+ const originalTrace = asRecord(original[SERIALIZED_AGENT_TRACE_STATE_KEY]);+ return {+ ...preserved,+ [SERIALIZED_AGENT_TRACE_STATE_KEY]: {+ actionAnchors: {+ ...asRecord(originalTrace["actionAnchors"]),+ ...traceActionAnchors,+ },+ actions: { ...asRecord(originalTrace["actions"]), ...traceActions },+ invocations: {+ ...asRecord(originalTrace["invocations"]),+ ...traceInvocations,+ },+ sessions: asRecord(originalTrace["sessions"]),+ turns: asRecord(originalTrace["turns"]),+ },+ };+}++function selectEntries(value: unknown, keys: ReadonlySet<string>): Record<string, unknown> {+ return Object.fromEntries(Object.entries(asRecord(value)).filter(([key]) => keys.has(key)));+}++function selectOwnedInvocations(+ value: unknown,+ actionIds: ReadonlySet<string>,+ retainedCallIds: Set<string>,+): Record<string, unknown> {+ const pending = Object.entries(asRecord(value));+ const selected: Record<string, unknown> = {};+ let found = true;+ while (found) {+ found = false;+ for (let index = pending.length - 1; index >= 0; index--) {+ const [key, candidate] = pending[index]!;+ const invocation = asRecord(candidate);+ const parentActionCallId = invocation["parentActionCallId"];+ if (+ !actionIds.has(key) &&+ !(typeof parentActionCallId === "string" && retainedCallIds.has(parentActionCallId))+ ) {+ continue;+ }+ selected[key] = candidate;+ const callId = invocation["callId"];+ if (typeof callId === "string") retainedCallIds.add(callId);+ pending.splice(index, 1);+ found = true;+ }+ }+ return selected;+}++function mergeSerializedRecord(+ context: Record<string, unknown>,+ key: string,+ entries: Record<string, unknown>,+): Record<string, unknown> {+ if (Object.keys(entries).length === 0) return context;+ return {+ ...context,+ [key]: { ...asRecord(context[key]), ...entries },+ };+}++function asRecord(value: unknown): Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : {};+}diff --git a/packages/eve/src/tracing/agent-action-instrumentation.ts b/packages/eve/src/tracing/agent-action-instrumentation.tsindex 48fecace8..a4dee44f6 100644--- a/packages/eve/src/tracing/agent-action-instrumentation.ts+++ b/packages/eve/src/tracing/agent-action-instrumentation.ts@@ -18,7 +18,7 @@ import type {} from "#instrumentation/lifecycle.js";import { actionIdempotencyKey, attemptIdempotencyKey } from "#instrumentation/lifecycle.js";import { agentTraceIdentityAttributes } from "#tracing/agent-otel-attributes.js";-import { contentAttribute } from "#tracing/agent-otel-content.js";+import { contentAttribute, textContentAttribute } from "#tracing/agent-otel-content.js";import { setAgentUsage } from "#tracing/agent-otel-usage.js";import { agentSpanNamingAttributes } from "#tracing/agent-span-naming.js";import type { AgentSpanIdGenerator } from "#tracing/agent-span-id-generator.js";@@ -40,7 +40,6 @@ export interface AgentActionInstrumentation {"action.completed" | "action.failed" | "action.started">;deleteForSession(sessionId: string): void | PromiseLike<void>;- deleteForTurn(sessionId: string, turnId: string): void | PromiseLike<void>;failForAttempt(scope: InstrumentationAttemptScope, error: unknown): Promise<void>;flushSettledInvocations(): Promise<void>;flushForSessionTransition(event: InstrumentationSessionTransitionEvent): Promise<void>;@@ -166,7 +165,6 @@ export function createAgentActionInstrumentation(input: {await input.stateStore.deleteActionAnchors(sessionId);await input.stateStore.deleteInvocations(sessionId);},- deleteForTurn: (sessionId, turnId) => input.stateStore.deleteActions(sessionId, turnId),async failForAttempt(scope, error) {const keys = byAttempt.get(scope.attemptId);if (keys === undefined) return;@@ -228,9 +226,9 @@ export function createAgentActionInstrumentation(input: {if (event.errorCode !== undefined) {span.setAttribute("agent.action.error.code", event.errorCode);}- recordError(span, event.error, event.errorCode);+ recordActionError(span, event.error, event.errorCode);} else if (event.output.type === "error") {- recordError(span, event.output.error);+ recordActionError(span, event.output.error);} else {if (event.usage !== undefined) {setAgentUsage(span, event.usage);@@ -288,3 +286,27 @@ function contextFromActionState(state: AgentActionTraceState): Context {function isAgentInvocation(kind: InstrumentationActionKind): boolean {return kind === "subagent-call" || kind === "remote-agent-call";}++function recordActionError(span: Span, error: unknown, errorType?: string): void {+ if (error instanceof Error || error === undefined) {+ recordError(span, error, errorType);+ return;+ }+ const detail = serializedErrorDetail(error);+ if (detail === undefined) {+ recordError(span, undefined, errorType);+ return;+ }+ const normalized = new Error(detail);+ if (errorType !== undefined) normalized.name = errorType;+ recordError(span, normalized, errorType);+}++function serializedErrorDetail(error: unknown): string | undefined {+ if (typeof error === "string") return textContentAttribute(error);+ const serialized = contentAttribute(error, false);+ if (typeof error !== "object" || error === null || Array.isArray(error)) return serialized;+ const message = Reflect.get(error, "message");+ if (typeof message !== "string") return serialized;+ return textContentAttribute(serialized === undefined ? message : `${message}\n${serialized}`);+}diff --git a/packages/eve/src/tracing/agent-otel-provider.test.ts b/packages/eve/src/tracing/agent-otel-provider.test.tsindex 5b5ea0078..8f74c5bf1 100644--- a/packages/eve/src/tracing/agent-otel-provider.test.ts+++ b/packages/eve/src/tracing/agent-otel-provider.test.ts@@ -49,6 +49,7 @@ import {redactSpanInputs,redactSpanOutputs,} from "#tracing/span-export-policy.js";+import { CONTENT_ATTRIBUTE_LIMIT } from "#tracing/agent-otel-content.js";import type { TraceCapturePolicy } from "#tracing/otel-declaration.js";import {actionIdempotencyKey,@@ -58,6 +59,12 @@ import {sessionIdempotencyKey,turnIdempotencyKey,} from "#instrumentation/lifecycle.js";+import {+ rememberInstrumentationActionScope,+ rememberInstrumentationBackgroundTask,+ takeInstrumentationActionScopeForTask,+} from "#instrumentation/state.js";+import { preserveSerializedBackgroundTaskObservabilityState } from "#shared/serialized-observability-state.js";interface TestRuntime {readonly exporter: InMemorySpanExporter;@@ -2093,6 +2100,169 @@ describe("createAgentOtelInstrumentation", () => {expect(byName(spans, "agent.step")).toHaveLength(1);});+ it("keeps a background action open after its initiating turn is cancelled", async () => {+ const runtime = createRuntime();+ const ctx = new ContextContainer();+ const scope: InstrumentationAttemptScope = {+ attemptId: "session-1:turn-1:0:0",+ attemptIndex: 0,+ sessionId: "session-1",+ stepIndex: 0,+ turnId: "turn-1",+ };+ const actionKey = actionIdempotencyKey(scope.sessionId, scope.turnId, "tool-1");++ await contextStorage.run(ctx, async () => {+ await publishTurnStarted({+ hooks: runtime.hooks,+ sessionId: scope.sessionId,+ turnId: scope.turnId,+ turnSequence: 0,+ });+ await runtime.hooks.publish({+ idempotencyKey: attemptIdempotencyKey(scope),+ operation: { modelId: "model", operationId: "ai.streamText", provider: "test" },+ scope,+ type: "step.attempt.started",+ });+ rememberInstrumentationActionScope(actionKey, scope);+ await runtime.hooks.publish({+ callId: "tool-1",+ idempotencyKey: actionKey,+ input: { report: "weekly" },+ kind: "tool-call",+ name: "publish",+ scope,+ type: "action.started",+ });+ rememberInstrumentationBackgroundTask("task-1", { idempotencyKey: actionKey, scope });+ await runtime.hooks.publish({+ idempotencyKey: attemptIdempotencyKey(scope),+ scope,+ type: "step.attempt.completed",+ });+ await runtime.hooks.publish({+ idempotencyKey: turnIdempotencyKey(scope.sessionId, scope.turnId),+ sessionId: scope.sessionId,+ turnId: scope.turnId,+ type: "turn.cancelled",+ });+ });+ await runtime.provider.forceFlush();+ expect(byName(runtime.exporter.getFinishedSpans(), "agent.action")).toHaveLength(0);++ const restored = await deserializeContext(+ preserveSerializedBackgroundTaskObservabilityState({}, serializeContext(ctx), [+ { taskId: "task-1" },+ ]),+ );+ const acceptedAtMs = Date.now() + 1_000;+ await contextStorage.run(restored, async () => {+ const correlation = takeInstrumentationActionScopeForTask("task-1")!;+ await runtime.hooks.publish({+ acceptedAtMs,+ idempotencyKey: correlation.idempotencyKey,+ outcome: "completed",+ output: { output: { reportId: "report-1" }, type: "result" },+ scope: correlation.scope,+ type: "action.completed",+ });+ });+ await runtime.provider.forceFlush();++ const action = byName(runtime.exporter.getFinishedSpans(), "agent.action")[0]!;+ expect(action.attributes).toMatchObject({+ "agent.action.outcome": "completed",+ "gen_ai.tool.call.result": expect.stringContaining("report-1"),+ });+ expect(nanos(action.endTime)).toBe(BigInt(acceptedAtMs) * 1_000_000n);+ });++ it("records serialized task error detail only when output content is admitted", async () => {+ const taskError = {+ code: "PUBLISH_FAILED",+ detail: "x".repeat(CONTENT_ATTRIBUTE_LIMIT * 2),+ message: "private publish failure",+ };+ const run = async (runtime: TestRuntime, sessionId: string): Promise<ReadableSpan> => {+ const scope: InstrumentationAttemptScope = {+ attemptId: `${sessionId}:turn-1:0:0`,+ attemptIndex: 0,+ sessionId,+ stepIndex: 0,+ turnId: "turn-1",+ };+ await publishTurnStarted({+ hooks: runtime.hooks,+ sessionId,+ turnId: scope.turnId,+ turnSequence: 0,+ });+ await runtime.hooks.publish({+ callId: "tool-1",+ idempotencyKey: actionIdempotencyKey(sessionId, scope.turnId, "tool-1"),+ input: {},+ kind: "tool-call",+ name: "publish",+ scope,+ type: "action.started",+ });+ await runtime.hooks.publish({+ error: taskError,+ errorCode: "BACKGROUND_TASK_FAILED",+ idempotencyKey: actionIdempotencyKey(sessionId, scope.turnId, "tool-1"),+ outcome: "failed",+ scope,+ type: "action.failed",+ });+ await runtime.provider.forceFlush();+ return byName(runtime.exporter.getFinishedSpans(), "agent.action")[0]!;+ };++ const recorded = await run(createRuntime(), "recorded");+ expect(recorded.attributes).toMatchObject({+ "agent.action.error.code": "BACKGROUND_TASK_FAILED",+ "agent.action.outcome": "failed",+ "error.type": "BACKGROUND_TASK_FAILED",+ });+ expect(recorded.status.code).toBe(SpanStatusCode.ERROR);+ expect(recorded.status.message).toContain("private publish failure");+ expect(recorded.status.message).toContain("... [truncated]");+ expect(recorded.status.message!.length).toBeLessThan(CONTENT_ATTRIBUTE_LIMIT + 32);+ expect(recorded.events).toContainEqual(+ expect.objectContaining({+ attributes: expect.objectContaining({+ "exception.message": recorded.status.message,+ "exception.type": "BACKGROUND_TASK_FAILED",+ }),+ name: "exception",+ }),+ );++ const redacted = await run(+ createRuntime(new InMemoryAgentTraceStateStore(), () => ({+ emit: true,+ recordInputs: true,+ recordOutputs: false,+ })),+ "redacted",+ );+ expect(redacted.attributes).toMatchObject({+ "agent.action.error.code": "BACKGROUND_TASK_FAILED",+ "agent.action.outcome": "failed",+ "error.type": "BACKGROUND_TASK_FAILED",+ });+ expect(redacted.status).toEqual({ code: SpanStatusCode.ERROR });+ expect(redacted.events.filter((event) => event.name === "exception")).toEqual([]);+ expect(+ JSON.stringify({+ attributes: redacted.attributes,+ events: redacted.events,+ status: redacted.status,+ }),+ ).not.toContain("private publish failure");+ });+it("records a failed attempt on model, tool, and action spans still open", async () => {const runtime = createRuntime();const error = new Error("attempt failed");diff --git a/packages/eve/src/tracing/agent-otel-provider.ts b/packages/eve/src/tracing/agent-otel-provider.tsindex 45bdf858d..30abd4aa9 100644--- a/packages/eve/src/tracing/agent-otel-provider.ts+++ b/packages/eve/src/tracing/agent-otel-provider.ts@@ -280,9 +280,6 @@ export function createAgentOtelInstrumentation(};const onTurnTerminal = async (event: InstrumentationTurnTerminalEvent): Promise<void> => {- if (event.type === "turn.cancelled" || event.type === "turn.failed") {- await actions.deleteForTurn(event.sessionId, event.turnId);- }await input.stateStore.updateTurn(event.sessionId, event.turnId, (turn) => ({...turn,terminal: