The Open Framework for Building Agents
fix(eve): give remote agents their own trace session (#4104)
Chad Hietala44031224c7d9
diff --git a/.changeset/remote-agent-own-trace-session.md b/.changeset/remote-agent-own-trace-session.mdnew file mode 100644index 000000000..a404dfbe3--- /dev/null+++ b/.changeset/remote-agent-own-trace-session.md@@ -0,0 +1,5 @@+---+"eve": patch+---++On Vercel, a remote agent's spans now carry its own session ID as `vercel.session_id` instead of the calling deployment's root session, and its local subagents carry the same ID. Agent Runs in the receiving project lists the remote agent as its own session, with its turns, subagents, and token usage. `gen_ai.conversation.id` still names the caller's conversation.diff --git a/docs/guides/remote-agents.md b/docs/guides/remote-agents.mdindex 491882e2c..72d131871 100644--- a/docs/guides/remote-agents.md+++ b/docs/guides/remote-agents.md@@ -158,6 +158,12 @@ eve carries parent session lineage separately. The receiver accepts it onlywhen `trustedForwarders` approves the authenticated caller; otherwise, tracecorrelation continues without it.+On Vercel, a remote agent's spans and its local subagents' spans carry the+remote session's ID as `vercel.session_id`, so the receiving project groups+them as their own session. `gen_ai.conversation.id` still names the sender's+conversation, and the remote agent's `agent.parent_run.id` names the calling+session.+## Preserving trace contentWith `forwardPrincipal: true`, a sampled remote dispatch forwards its originaldiff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.tsindex 7037724b9..8159f1c40 100644--- a/packages/eve/src/channel/types.ts+++ b/packages/eve/src/channel/types.ts@@ -82,6 +82,20 @@ export interface SessionParent {readonly turn: SessionTurn;}+/**+ * Session whose id a run's spans carry as their trace session.+ *+ * Lineage and tracing usually share a root: every span in a conversation+ * carries `parent.rootSessionId`. A remote agent runs in another deployment,+ * so its spans start their own trace session (`own`) while its lineage still+ * names the caller's root. Its local subagents then carry that session+ * (`inherited`). Conversation correlation across deployments stays on+ * `gen_ai.conversation.id`.+ */+export type SessionTraceRoot =+ | { readonly kind: "own" }+ | { readonly kind: "inherited"; readonly sessionId: string };+/*** Serializable W3C span context identifying a parent's open trace window.* Structural rather than an OTel `SpanContext` so the channel surface stays@@ -490,6 +504,8 @@ export interface RunInput {/** Observability correlation only; never grants delegated-session privileges. */readonly conversationId?: string;readonly parent?: SessionParent;+ /** Trace session for this run when it differs from `parent.rootSessionId`. */+ readonly traceRoot?: SessionTraceRoot;/*** Dispatching parent's open trace window. Handed down rather than looked up* because trace state is scoped to one session's context.diff --git a/packages/eve/src/context/keys.ts b/packages/eve/src/context/keys.tsindex a33b9d2a8..2266fb0f1 100644--- a/packages/eve/src/context/keys.ts+++ b/packages/eve/src/context/keys.ts@@ -14,6 +14,7 @@ import type {SessionCapabilities,SessionParent,SessionTraceContext,+ SessionTraceRoot,SessionTurn,} from "#channel/types.js";import { ContextKey } from "#context/key.js";@@ -36,7 +37,12 @@ import type { PreparedRuntimeDelegationTool } from "#runtime/sessions/turn.js";import type { MemoryScope, MemoryTurnContext } from "#public/memory/index.js";// Re-export so consumers don't need a direct channel/ import.-export type { SessionAuthContext, SessionParent, SessionTurn } from "#channel/types.js";+export type {+ SessionAuthContext,+ SessionParent,+ SessionTraceRoot,+ SessionTurn,+} from "#channel/types.js";// ---------------------------------------------------------------------------// Session types (public API surface)@@ -110,6 +116,7 @@ export interface HistoryState {}export const HistoryStateKey = new ContextKey<HistoryState>("eve.historyState");export interface ActiveChannelDelivery {+ readonly traceSessionId: string;readonly agentName?: string;readonly channelType?: string;readonly delivery: InstrumentationChannelDeliveryRef;@@ -126,6 +133,8 @@ export const ChannelInstrumentationKey = new ContextKey<ChannelInstrumentationPr"eve.channelInstrumentation",);export const ParentSessionKey = new ContextKey<SessionParent>("eve.parentSession");+/** Set only when the trace root differs from `ParentSessionKey`'s root; see {@link SessionTraceRoot}. */+export const TraceRootKey = new ContextKey<SessionTraceRoot>("eve.traceRoot");/** Separate from {@link ParentSessionKey} so it stays out of what extensions read. */export const ParentTraceContextKey = new ContextKey<SessionTraceContext>("eve.parentTraceContext");diff --git a/packages/eve/src/eve-channel/index.ts b/packages/eve/src/eve-channel/index.tsindex 5df1d28b1..b632e0773 100644--- a/packages/eve/src/eve-channel/index.ts+++ b/packages/eve/src/eve-channel/index.ts@@ -345,6 +345,9 @@ export function eveChannel(input: EveChannelInput): EveChannel {: readConversationBaggage(req.headers.get("baggage")),parent,parentTraceContext,+ // A remote agent's spans form their own session in this+ // deployment; its lineage still names the caller's root.+ traceRoot: parent === undefined ? undefined : { kind: "own" },title: messageResult.title,});} catch (error) {diff --git a/packages/eve/src/execution/agent-sessions/context.ts b/packages/eve/src/execution/agent-sessions/context.tsindex 78e0aa49a..4dc079946 100644--- a/packages/eve/src/execution/agent-sessions/context.ts+++ b/packages/eve/src/execution/agent-sessions/context.ts@@ -3,6 +3,7 @@ import type {RunSessionLimits,SessionCapabilities,SessionParent,+ SessionTraceRoot,} from "#channel/types.js";import type { LocalDevRequestProvenance } from "#context/keys.js";import type { DynamicSubagentSelections } from "#execution/agent-sessions/target.js";@@ -46,6 +47,8 @@ export interface AgentSessionContext {readonly localDevRequest?: LocalDevRequestProvenance;/** The calling session, turn, and tool call, recorded as each session's lineage. */readonly parent: SessionParent;+ /** Present when the caller's trace root differs from `parent.rootSessionId`. */+ readonly traceRoot?: SessionTraceRoot;readonly sandbox: AgentSessionSandbox;readonly trace: AgentChildTraceDispatch;}@@ -74,6 +77,7 @@ type CallerDispatch = Pick<| "sandboxSessionId"| "serializedContext"| "session"+ | "traceRoot"| "workflowAgents">;@@ -121,6 +125,7 @@ export function captureAgentSessionContext(turn: { id: batch.event.turnId, sequence: batch.event.sequence },},sandbox: { sessionId: caller.sandboxSessionId, state: session.sandboxState },+ traceRoot: caller.traceRoot,trace: resolveToolCallAgentTrace({callId,conversation: caller.inheritedConversation,diff --git a/packages/eve/src/execution/agent-sessions/steps.ts b/packages/eve/src/execution/agent-sessions/steps.tsindex 4b6325311..3dbea8133 100644--- a/packages/eve/src/execution/agent-sessions/steps.ts+++ b/packages/eve/src/execution/agent-sessions/steps.ts@@ -305,6 +305,7 @@ function createParentContext(context: AgentSessionContext, replyTo: string): Sublineage: context.parent,originAudience: context.trace.originAudience,traceContext: context.trace.parentTraceContext,+ traceRoot: context.traceRoot,};}diff --git a/packages/eve/src/execution/coordination-dispatch-shared.ts b/packages/eve/src/execution/coordination-dispatch-shared.tsindex 6a2f2083b..ea6a48396 100644--- a/packages/eve/src/execution/coordination-dispatch-shared.ts+++ b/packages/eve/src/execution/coordination-dispatch-shared.ts@@ -10,6 +10,7 @@ import {LocalDevRequestKey,type LocalDevRequestProvenance,ParentSessionKey,+ TraceRootKey,} from "#context/keys.js";import { ConversationContextKey } from "#shared/conversation-context.js";import { ContextContainer } from "#context/container.js";@@ -27,7 +28,9 @@ import {} from "#harness/coordination.js";import { activeTurnId } from "#harness/active-turn-id.js";import type { RuntimeActionResult, RuntimeWorkflowTaskRequest } from "#shared/action-types.js";-import type { SessionParent } from "#channel/types.js";+import type { SessionParent, SessionTraceRoot } from "#channel/types.js";+import type { ContextReader } from "#context/key.js";+import { resolveTraceRootSessionId } from "#shared/trace-root.js";import {createDurableSessionState,type DurableSessionState,@@ -80,6 +83,8 @@ export interface PreparedCoordinationDispatch<PlanEntry = RuntimeWorkflowTaskReqreadonly plan: readonly PlanEntry[];readonly session: HarnessSessionBase;readonly sessionState: DurableSessionState;+ /** Trace root that this session's local children inherit, when it isn't the lineage root. */+ readonly traceRoot?: SessionTraceRoot;readonly workflowAgents: Readonly<Record<string, WorkflowAgentMetadata>>;}@@ -191,10 +196,21 @@ export async function prepareActionDispatch<PlanEntry>(input: {sandboxSessionId,serializedContext: input.serializedContext,session,+ traceRoot: childTraceRoot(ctx, session.sessionId),workflowAgents: resolveWorkflowAgentMetadata(ctx),};}+/**+ * A local child normally shares its caller's lineage root as its trace+ * session, so nothing is recorded. When the caller's trace session differs,+ * as for a remote agent and its descendants, the child inherits it.+ */+function childTraceRoot(ctx: ContextReader, sessionId: string): SessionTraceRoot | undefined {+ if (ctx.get(TraceRootKey) === undefined) return undefined;+ return { kind: "inherited", sessionId: resolveTraceRootSessionId(ctx, sessionId) };+}+function resolveActiveSandboxSessionId(adapterState: unknown, sessionId: string): string {if (typeof adapterState !== "object" || adapterState === null) return sessionId;const value = (adapterState as Record<string, unknown>).sandboxSessionId;diff --git a/packages/eve/src/execution/runtime-context.test.ts b/packages/eve/src/execution/runtime-context.test.tsindex 74958f321..d90ad2a02 100644--- a/packages/eve/src/execution/runtime-context.test.ts+++ b/packages/eve/src/execution/runtime-context.test.ts@@ -243,7 +243,7 @@ describe("buildRunContext", () => {expect(ctx.require(ScheduleIdKey)).toBe("automatic-reports");});- it("stores a title only for top-level sessions", () => {+ it("stores titles for root and remote-owned sessions, not local children", () => {const root = buildRunContext({bundle: createMinimalBundle(),run: {@@ -269,6 +269,22 @@ describe("buildRunContext", () => {expect(root.get(SessionTitleKey)).toBe("Investigate the incident");expect(child.get(SessionTitleKey)).toBeUndefined();+ const remote = buildRunContext({+ bundle: createMinimalBundle(),+ run: {+ auth: null,+ adapter: { kind: "eve" },+ input: { message: "Remote task" },+ traceRoot: { kind: "own" },+ parent: {+ callId: "call",+ rootSessionId: "caller-root",+ sessionId: "caller",+ turn: { id: "turn_0", sequence: 0 },+ },+ },+ });+ expect(remote.get(SessionTitleKey)).toBe("Remote task");});it("does not invent a continuation for an ID-only run", () => {diff --git a/packages/eve/src/execution/runtime-context.ts b/packages/eve/src/execution/runtime-context.tsindex 1c69a1f5f..d4763be27 100644--- a/packages/eve/src/execution/runtime-context.ts+++ b/packages/eve/src/execution/runtime-context.ts@@ -18,6 +18,7 @@ import {SessionCallbackKey,LegacyRemoteAgentCallerKey,SessionTitleKey,+ TraceRootKey,} from "#context/keys.js";import { deriveSessionTitle } from "#execution/eve-workflow-attributes.js";import { BundleKey, type CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";@@ -47,7 +48,7 @@ export function buildRunContext(input: {ConversationContextKey,buildConversationContext(run, resolveInstrumentationEnvironment()),);- if (run.parent === undefined) {+ if (run.parent === undefined || run.traceRoot?.kind === "own") {const title = deriveSessionTitle(run.title ?? run.input.message);if (title !== undefined) ctx.set(SessionTitleKey, title);}@@ -101,6 +102,9 @@ export function buildRunContext(input: {if (run.parent !== undefined) {ctx.set(ParentSessionKey, run.parent);}+ if (run.traceRoot !== undefined) {+ ctx.set(TraceRootKey, run.traceRoot);+ }if (run.parentTraceContext !== undefined) {ctx.set(ParentTraceContextKey, run.parentTraceContext);diff --git a/packages/eve/src/execution/session/turn-step.test.ts b/packages/eve/src/execution/session/turn-step.test.tsindex 6304b758b..a8e2156ca 100644--- a/packages/eve/src/execution/session/turn-step.test.ts+++ b/packages/eve/src/execution/session/turn-step.test.ts@@ -19,14 +19,17 @@ import {SessionDynamicModelReferenceKey,SessionDynamicToolMetadataKey,SessionDynamicToolRuntimeRevisionKey,+ ParentSessionKey,SessionIdKey,SessionTraceSeedKey,+ TraceRootKey,TurnDynamicToolMetadataKey,TurnDeliveryIdsKey,HistoryStateKey,} from "#context/keys.js";import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";-import { serializeContext } from "#context/serialize.js";+import { deserializeContext, serializeContext } from "#context/serialize.js";+import { startWorkflowTask } from "#execution/tools/workflow/start.js";import { getPendingCoordinationBatch, setPendingCoordinationBatch } from "#harness/coordination.js";import { TurnCancelledError } from "#harness/turn-cancellation.js";import { setHarnessEmissionState } from "#harness/emission-state.js";@@ -667,7 +670,7 @@ function currentSessionHook(token: string) {}describe("dispatchCoordinationStep", () => {- it("repairs an empty pending turn id from the active session turn", async () => {+ function mockCoordinationBundle(): void {vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({adapterRegistry: {adaptersByKind: new Map([[threadContextAdapter.kind, threadContextAdapter]]),@@ -683,7 +686,10 @@ describe("dispatchCoordinationStep", () => {toolRegistry: {},turnAgent: TestTurnAgent,} as never);- const session = setPendingCoordinationBatch({+ }++ function pendingWorkflowTask(turnId: string): HarnessSession {+ return setPendingCoordinationBatch({tasks: [{callId: "call-1",@@ -695,11 +701,15 @@ describe("dispatchCoordinationStep", () => {workflowId: "workflow//eve//research",},],- event: { sequence: 3, stepIndex: 2, turnId: "" },+ event: { sequence: 3, stepIndex: 2, turnId },responseMessages: [],session: createStubSession(),});- installSessionStoreMocks([session]);+ }++ it("repairs an empty pending turn id from the active session turn", async () => {+ mockCoordinationBundle();+ installSessionStoreMocks([pendingWorkflowTask("")]);const sessionState = createStubSessionState({emissionState: { sequence: 3, sessionStarted: true, stepIndex: 2, turnId: "" },});@@ -716,6 +726,41 @@ describe("dispatchCoordinationStep", () => {expect(result.stateDelta.sessionState).toBeDefined();expect(getPendingCoordinationBatch(persisted?.state)?.event.turnId).toBe("turn_3");});++ it.each([+ { name: "a remote agent", traceRoot: { kind: "own" } as const, expected: "sess-test" },+ {+ name: "a remote agent's descendant",+ traceRoot: { kind: "inherited", sessionId: "remote-root" } as const,+ expected: "remote-root",+ },+ ])("hands $name's trace session down to the agents it opens", async ({ traceRoot, expected }) => {+ mockCoordinationBundle();+ installSessionStoreMocks([pendingWorkflowTask("turn_3")]);+ const ctx = await deserializeContext(createSerializedContext());+ ctx.set(ParentSessionKey, {+ callId: "remote-call",+ rootSessionId: "caller-root",+ sessionId: "caller-session",+ turn: { id: "caller-turn", sequence: 0 },+ });+ ctx.set(TraceRootKey, traceRoot);++ await dispatchCoordinationStep({+ action: "park",+ workflowToolRunOwner: { inbox: "generated-owner-token" },+ sessionWritable: createTestWritable(),+ serializedContext: serializeContext(ctx),+ sessionState: createStubSessionState({+ emissionState: { sequence: 3, sessionStarted: true, stepIndex: 2, turnId: "turn_3" },+ }),+ });++ expect(vi.mocked(startWorkflowTask).mock.calls[0]?.[0].agentContext.traceRoot).toEqual({+ kind: "inherited",+ sessionId: expected,+ });+ });});describe("turnStep", () => {diff --git a/packages/eve/src/instrumentation/channel-delivery.ts b/packages/eve/src/instrumentation/channel-delivery.tsindex 5e35a09e4..b1c3afef8 100644--- a/packages/eve/src/instrumentation/channel-delivery.ts+++ b/packages/eve/src/instrumentation/channel-delivery.ts@@ -19,6 +19,7 @@ import {} from "#shared/conversation-context.js";export interface ChannelDeliveryStartInstrumentation {+ readonly traceSessionId: string;readonly agentName?: string;readonly ctx: AlsContext;readonly delivery: DeliverHookPayload;@@ -65,6 +66,7 @@ export async function instrumentChannelDelivery(idempotencyKey: channelDeliveryIdempotencyKey(item.sessionId, item.delivery.deliveryId),outcome: input.outcome,rootSessionId: item.rootSessionId,+ traceSessionId: item.traceSessionId,sequence: input.includeTurn ? item.sequence : undefined,sessionId: item.sessionId,turnId: input.includeTurn ? item.turnId : undefined,@@ -104,6 +106,7 @@ export async function instrumentChannelDelivery(delivery,policyAgentName: input.policyAgentName,rootSessionId: input.rootSessionId,+ traceSessionId: input.traceSessionId,sequence: input.sequence,sessionId: input.sessionId,turnId: input.turnId,@@ -125,6 +128,7 @@ export async function instrumentChannelDelivery(input: deliveryInput,parentTraceContext: input.ctx.get(ParentTraceContextKey),rootSessionId: input.rootSessionId,+ traceSessionId: input.traceSessionId,sequence: input.sequence,sessionId: input.sessionId,traceSeed: input.ctx.get(SessionTraceSeedKey),diff --git a/packages/eve/src/instrumentation/lifecycle.ts b/packages/eve/src/instrumentation/lifecycle.tsindex 54d553ece..a48cddc5e 100644--- a/packages/eve/src/instrumentation/lifecycle.ts+++ b/packages/eve/src/instrumentation/lifecycle.ts@@ -12,6 +12,7 @@ import type { TraceCaptureContext, TraceCapturePolicy } from "#shared/trace-poli* protocol `step.*` events and the resolver hook fire once per step.*/export interface InstrumentationAttemptScope {+ readonly traceSessionId?: string;readonly channelAudience?: ChannelAudience;readonly attemptId: string;readonly attemptIndex: number;@@ -166,6 +167,7 @@ export interface InstrumentationChannelDeliveryInput {}interface InstrumentationChannelDeliveryScope {+ readonly traceSessionId?: string;readonly agentName?: string;readonly delivery: InstrumentationChannelDeliveryRef;readonly idempotencyKey: string;@@ -269,6 +271,7 @@ export interface InstrumentationStepAttemptStartedEvent {}export interface InstrumentationSessionStartedEvent {+ readonly traceSessionId?: string;readonly type: "session.started";readonly agentName?: string;readonly channelKind?: string;@@ -353,6 +356,7 @@ export type InstrumentationSessionTransitionEvent =| InstrumentationSessionFailedEvent;export interface InstrumentationTurnStartedEvent {+ readonly traceSessionId?: string;readonly type: "turn.started";readonly agentName?: string;readonly currentPrincipal?: InstrumentationPrincipalSummary;diff --git a/packages/eve/src/instrumentation/memory.ts b/packages/eve/src/instrumentation/memory.tsindex e6f5af31e..e1f56883f 100644--- a/packages/eve/src/instrumentation/memory.ts+++ b/packages/eve/src/instrumentation/memory.ts@@ -32,6 +32,7 @@ export interface InstrumentationMemoryOperation {/** Bound session identity added when eve publishes a memory operation. */export interface InstrumentationMemoryOperationEvent extends InstrumentationMemoryOperation {+ readonly traceSessionId?: string;readonly rootSessionId: string;readonly sessionId: string;}@@ -84,14 +85,15 @@ export function createMemoryInstrumentation(input: {readonly resolveContext: () => {readonly hooks: InstrumentationHooks;readonly rootSessionId: string;+ readonly traceSessionId: string;};readonly runInContext: InstrumentationContextRunner;readonly sessionId: string;}): MemoryInstrumentation {return {async execute(operation, execute) {- const { hooks, rootSessionId } = input.resolveContext();- const event = { ...operation, rootSessionId, sessionId: input.sessionId };+ const { hooks, rootSessionId, traceSessionId } = input.resolveContext();+ const event = { ...operation, rootSessionId, traceSessionId, sessionId: input.sessionId };await hooks.publish({ ...event, type: "memory.operation.started" });try {const result = await input.runInContext(diff --git a/packages/eve/src/instrumentation/native-events.test.ts b/packages/eve/src/instrumentation/native-events.test.tsindex aa6aa8f89..81b16b7b4 100644--- a/packages/eve/src/instrumentation/native-events.test.ts+++ b/packages/eve/src/instrumentation/native-events.test.ts@@ -53,6 +53,7 @@ describe("createInstrumentationHandleEvent", () => {},policyAgentName: "weather",rootSessionId: "session-1",+ traceSessionId: "session-1",sequence: 0,sessionId: "session-1",turnId: "turn_0",diff --git a/packages/eve/src/instrumentation/native-events.ts b/packages/eve/src/instrumentation/native-events.tsindex c1476ee64..e2be70e40 100644--- a/packages/eve/src/instrumentation/native-events.ts+++ b/packages/eve/src/instrumentation/native-events.ts@@ -36,6 +36,7 @@ import {import type { ChannelAudience } from "#shared/channel-audience.js";export interface CreateInstrumentationHandleEventInput {+ readonly traceSessionId?: string;readonly agentName?: string;readonly channelKind?: string;readonly channelAudience?: ChannelAudience;@@ -318,6 +319,7 @@ function toLifecycleEvent(parentLineage: input.parentLineage,parentTraceContext: input.parentTraceContext,rootSessionId: input.rootSessionId ?? input.sessionId,+ traceSessionId: input.traceSessionId,scheduleId: input.scheduleId,sessionId: input.sessionId,title: input.title,@@ -345,6 +347,7 @@ function toLifecycleEvent(parentLineage: input.parentLineage,parentTraceContext: input.parentTraceContext,rootSessionId: input.rootSessionId ?? input.sessionId,+ traceSessionId: input.traceSessionId,sequence: event.data.sequence,sessionId: input.sessionId,turnId: event.data.turnId,diff --git a/packages/eve/src/instrumentation/runtime.test.ts b/packages/eve/src/instrumentation/runtime.test.tsindex b4ed3ddad..69b1087bb 100644--- a/packages/eve/src/instrumentation/runtime.test.ts+++ b/packages/eve/src/instrumentation/runtime.test.ts@@ -12,6 +12,7 @@ import {ScheduleIdKey,SessionTitleKey,SessionTraceSeedKey,+ TraceRootKey,} from "#context/keys.js";import { setChannelContext } from "#execution/channel-context.js";import type { InstrumentationHooks } from "#instrumentation/lifecycle.js";@@ -371,6 +372,75 @@ describe("initializeSessionInstrumentation", () => {});describe("bindInstrumentationRuntime", () => {+ it("carries the bound trace session through methods called under another session's context", async () => {+ const publish = vi.fn();+ const prepareSessionTrace = vi.fn(async (_event: unknown) => ({+ spanId: "a".repeat(16),+ traceId: "b".repeat(32),+ traceFlags: 1,+ }));+ const prepareTurnTrace = vi.fn(async (_event: unknown) => ({+ spanId: "a".repeat(16),+ traceId: "b".repeat(32),+ traceFlags: 1,+ }));+ const ctx = createContext();+ ctx.set(TraceRootKey, { kind: "own" });+ const other = createContext();+ other.set(TraceRootKey, { kind: "inherited", sessionId: "unrelated" });+ const bound = bindInstrumentationRuntime(+ {+ ...createRuntime({ capturesContent: true, publish }),+ prepareSessionTrace,+ prepareTurnTrace,+ memoryOperations: true,+ },+ ctx,+ boundSession,+ )!;+ await contextStorage.run(other, async () => {+ await bound.preparePreamble({ sequence: 0, sessionStarted: false, turnId: "turn_0" });+ await bound.memory!.execute(+ {+ idempotencyKey: "memory",+ operationName: "search_memory",+ phase: "turn.started",+ slot: "notes",+ storeId: "store",+ },+ async () => ({ value: undefined }),+ );+ await bound.prepareExecution().runStep(+ {+ environment: "test",+ eveVersion: "test",+ hasInput: true,+ session: { sessionId: boundSession.sessionId },+ },+ async (step) => {+ const attempt = step.prepareAttempt({+ attemptIndex: 0,+ stepIndex: 0,+ turnId: "turn_0",+ });+ expect(attempt.scope.traceSessionId).toBe(boundSession.sessionId);+ await attempt.complete();+ },+ );+ });+ expect(prepareSessionTrace.mock.calls[0]?.[0]).toMatchObject({+ traceSessionId: boundSession.sessionId,+ });+ expect(prepareTurnTrace.mock.calls[0]?.[0]).toMatchObject({+ traceSessionId: boundSession.sessionId,+ });+ expect(+ publish.mock.calls+ .map(([event]) => event)+ .filter((event) => event.type.startsWith("memory."))+ .every((event) => event.traceSessionId === boundSession.sessionId),+ ).toBe(true);+ });it("initializes conversation identity without worker controls when no runtime is loaded", () => {const ctx = new ContextContainer();expect(bindInstrumentationRuntime(undefined, ctx, boundSession)).toBeUndefined();@@ -652,7 +722,15 @@ describe("bindInstrumentationRuntime", () => {expect(publish).not.toHaveBeenCalled();});- it("publishes memory operations with the effective session identity", async () => {+ it.each([+ { name: "local subagent", traceRoot: undefined, expected: "conversation-root" },+ { name: "remote agent", traceRoot: { kind: "own" } as const, expected: "session-1" },+ {+ name: "remote agent's local subagent",+ traceRoot: { kind: "inherited", sessionId: "remote-root" } as const,+ expected: "remote-root",+ },+ ])("preserves the lifecycle lineage root for a $name", async ({ traceRoot, expected }) => {const publish = vi.fn();const ctx = createContext();ctx.set(ParentSessionKey, {@@ -661,6 +739,7 @@ describe("bindInstrumentationRuntime", () => {sessionId: "parent-session",turn: { id: "parent-turn", sequence: 0 },});+ if (traceRoot !== undefined) ctx.set(TraceRootKey, traceRoot);const instrumentation = bindInstrumentationRuntime({...createRuntime({ capturesContent: true, publish }),@@ -687,15 +766,18 @@ describe("bindInstrumentationRuntime", () => {}),);+ expect(ctx.get(ConversationIdKey)).toBe("conversation-root");expect(publish.mock.calls.map(([event]) => event)).toEqual([expect.objectContaining({rootSessionId: "conversation-root",+ traceSessionId: expected,sessionId: "session-1",type: "memory.operation.started",}),expect.objectContaining({recordCount: 1,rootSessionId: "conversation-root",+ traceSessionId: expected,sessionId: "session-1",type: "memory.operation.completed",}),@@ -923,6 +1005,7 @@ describe("bindSessionInstrumentation", () => {context: { spanId: "1".repeat(16), traceFlags: 1, traceId: "2".repeat(32) },decision: { action: "record", recordInputs: false, recordOutputs: true },rootSessionId: "session-1",+ traceSessionId: "session-1",});});diff --git a/packages/eve/src/instrumentation/runtime.ts b/packages/eve/src/instrumentation/runtime.tsindex 1934580ac..634e03cea 100644--- a/packages/eve/src/instrumentation/runtime.ts+++ b/packages/eve/src/instrumentation/runtime.ts@@ -62,6 +62,7 @@ import { readSessionTraceDecision } from "#tracing/agent-trace-context-store.js"import { readInstrumentationDecision } from "#shared/instrumentation-decision.js";import { applyLiveDeliveryAudienceCeiling } from "#shared/forwarded-trace-policy.js";import { readConversationId } from "#shared/conversation-identity.js";+import { resolveTraceRootSessionId } from "#shared/trace-root.js";import {getInstrumentationRuntime,registerInstrumentationRuntime,@@ -90,6 +91,7 @@ export interface InstrumentationStepScope<TSession> {| "parentLineage"| "parentTraceContext"| "rootSessionId"+ | "traceSessionId"| "sessionId">,) => HandleEventFn | undefined;@@ -129,6 +131,7 @@ export interface PreparedInstrumentationAttempt {export type InstrumentationAttempt = InstrumentationAttemptScope;export interface BoundInstrumentationSession {+ readonly traceSessionId: string;readonly agentName: string;readonly rootSessionId: string;readonly sessionId: string;@@ -177,7 +180,7 @@ export interface ExecutionInstrumentation {readonly flush: () => Promise<void>;readonly instrumentChannelDelivery: (input:- | Omit<ChannelDeliveryStartInstrumentation, "hooks" | "policyAgentName">+ | Omit<ChannelDeliveryStartInstrumentation, "hooks" | "policyAgentName" | "traceSessionId">| Omit<ChannelDeliveryTerminalInstrumentation, "hooks">,) => Promise<void>;readonly memory?: MemoryInstrumentation;@@ -188,8 +191,12 @@ export interface ExecutionInstrumentation {export function bindInstrumentationRuntime(runtime: InstrumentationRuntime | undefined,ctx: ContextContainer,- boundSession: BoundInstrumentationSession,+ boundInput: Omit<BoundInstrumentationSession, "traceSessionId">,): ExecutionInstrumentation | undefined {+ const boundSession: BoundInstrumentationSession = {+ ...boundInput,+ traceSessionId: resolveTraceRootSessionId(ctx, boundInput.sessionId),+ };if (readConversationId(ctx.get(ConversationIdKey)) === undefined) {ctx.set(ConversationIdKey,@@ -198,8 +205,15 @@ export function bindInstrumentationRuntime(}if (runtime === undefined) return undefined;const baseHooks = runtime.hooks;- const readSessionContext = () =>- readInstrumentationSessionContext(contextStorage.getStore() ?? ctx);+ const traceSessionId = boundSession.traceSessionId;+ const readSessionContext = () => {+ const sessionContext = readInstrumentationSessionContext(contextStorage.getStore() ?? ctx);+ return {+ ...sessionContext,+ rootSessionId: sessionContext.parent?.rootSessionId ?? boundSession.rootSessionId,+ traceSessionId,+ };+ };const bindHooks = (sessionContext: ReturnType<typeof readSessionContext>) => {return (baseHooks.forTrace?.({@@ -235,7 +249,8 @@ export function bindInstrumentationRuntime(channelType: sessionContext.instrumentation?.channelType,parentLineage: sessionContext.parentLineage,parentTraceContext: sessionContext.parentTraceContext,- rootSessionId: sessionContext.parent?.rootSessionId ?? boundSession.rootSessionId,+ rootSessionId: sessionContext.rootSessionId,+ traceSessionId: sessionContext.traceSessionId,scheduleId: sessionContext.scheduleId,sessionId: boundSession.sessionId,title: sessionContext.title,@@ -250,7 +265,8 @@ export function bindInstrumentationRuntime(const sessionContext = readSessionContext();return {hooks: bindHooks(sessionContext),- rootSessionId: sessionContext.parent?.rootSessionId ?? boundSession.rootSessionId,+ rootSessionId: sessionContext.rootSessionId,+ traceSessionId: sessionContext.traceSessionId,};},runInContext: runtime.runInContext,@@ -396,7 +412,8 @@ export function bindInstrumentationRuntime(hooks,parentLineage: sessionContext.parentLineage,parentTraceContext: sessionContext.parentTraceContext,- rootSessionId: sessionContext.parent?.rootSessionId,+ rootSessionId: sessionContext.rootSessionId,+ traceSessionId: sessionContext.traceSessionId,scheduleId: sessionContext.scheduleId,sessionId: boundSession.sessionId,title: sessionContext.title,@@ -407,7 +424,8 @@ export function bindInstrumentationRuntime(attemptIndex: attemptInput.attemptIndex,channelAudience: audience,functionId: settings?.functionId ?? boundSession.agentName,- rootSessionId: sessionContext.parent?.rootSessionId ?? boundSession.sessionId,+ rootSessionId: sessionContext.rootSessionId,+ traceSessionId: sessionContext.traceSessionId,sessionId: boundSession.sessionId,stepIndex: attemptInput.stepIndex,turnId: attemptInput.turnId,@@ -485,6 +503,10 @@ export function bindInstrumentationRuntime(channelKind: sessionContext.conversation.channel.kind,handleEvent: input.handleEvent,hooks: bindHooks(sessionContext),+ rootSessionId: sessionContext.rootSessionId,+ traceSessionId: sessionContext.traceSessionId,+ parentLineage: sessionContext.parentLineage,+ parentTraceContext: sessionContext.parentTraceContext,scheduleId: sessionContext.scheduleId,sessionId: boundSession.sessionId,title: sessionContext.title,@@ -492,12 +514,18 @@ export function bindInstrumentationRuntime(});},flush: runtime.forceFlush,- instrumentChannelDelivery: (input) =>- instrumentChannelDelivery({- ...input,- hooks: baseHooks,- policyAgentName: boundSession.agentName,- }),+ instrumentChannelDelivery: (input) => {+ const sessionContext = readSessionContext();+ if ("delivery" in input) {+ return instrumentChannelDelivery({+ ...input,+ hooks: baseHooks,+ policyAgentName: boundSession.agentName,+ traceSessionId: sessionContext.traceSessionId,+ });+ }+ return instrumentChannelDelivery({ ...input, hooks: baseHooks });+ },memory,prepareExecution,preparePreamble: (input) => preparePreamble(input, readSessionContext()),@@ -510,11 +538,13 @@ export function bindSessionInstrumentation(input: {readonly rootSessionId: string;readonly sessionId: string;}): ExecutionInstrumentation | undefined {- return bindInstrumentationRuntime(getInstrumentationRuntime(), input.ctx, {+ const session: BoundInstrumentationSession = {agentName: input.agentName,rootSessionId: input.rootSessionId,+ traceSessionId: resolveTraceRootSessionId(input.ctx, input.sessionId),sessionId: input.sessionId,- });+ };+ return bindInstrumentationRuntime(getInstrumentationRuntime(), input.ctx, session);}function resolveStepInstrumentationDecision(diff --git a/packages/eve/src/instrumentation/trace-session-producers.integration.test.ts b/packages/eve/src/instrumentation/trace-session-producers.integration.test.tsnew file mode 100644index 000000000..443492973--- /dev/null+++ b/packages/eve/src/instrumentation/trace-session-producers.integration.test.ts@@ -0,0 +1,18 @@+import { readFile } from "node:fs/promises";+import { describe, expect, it } from "vitest";++describe("trace-session producers", () => {+ it.each(["native-events.ts", "runtime.ts", "channel-delivery.ts", "memory.ts"])(+ "requires explicit trace-session fields in %s identity literals",+ async (file) => {+ const source = await readFile(new URL(file, import.meta.url), "utf8");+ const identityLiterals = (+ source.match(/\{[^{}]*(?<!\.)\brootSessionId(?:\s*:|\s*,)[^{}]*\}/gu) ?? []+ ).filter((literal) => !literal.includes("readonly"));+ expect(identityLiterals.length).toBeGreaterThan(0);+ for (const literal of identityLiterals) {+ expect(literal).toMatch(/\btraceSessionId(?:\s*:|\s*[,}])/u);+ }+ },+ );+});diff --git a/packages/eve/src/public/channels/eve-session-routes.test.ts b/packages/eve/src/public/channels/eve-session-routes.test.tsindex 5af037a0b..3dbd21601 100644--- a/packages/eve/src/public/channels/eve-session-routes.test.ts+++ b/packages/eve/src/public/channels/eve-session-routes.test.ts@@ -393,6 +393,9 @@ describe("eve ID-addressed session routes", () => {parent: trusted ? parent : undefined,}),);+ expect(createSession.mock.calls[0]?.[0].traceRoot).toEqual(+ trusted ? { kind: "own" } : undefined,+ );const untrusted = logs.records.filter((record) => record.message === "ignoring remote parent lineage from an untrusted forwarder",);diff --git a/packages/eve/src/shared/trace-root.ts b/packages/eve/src/shared/trace-root.tsnew file mode 100644index 000000000..76dfa2a42--- /dev/null+++ b/packages/eve/src/shared/trace-root.ts@@ -0,0 +1,15 @@+import type { ContextReader } from "#context/key.js";+import { ParentSessionKey, TraceRootKey } from "#context/keys.js";++/**+ * Session id that a run's spans carry as `vercel.session_id`.+ *+ * Falls back to the lineage root, then to the run's own session for a+ * top-level run.+ */+export function resolveTraceRootSessionId(ctx: ContextReader, sessionId: string): string {+ const traceRoot = ctx.get(TraceRootKey);+ if (traceRoot?.kind === "own") return sessionId;+ if (traceRoot?.kind === "inherited") return traceRoot.sessionId;+ return ctx.get(ParentSessionKey)?.rootSessionId ?? sessionId;+}diff --git a/packages/eve/src/subagents/invocation.ts b/packages/eve/src/subagents/invocation.tsindex 43072d88d..1260af384 100644--- a/packages/eve/src/subagents/invocation.ts+++ b/packages/eve/src/subagents/invocation.ts@@ -1,11 +1,13 @@import type { StepInput } from "#harness/types.js";-import type { SessionParent, SessionTraceContext } from "#channel/types.js";+import type { SessionParent, SessionTraceContext, SessionTraceRoot } from "#channel/types.js";import type { ChannelAudience } from "#shared/channel-audience.js";import { isJsonObjectValue, type JsonObject, type JsonValue } from "#shared/json.js";export interface SubagentParentContext {readonly conversationId?: string;readonly lineage: SessionParent;+ /** The caller's trace root, which a local child inherits. */+ readonly traceRoot?: SessionTraceRoot;readonly continuationToken?: string;readonly traceContext?: SessionTraceContext;readonly originAudience?: ChannelAudience;diff --git a/packages/eve/src/subagents/tool.test.ts b/packages/eve/src/subagents/tool.test.tsindex cf423aeaa..30f305ab8 100644--- a/packages/eve/src/subagents/tool.test.ts+++ b/packages/eve/src/subagents/tool.test.ts@@ -239,20 +239,18 @@ describe("buildSubagentRunInput", () => {expect(runInput.input.outputSchema).toEqual(schema);});- it("hands the parent's trace window down to the child, and omits it when absent", () => {+ it("hands the parent's trace window and trace root down to the child, and omits them when absent", () => {const traceContext = { spanId: "2".repeat(16), traceFlags: 1, traceId: "1".repeat(32) };+ const traceRoot = { kind: "inherited", sessionId: "remote-root" } as const;const { runInput } = buildRuntimeSubagentRunInput({action: makeAction(),auth: null,initiatorAuth: null,session: makeSession(),- parent: makeParent(- makeSession(),- { id: "turn-0", sequence: 0 },- { traceContext: traceContext },- ),+ parent: makeParent(makeSession(), { id: "turn-0", sequence: 0 }, { traceContext, traceRoot }),});expect(runInput.parentTraceContext).toEqual(traceContext);+ expect(runInput.traceRoot).toEqual(traceRoot);const untraced = buildRuntimeSubagentRunInput({action: makeAction(),@@ -262,6 +260,7 @@ describe("buildSubagentRunInput", () => {parent: makeParent(makeSession(), { id: "turn-0", sequence: 0 }),});expect(untraced.runInput.parentTraceContext).toBeUndefined();+ expect(untraced.runInput.traceRoot).toBeUndefined();});it("passes a resolved local subagent description into the child message", () => {diff --git a/packages/eve/src/subagents/tool.ts b/packages/eve/src/subagents/tool.tsindex 283381245..70ad2a222 100644--- a/packages/eve/src/subagents/tool.ts+++ b/packages/eve/src/subagents/tool.ts@@ -136,6 +136,7 @@ export function buildSubagentRunInput(input: {conversationId: input.parent.conversationId,parent: input.parent.lineage,parentTraceContext: input.parent.traceContext,+ traceRoot: input.parent.traceRoot,};return { childContinuationToken, runInput };}diff --git a/packages/eve/src/tracing/agent-action-instrumentation.ts b/packages/eve/src/tracing/agent-action-instrumentation.tsindex f294d115a..90dadc980 100644--- a/packages/eve/src/tracing/agent-action-instrumentation.ts+++ b/packages/eve/src/tracing/agent-action-instrumentation.ts@@ -16,7 +16,7 @@ import type {InstrumentationProviderDefinition,} from "#instrumentation/lifecycle.js";import { actionIdempotencyKey, attemptIdempotencyKey } from "#instrumentation/lifecycle.js";-import { agentTraceIdentityAttributes } from "#tracing/agent-otel-attributes.js";+import { agentTraceIdentityAttributes, traceSessionIdOf } from "#tracing/agent-otel-attributes.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";@@ -79,6 +79,7 @@ export function createAgentActionInstrumentation(input: {traceId: traceContext.traceId,},rootSessionId: event.scope.rootSessionId ?? event.scope.sessionId,+ traceSessionId: traceSessionIdOf(event.scope),sessionId: event.scope.sessionId,spanId: input.idGenerator.deriveSpanId(`action:${event.idempotencyKey}`),startTimeMs: Date.now(),@@ -123,6 +124,7 @@ export function createAgentActionInstrumentation(input: {...agentSpanNamingAttributes(AGENT_SPAN_NAMES.action),...agentTraceIdentityAttributes({rootSessionId: state.rootSessionId,+ traceSessionId: state.traceSessionId,sessionId: state.sessionId,}),...(invocationdiff --git a/packages/eve/src/tracing/agent-approval-instrumentation.ts b/packages/eve/src/tracing/agent-approval-instrumentation.tsindex 9955e4c0f..5fde7f5d5 100644--- a/packages/eve/src/tracing/agent-approval-instrumentation.ts+++ b/packages/eve/src/tracing/agent-approval-instrumentation.ts@@ -14,7 +14,8 @@ import type {import type { JsonValue } from "#shared/json.js";import { contentAttribute } from "#tracing/agent-otel-content.js";import { agentSpanNamingAttributes } from "#tracing/agent-span-naming.js";-import { agentTraceIdentityAttributes } from "#tracing/agent-otel-attributes.js";+import { agentTraceIdentityAttributes, traceSessionIdOf } from "#tracing/agent-otel-attributes.js";+import { decodeTraceSessionId } from "#tracing/agent-trace-context-codec.js";import { AGENT_SPAN_NAMES } from "#tracing/agent-span-contract.js";import { recordAgentSpanError as recordError } from "#tracing/agent-span-error.js";import { withChannelAudience } from "#tracing/channel-audience-context.js";@@ -23,6 +24,7 @@ import type { AgentSpanIdGenerator } from "#tracing/agent-span-id-generator.js";import { normalizeChannelAudience, type ChannelAudience } from "#shared/channel-audience.js";interface AgentApprovalSpanState {+ readonly traceSessionId: string;readonly actionCallId: string;readonly actionName: string;readonly attemptIndex: number;@@ -74,6 +76,7 @@ export function createAgentApprovalInstrumentation(input: {},requestId: event.requestId,rootSessionId: event.scope.rootSessionId ?? event.scope.sessionId,+ traceSessionId: traceSessionIdOf(event.scope),sessionId: event.scope.sessionId,startTimeMs: Date.now(),stepIndex: event.scope.stepIndex,@@ -110,6 +113,7 @@ export function createAgentApprovalInstrumentation(input: {...agentSpanNamingAttributes("agent.approval"),...agentTraceIdentityAttributes({rootSessionId: state.rootSessionId,+ traceSessionId: state.traceSessionId,sessionId: state.sessionId,}),},@@ -179,6 +183,7 @@ function readState(value: unknown): AgentApprovalSpanState | undefined {requestAttribute,requestId: state["requestId"],rootSessionId: state["rootSessionId"],+ traceSessionId: decodeTraceSessionId(state),sessionId: state["sessionId"],startTimeMs: state["startTimeMs"],stepIndex: state["stepIndex"],diff --git a/packages/eve/src/tracing/agent-invocation-coordinator.test.ts b/packages/eve/src/tracing/agent-invocation-coordinator.test.tsindex c0de53c7b..f25b222c9 100644--- a/packages/eve/src/tracing/agent-invocation-coordinator.test.ts+++ b/packages/eve/src/tracing/agent-invocation-coordinator.test.ts@@ -35,6 +35,7 @@ describe("resolveToolCallAgentTrace", () => {store.setTurn("session-1", "turn-1", {context: action.parent,rootSessionId: "session-1",+ traceSessionId: "session-1",sequence: 0,startTimeMs: 1,});@@ -72,6 +73,7 @@ function workflowAction() {traceId: "1".repeat(32),},rootSessionId: "session-1",+ traceSessionId: "session-1",sessionId: "session-1",spanId: "3".repeat(16),startTimeMs: 1,diff --git a/packages/eve/src/tracing/agent-memory-instrumentation.ts b/packages/eve/src/tracing/agent-memory-instrumentation.tsindex fbd1af6e4..63066d51e 100644--- a/packages/eve/src/tracing/agent-memory-instrumentation.ts+++ b/packages/eve/src/tracing/agent-memory-instrumentation.ts@@ -23,7 +23,7 @@ import {resolveForwardedTraceSeed,} from "#shared/forwarded-trace-policy.js";import { genAiMemoryRecordsAttribute } from "#tracing/agent-otel-content.js";-import { agentTraceIdentityAttributes } from "#tracing/agent-otel-attributes.js";+import { agentTraceIdentityAttributes, traceSessionIdOf } from "#tracing/agent-otel-attributes.js";import { isAgentTraceContext, markAgentTraceContext } from "#tracing/agent-trace-context.js";import { recordAgentSpanError } from "#tracing/agent-span-error.js";import { agentSpanNamingAttributes } from "#tracing/agent-span-naming.js";@@ -164,6 +164,7 @@ function memorySpanAttributes(...agentSpanNamingAttributes(event.operationName, event.operationName),...agentTraceIdentityAttributes({rootSessionId: event.rootSessionId,+ traceSessionId: traceSessionIdOf(event),sessionId: event.sessionId,}),};diff --git a/packages/eve/src/tracing/agent-otel-attributes.test.ts b/packages/eve/src/tracing/agent-otel-attributes.test.tsindex 29234205e..77ed5e893 100644--- a/packages/eve/src/tracing/agent-otel-attributes.test.ts+++ b/packages/eve/src/tracing/agent-otel-attributes.test.ts@@ -1,7 +1,7 @@import { afterEach, describe, expect, it, vi } from "vitest";import { ContextContainer, contextStorage } from "#context/container.js";-import { ConversationIdKey } from "#context/keys.js";+import { ConversationIdKey, TraceRootKey } from "#context/keys.js";import { agentTraceIdentityAttributes } from "#tracing/agent-otel-attributes.js";afterEach(() => {@@ -9,7 +9,43 @@ afterEach(() => {});describe("agentTraceIdentityAttributes", () => {- const input = { rootSessionId: "root-session", sessionId: "session-1" };+ it("uses the lineage fallback when a remote entry has no conversation in context", () => {+ vi.stubEnv("VERCEL_ENV", "preview");+ const context = new ContextContainer();+ context.set(TraceRootKey, { kind: "own" });+ contextStorage.run(context, () => {+ expect(+ agentTraceIdentityAttributes({+ rootSessionId: "caller-root",+ sessionId: "remote-session",+ traceSessionId: "remote-session",+ }),+ ).toMatchObject({+ "gen_ai.conversation.id": "caller-root",+ "vercel.session_id": "remote-session",+ "agent.run.id": "remote-session",+ });+ });+ });+ const input = {+ rootSessionId: "root-session",+ sessionId: "session-1",+ traceSessionId: "root-session",+ };+ it("uses the explicit trace session when active context belongs to another session", () => {+ vi.stubEnv("VERCEL_ENV", "preview");+ const context = new ContextContainer();+ context.set(TraceRootKey, { kind: "inherited", sessionId: "unrelated-session" });+ contextStorage.run(context, () => {+ expect(+ agentTraceIdentityAttributes({+ rootSessionId: "caller-root",+ sessionId: "remote",+ traceSessionId: "remote",+ })["vercel.session_id"],+ ).toBe("remote");+ });+ });it("uses the GenAI conversation identifier outside Vercel", () => {vi.stubEnv("VERCEL_ENV", undefined);diff --git a/packages/eve/src/tracing/agent-otel-attributes.ts b/packages/eve/src/tracing/agent-otel-attributes.tsindex 4fd91029c..9eb30cc37 100644--- a/packages/eve/src/tracing/agent-otel-attributes.ts+++ b/packages/eve/src/tracing/agent-otel-attributes.ts@@ -1,9 +1,18 @@import { resolveConversationId } from "#shared/conversation-identity.js";import { AGENT_TRACE_SCHEMA_VERSION } from "#tracing/agent-span-contract.js";+export function traceSessionIdOf(scope: {+ readonly traceSessionId?: string;+ readonly rootSessionId?: string;+ readonly sessionId: string;+}): string {+ return scope.traceSessionId ?? scope.rootSessionId ?? scope.sessionId;+}+export function agentTraceIdentityAttributes(input: {readonly rootSessionId: string;readonly sessionId: string;+ readonly traceSessionId: string;}): Record<string, string | number> {const conversationId = resolveConversationId(input.rootSessionId);const attributes: Record<string, string | number> = {@@ -12,7 +21,7 @@ export function agentTraceIdentityAttributes(input: {"gen_ai.conversation.id": conversationId,};if (process.env.VERCEL_ENV !== undefined) {- attributes["vercel.session_id"] = input.rootSessionId;+ attributes["vercel.session_id"] = input.traceSessionId;}return attributes;}diff --git a/packages/eve/src/tracing/agent-otel-provider.test.ts b/packages/eve/src/tracing/agent-otel-provider.test.tsindex fe9ed6fc8..e0e6fe7cd 100644--- a/packages/eve/src/tracing/agent-otel-provider.test.ts+++ b/packages/eve/src/tracing/agent-otel-provider.test.ts@@ -1156,6 +1156,7 @@ describe("createAgentOtelInstrumentation", () => {delivery: started.delivery,policyAgentName: started.agentName,rootSessionId: started.rootSessionId,+ traceSessionId: started.rootSessionId,sequence: 0,sessionId: started.sessionId,turnId: "turn_0",@@ -1227,6 +1228,7 @@ describe("createAgentOtelInstrumentation", () => {idempotencyKey: `channel-delivery:remote-session:${delivery.deliveryId}`,parentTraceContext,rootSessionId: "parent-session",+ traceSessionId: "parent-session",sequence: 0,sessionId: "remote-session",turnId: "turn-remote",@@ -1244,6 +1246,7 @@ describe("createAgentOtelInstrumentation", () => {delivery,policyAgentName: "weather",rootSessionId: "parent-session",+ traceSessionId: "parent-session",sequence: 0,sessionId: "remote-session",turnId: "turn-remote",@@ -1663,6 +1666,7 @@ describe("createAgentOtelInstrumentation", () => {context: spanContext("1", "2"),decision: { action: "record", recordInputs: false, recordOutputs: true },rootSessionId: "session-policy",+ traceSessionId: "session-policy",});const runtime = createRuntime(stateStore, null);@@ -1678,6 +1682,7 @@ describe("createAgentOtelInstrumentation", () => {context: spanContext("1", "2"),decision: { action: "record", recordInputs: true, recordOutputs: false },rootSessionId: "session-forwarded-private",+ traceSessionId: "session-forwarded-private",});const runtime = createRuntime(stateStore, null);const ctx = new ContextContainer();@@ -1798,6 +1803,7 @@ describe("createAgentOtelInstrumentation", () => {channelAudience: "public",context: spanContext("1", "2"),rootSessionId: "session-sampled",+ traceSessionId: "session-sampled",});const runtime = createRuntime(stateStore, null);@@ -1814,6 +1820,7 @@ describe("createAgentOtelInstrumentation", () => {channelAudience: "public",context: { ...spanContext("1", "2"), traceFlags: 0 },rootSessionId: "session-unsampled",+ traceSessionId: "session-unsampled",});const runtime = createRuntime(stateStore, null);diff --git a/packages/eve/src/tracing/agent-otel-provider.ts b/packages/eve/src/tracing/agent-otel-provider.tsindex a6ab0095b..3d2ef98be 100644--- a/packages/eve/src/tracing/agent-otel-provider.ts+++ b/packages/eve/src/tracing/agent-otel-provider.ts@@ -30,7 +30,7 @@ import { createAgentChannelDeliveryInstrumentation } from "#tracing/agent-channeimport { createAgentToolInstrumentation } from "#tracing/agent-tool-instrumentation.js";import { agentSpanNamingAttributes } from "#tracing/agent-span-naming.js";import { markAgentTraceContext } from "#tracing/agent-trace-context.js";-import { agentTraceIdentityAttributes } from "#tracing/agent-otel-attributes.js";+import { agentTraceIdentityAttributes, traceSessionIdOf } from "#tracing/agent-otel-attributes.js";import * as runtimeAttributes from "#tracing/agent-otel-runtime-context.js";import { createAgentMemoryInstrumentation } from "#tracing/agent-memory-instrumentation.js";import {@@ -375,6 +375,7 @@ export function createAgentOtelInstrumentation(...agentSpanNamingAttributes(modelSpanName(event.model.modelId), "chat"),...agentTraceIdentityAttributes({rootSessionId: event.scope.rootSessionId ?? event.scope.sessionId,+ traceSessionId: traceSessionIdOf(event.scope),sessionId: event.scope.sessionId,}),...runtimeAttributes.runtimeContextAttributes(event.runtimeContext),diff --git a/packages/eve/src/tracing/agent-otel-runtime-context.test.ts b/packages/eve/src/tracing/agent-otel-runtime-context.test.tsindex 244af61a9..6c6a93b3b 100644--- a/packages/eve/src/tracing/agent-otel-runtime-context.test.ts+++ b/packages/eve/src/tracing/agent-otel-runtime-context.test.ts@@ -13,6 +13,7 @@ function turn(overrides: Partial<AgentTurnTraceState> = {}): AgentTurnTraceStatereturn {context,rootSessionId: "root-session",+ traceSessionId: "root-session",sequence: 0,startTimeMs: 1,...overrides,@@ -27,12 +28,66 @@ function session(overrides: Partial<AgentSessionTraceState> = {}): AgentSessionTcontext,decision: { action: "record", recordInputs: true, recordOutputs: true },rootSessionId: "root-session",+ traceSessionId: "root-session",title: "Call the general agent",...overrides,};}describe("agentActivationAttributes", () => {+ it.each([+ {+ name: "root",+ sessionId: "root-session",+ traceSessionId: "root-session",+ parent: undefined,+ ownsMetadata: true,+ },+ {+ name: "remote",+ sessionId: "remote-session",+ traceSessionId: "remote-session",+ parent: "caller",+ ownsMetadata: true,+ },+ {+ name: "remote local child",+ sessionId: "child",+ traceSessionId: "remote-session",+ parent: "remote-session",+ ownsMetadata: false,+ },+ {+ name: "local child",+ sessionId: "child",+ traceSessionId: "root-session",+ parent: "root-session",+ ownsMetadata: false,+ },+ ])(+ "derives $name metadata ownership from explicit session identity",+ ({ sessionId, traceSessionId, parent, ownsMetadata }) => {+ const attributes = agentActivationAttributes({+ frameworkVersion: "test",+ session: session({ traceSessionId, channelKind: "http", title: "Task" }),+ sessionId,+ turnId: "turn_0",+ turn: turn({+ traceSessionId,+ parentLineage:+ parent === undefined+ ? undefined+ : { sessionId: parent, callId: "call", turnId: "turn_0" },+ }),+ });+ expect(attributes["agent.channel.kind"]).toBe(ownsMetadata ? "http" : undefined);+ expect(attributes["agent.session.origin"]).toBe(ownsMetadata ? "channel" : undefined);+ expect(attributes["agent.session.title"]).toBe(ownsMetadata ? "Task" : undefined);+ expect(attributes["agent.run.type"]).toBe(parent === undefined ? "session" : "subagent");+ expect(attributes["agent.parent_run.id"]).toBe(parent);+ expect(attributes["agent.parent_call.id"]).toBe(parent === undefined ? undefined : "call");+ },+ );it("emits root-session inventory and trace-policy metadata", () => {expect(agentActivationAttributes({diff --git a/packages/eve/src/tracing/agent-otel-runtime-context.ts b/packages/eve/src/tracing/agent-otel-runtime-context.tsindex ba37d9fb4..fd6b7a928 100644--- a/packages/eve/src/tracing/agent-otel-runtime-context.ts+++ b/packages/eve/src/tracing/agent-otel-runtime-context.ts@@ -2,7 +2,7 @@ import type { AgentSessionTraceState, AgentTurnTraceState } from "#tracing/agentimport type { InstrumentationStepAttemptStartedEvent } from "#instrumentation/lifecycle.js";import { agentSpanNamingAttributes } from "#tracing/agent-span-naming.js";import { agentInvocationSpanName } from "#tracing/agent-span-contract.js";-import { agentTraceIdentityAttributes } from "#tracing/agent-otel-attributes.js";+import { agentTraceIdentityAttributes, traceSessionIdOf } from "#tracing/agent-otel-attributes.js";import { normalizeInstrumentationChannelKind } from "#internal/instrumentation.js";type SpanAttributePrimitive = string | number | boolean;@@ -21,7 +21,12 @@ export function agentActivationAttributes(input: {const recordsOutputs = recordsTrace && input.session?.decision?.recordOutputs === true;const parentLineage = input.turn.parentLineage ?? input.session?.parentLineage;const isSubagent = parentLineage !== undefined;- const channelClassification = agentChannelClassificationAttributes(input.session, input.turn);+ const ownsSessionMetadata = !isSubagent || input.turn.traceSessionId === input.sessionId;+ const channelClassification = agentChannelClassificationAttributes(+ input.session,+ input.turn,+ input.sessionId,+ );const scheduleId = isSubagent ? undefined : input.session?.scheduleId;return {"agent.framework.name": "eve",@@ -38,7 +43,7 @@ export function agentActivationAttributes(input: {"agent.parent_run.id": parentLineage?.sessionId,"agent.run.type": isSubagent ? "subagent" : "session","agent.schedule.id": scheduleId,- "agent.session.title": !isSubagent && recordsInputs ? input.session?.title : undefined,+ "agent.session.title": ownsSessionMetadata && recordsInputs ? input.session?.title : undefined,"agent.subagent.name": input.turn.subagentName,"agent.trace.content.input": recordsInputs,"agent.trace.content.output": recordsOutputs,@@ -49,6 +54,7 @@ export function agentActivationAttributes(input: {...agentSpanNamingAttributes(agentInvocationSpanName(input.agentName), "invoke_agent"),...agentTraceIdentityAttributes({rootSessionId: input.turn.rootSessionId,+ traceSessionId: input.turn.traceSessionId,sessionId: input.sessionId,}),};@@ -57,21 +63,23 @@ export function agentActivationAttributes(input: {export function agentChannelClassificationAttributes(session: AgentSessionTraceState | undefined,turn: AgentTurnTraceState,+ sessionId: string,): {readonly "agent.channel.kind": string | undefined;readonly "agent.session.origin": string | undefined;} {const isSubagent = (turn.parentLineage ?? session?.parentLineage) !== undefined;+ const ownsSessionMetadata = !isSubagent || turn.traceSessionId === sessionId;const channelKind =turn.channelDelivery?.channelKind ??- (isSubagent+ (!ownsSessionMetadata? undefined: (session?.channelKind ??(session?.channelType === undefined? undefined: normalizeInstrumentationChannelKind(session.channelType))));const origin =- isSubagent || channelKind === undefined+ !ownsSessionMetadata || channelKind === undefined? undefined: session?.scheduleId !== undefined? "schedule"@@ -89,7 +97,11 @@ export function agentStepAttributes(input: {readonly turn: AgentTurnTraceState;}) {const { event, session, turn } = input;- const channelClassification = agentChannelClassificationAttributes(session, turn);+ const channelClassification = agentChannelClassificationAttributes(+ session,+ turn,+ event.scope.sessionId,+ );return {"agent.framework.name": "eve","agent.framework.version": input.frameworkVersion,@@ -104,6 +116,7 @@ export function agentStepAttributes(input: {...agentSpanNamingAttributes("agent.step"),...agentTraceIdentityAttributes({rootSessionId: event.scope.rootSessionId ?? event.scope.sessionId,+ traceSessionId: traceSessionIdOf(event.scope),sessionId: event.scope.sessionId,}),...runtimeContextAttributes(event.runtimeContext),diff --git a/packages/eve/src/tracing/agent-otel-session-context.ts b/packages/eve/src/tracing/agent-otel-session-context.tsindex 8a35862b6..da02a5048 100644--- a/packages/eve/src/tracing/agent-otel-session-context.ts+++ b/packages/eve/src/tracing/agent-otel-session-context.ts@@ -26,6 +26,7 @@ import type { AgentTurnTraceState } from "#tracing/agent-trace-state.js";import { applyPrincipalTraceDecision } from "#instrumentation/principal-summary.js";import { normalizeInstrumentationChannelKind } from "#internal/instrumentation.js";import type { ConversationEnvironment } from "#shared/conversation-context.js";+import { traceSessionIdOf } from "#tracing/agent-otel-attributes.js";interface AgentOtelSessionContextInput {readonly environment: ConversationEnvironment;@@ -70,6 +71,7 @@ export function createAgentOtelSessionContext(context: initialSessionContext(input, event, decision),parentLineage: event.parentLineage,rootSessionId: event.rootSessionId,+ traceSessionId: traceSessionIdOf(event),scheduleId: event.scheduleId,title: event.title,};@@ -107,6 +109,7 @@ export function createAgentOtelSessionContext(initiatorPrincipal: applyPrincipalTraceDecision(event.initiatorPrincipal, session.decision),parentLineage: event.parentLineage ?? session.parentLineage,rootSessionId: event.rootSessionId,+ traceSessionId: traceSessionIdOf(event),sequence: event.sequence,startTimeMs: Date.now(),subagentName: (event.parentLineage ?? session.parentLineage)?.subagentName,diff --git a/packages/eve/src/tracing/agent-telemetry-contract.integration.test.ts b/packages/eve/src/tracing/agent-telemetry-contract.integration.test.tsindex 379550c6c..258ba9fa2 100644--- a/packages/eve/src/tracing/agent-telemetry-contract.integration.test.ts+++ b/packages/eve/src/tracing/agent-telemetry-contract.integration.test.ts@@ -16,6 +16,7 @@ import {ParentSessionKey,ParentTraceContextKey,SessionTraceSeedKey,+ TraceRootKey,} from "#context/keys.js";import { deserializeContext, serializeContext } from "#context/serialize.js";import {@@ -125,6 +126,178 @@ function scopeFor(sessionId: string, audience: "public" | "private"): Instrument}describe("exported agent telemetry contract", () => {+ it("preserves explicit trace-session identity on every remote and local-child span", async () => {+ vi.stubEnv("VERCEL_ENV", "preview");+ const runtime = { ...createRuntime(), memoryOperations: true };+ try {+ for (const sessionId of ["remote", "local-child"]) {+ const ctx = contextFor("public");+ ctx.set(ConversationIdKey, "caller-conversation");+ ctx.set(+ TraceRootKey,+ sessionId === "remote" ? { kind: "own" } : { kind: "inherited", sessionId: "remote" },+ );+ ctx.set(ParentSessionKey, {+ callId: "dispatch",+ rootSessionId: "caller-root",+ sessionId: sessionId === "remote" ? "caller" : "remote",+ turn: { id: "turn_0", sequence: 0 },+ });+ const bound = bindInstrumentationRuntime(runtime, ctx, {+ agentName: sessionId,+ rootSessionId: "caller-root",+ sessionId,+ })!;+ const hooks = runtime.hooks.forTrace!(traceContext(sessionId, "public"));+ await contextStorage.run(ctx, async () => {+ await bound.preparePreamble({ sequence: 0, sessionStarted: false, turnId: "turn_0" });+ await bound.prepareExecution().runStep(+ {+ environment: "production",+ eveVersion: "test",+ hasInput: true,+ session: { sessionId },+ },+ async (step) => {+ const attempt = step.prepareAttempt({+ attemptIndex: 0,+ stepIndex: 0,+ turnId: "turn_0",+ });+ const scope = attempt.scope;+ await hooks.publish({+ type: "step.attempt.started",+ idempotencyKey: attemptIdempotencyKey(scope),+ scope,+ operation: { modelId: "test", operationId: "ai.streamText", provider: "test" },+ });+ const actionKey = actionIdempotencyKey(sessionId, "turn_0", "tool");+ const toolKey = toolCallIdempotencyKey(scope, "tool", 0);+ const modelKey = modelCallIdempotencyKey(scope, 0, 0);+ await hooks.publish({+ type: "action.started",+ idempotencyKey: actionKey,+ scope,+ callId: "tool",+ name: "inspect",+ kind: "tool-call",+ input: {},+ });+ await hooks.publish({+ type: "tool.call.started",+ idempotencyKey: toolKey,+ scope,+ callId: "tool",+ toolName: "inspect",+ input: {},+ });+ await hooks.publish({+ type: "model.call.started",+ idempotencyKey: modelKey,+ scope,+ model: { modelId: "test", provider: "test" },+ });+ await hooks.publish({+ type: "model.call.completed",+ idempotencyKey: modelKey,+ scope,+ finishReason: "stop",+ content: [],+ usage: { inputTokens: 1, outputTokens: 1 },+ });+ const approvalKey = inputIdempotencyKey(sessionId, "turn_0", "approval");+ await hooks.publish({+ type: "input.requested",+ idempotencyKey: approvalKey,+ scope,+ requestId: "approval",+ kind: "tool-approval",+ action: { callId: "tool", name: "inspect" },+ request: { prompt: "Approve" },+ });+ // State must preserve identity when execution resumes with a different context.+ const saved = serializeContext(ctx);+ const restored = await deserializeContext(saved);+ await contextStorage.run(restored, async () => {+ await hooks.publish({+ type: "input.resolved",+ idempotencyKey: approvalKey,+ scope,+ requestId: "approval",+ kind: "tool-approval",+ outcome: "approved",+ response: {},+ });+ await hooks.publish({+ type: "tool.call.completed",+ idempotencyKey: toolKey,+ scope,+ output: { type: "result", output: {} },+ });+ await hooks.publish({+ type: "action.completed",+ idempotencyKey: actionKey,+ scope,+ outcome: "completed",+ output: { type: "result", output: {} },+ });+ });+ await bound.memory!.execute(+ {+ idempotencyKey: `memory:${sessionId}`,+ operationName: "search_memory",+ phase: "turn.started",+ slot: "notes",+ storeId: "store",+ turnId: "turn_0",+ },+ async () => ({ value: undefined }),+ );+ await attempt.complete();+ },+ );+ await hooks.publish({+ type: "turn.completed",+ idempotencyKey: turnIdempotencyKey(sessionId, "turn_0"),+ sessionId,+ turnId: "turn_0",+ });+ await hooks.publish({+ type: "session.waiting",+ idempotencyKey: sessionIdempotencyKey(sessionId),+ sessionId,+ turnId: "turn_0",+ });+ });+ }+ await runtime.forceFlush();+ const owned = runtime.exporter+ .getFinishedSpans()+ .filter((span) => typeof span.attributes["agent.run.id"] === "string");+ for (const runId of ["remote", "local-child"]) {+ const spans = owned.filter((span) => span.attributes["agent.run.id"] === runId);+ expect(spans.map((span) => span.name).sort()).toEqual(+ [+ `invoke_agent ${runId}`,+ "agent.step",+ "chat test",+ "execute_tool inspect",+ "agent.action",+ "agent.approval",+ "search_memory",+ ].sort(),+ );+ for (const span of spans) {+ expect(span.attributes["vercel.session_id"]).toBe("remote");+ expect(span.attributes["gen_ai.conversation.id"]).toBe("caller-conversation");+ }+ }+ } finally {+ await runtime.shutdown();+ vi.unstubAllEnvs();+ }+ });+it.each(["public", "private"] as const)("round-trips the normalized %s v4 trace forest through OTLP",async (audience) => {diff --git a/packages/eve/src/tracing/agent-tool-instrumentation.ts b/packages/eve/src/tracing/agent-tool-instrumentation.tsindex fa0c0c823..baac9ccb0 100644--- a/packages/eve/src/tracing/agent-tool-instrumentation.ts+++ b/packages/eve/src/tracing/agent-tool-instrumentation.ts@@ -17,7 +17,7 @@ import type {import { actionIdempotencyKey } from "#instrumentation/lifecycle.js";import { contentAttribute } from "#tracing/agent-otel-content.js";import { agentSpanNamingAttributes } from "#tracing/agent-span-naming.js";-import { agentTraceIdentityAttributes } from "#tracing/agent-otel-attributes.js";+import { agentTraceIdentityAttributes, traceSessionIdOf } from "#tracing/agent-otel-attributes.js";import { withChannelAudience } from "#tracing/channel-audience-context.js";import type { AgentSpanIdGenerator } from "#tracing/agent-span-id-generator.js";import type { AgentActionContext } from "#tracing/agent-action-instrumentation.js";@@ -251,6 +251,7 @@ function toolAttributes(...agentSpanNamingAttributes(`execute_tool ${event.toolName}`, "execute_tool"),...agentTraceIdentityAttributes({rootSessionId: event.scope.rootSessionId ?? event.scope.sessionId,+ traceSessionId: traceSessionIdOf(event.scope),sessionId: event.scope.sessionId,}),};diff --git a/packages/eve/src/tracing/agent-trace-context-codec.ts b/packages/eve/src/tracing/agent-trace-context-codec.tsindex 60a982418..decc521d7 100644--- a/packages/eve/src/tracing/agent-trace-context-codec.ts+++ b/packages/eve/src/tracing/agent-trace-context-codec.ts@@ -13,6 +13,18 @@ import { isInstrumentationPrincipalType } from "#instrumentation/lifecycle.js";export const AGENT_TRACE_CONTEXT_KEY = "eve.harness.agentTrace";+export function decodeTraceSessionId(state: {+ readonly traceSessionId?: unknown;+ readonly rootSessionId?: unknown;+}): string {+ // Persisted state from before trace-session identity uses the lineage root.+ return typeof state.traceSessionId === "string"+ ? state.traceSessionId+ : typeof state.rootSessionId === "string"+ ? state.rootSessionId+ : "";+}+export interface AgentTraceContextState {readonly actionAnchors: Readonly<Record<string, AgentActionTraceState>>;readonly actions: Readonly<Record<string, AgentActionTraceState>>;@@ -84,6 +96,7 @@ function deserializeSession(value: unknown): AgentSessionTraceState | undefineddecision: readInstrumentationDecision(value.decision),parentLineage: deserializeParentLineage(value.parentLineage),rootSessionId: typeof value.rootSessionId === "string" ? value.rootSessionId : "",+ traceSessionId: decodeTraceSessionId(value),scheduleId: typeof value.scheduleId === "string" ? value.scheduleId : undefined,title: typeof value.title === "string" ? value.title : undefined,};@@ -102,6 +115,7 @@ function deserializeTurn(value: unknown): AgentTurnTraceState | undefined {modelUsage: deserializeModelUsage(value.modelUsage),parentLineage: deserializeParentLineage(value.parentLineage),rootSessionId: typeof value.rootSessionId === "string" ? value.rootSessionId : "",+ traceSessionId: decodeTraceSessionId(value),sequence: typeof value.sequence === "number" ? value.sequence : 0,startTimeMs: value.startTimeMs,subagentName: typeof value.subagentName === "string" ? value.subagentName : undefined,@@ -164,6 +178,7 @@ function deserializeAction(value: unknown): AgentActionTraceState | undefined {name: value.name,parent: value.parent,rootSessionId: value.rootSessionId,+ traceSessionId: decodeTraceSessionId(value),sessionId: value.sessionId,spanId: value.spanId,startTimeMs: value.startTimeMs,diff --git a/packages/eve/src/tracing/agent-trace-context-store.test.ts b/packages/eve/src/tracing/agent-trace-context-store.test.tsindex e52d40915..364ff5576 100644--- a/packages/eve/src/tracing/agent-trace-context-store.test.ts+++ b/packages/eve/src/tracing/agent-trace-context-store.test.ts@@ -22,6 +22,7 @@ describe("ContextAgentTraceStateStore", () => {channelType: "http",context: spanContext("1", "2"),rootSessionId: "session-1",+ traceSessionId: "session-1",});store.setTurn("session-1", "turn-1", {channelDelivery: {@@ -38,6 +39,7 @@ describe("ContextAgentTraceStateStore", () => {modelUsage: { inputTokens: 12, outputTokens: 4 },caller: { ...spanContext("4", "2"), isRemote: true },rootSessionId: "session-1",+ traceSessionId: "session-1",sequence: 0,startTimeMs: 1_700_000_000_000,subagentName: "researcher",@@ -115,11 +117,13 @@ describe("ContextAgentTraceStateStore", () => {store.setSession("session-1", {context: spanContext("1", "2"),rootSessionId: "session-1",+ traceSessionId: "session-1",});store.setTurn("session-1", "turn-1", {context: spanContext("1", "3"),caller: spanContext("4", "2"),rootSessionId: "session-1",+ traceSessionId: "session-1",sequence: 0,startTimeMs: 1_700_000_000_000,});@@ -139,6 +143,7 @@ describe("ContextAgentTraceStateStore", () => {context: spanContext("1", "3"),caller: spanContext("4", "2"),rootSessionId: "session-1",+ traceSessionId: "session-1",sequence: 0,startTimeMs: 1_700_000_000_000,});@@ -171,6 +176,7 @@ describe("ContextAgentTraceStateStore", () => {new ContextAgentTraceStateStore().setSession("session-1", {context: spanContext("1", "2"),rootSessionId: "session-1",+ traceSessionId: "session-1",});});@@ -200,10 +206,12 @@ describe("readTurnTraceContext", () => {context: spanContext("1", "2"),decision: { action: "record", recordInputs: true, recordOutputs: false },rootSessionId: "session-1",+ traceSessionId: "session-1",});new ContextAgentTraceStateStore().setTurn("session-1", "turn-1", {context: spanContext("3", "4"),rootSessionId: "session-1",+ traceSessionId: "session-1",sequence: 0,startTimeMs: 1,});@@ -230,10 +238,12 @@ describe("readTurnTraceContext", () => {context: spanContext("1", "2"),decision: { action: "record", recordInputs: false, recordOutputs: true },rootSessionId: "session-1",+ traceSessionId: "session-1",});store.setTurn("session-1", "turn-1", {context: spanContext("3", "4"),rootSessionId: "session-1",+ traceSessionId: "session-1",sequence: 0,startTimeMs: 1,});@@ -267,6 +277,7 @@ describe("readActionTraceContext", () => {name: "researcher",parent: spanContext("1", "2"),rootSessionId: "session-1",+ traceSessionId: "session-1",sessionId: "session-1",spanId: "3".repeat(16),startTimeMs: 1_700_000_000_000,@@ -298,6 +309,7 @@ describe("readActionTraceContext", () => {context: spanContext("1", "2"),decision: { action: "record", recordInputs: true, recordOutputs: false },rootSessionId: "session-1",+ traceSessionId: "session-1",});store.setAction("action:session-1:turn-1:call-1", {attemptIndex: 0,@@ -306,6 +318,7 @@ describe("readActionTraceContext", () => {name: "researcher",parent: spanContext("1", "2"),rootSessionId: "session-1",+ traceSessionId: "session-1",sessionId: "session-1",spanId: "3".repeat(16),startTimeMs: 1_700_000_000_000,diff --git a/packages/eve/src/tracing/agent-trace-retention.test.ts b/packages/eve/src/tracing/agent-trace-retention.test.tsindex 44e421f04..599472f40 100644--- a/packages/eve/src/tracing/agent-trace-retention.test.ts+++ b/packages/eve/src/tracing/agent-trace-retention.test.ts@@ -15,6 +15,7 @@ const anchor = {name: "workflow",parent: { spanId: "1".repeat(16), traceFlags: 1, traceId: "2".repeat(32) },rootSessionId: "session",+ traceSessionId: "session",sessionId: "session",spanId: "3".repeat(16),startTimeMs: 1,diff --git a/packages/eve/src/tracing/agent-trace-state.ts b/packages/eve/src/tracing/agent-trace-state.tsindex ade39d6fa..caafd0bee 100644--- a/packages/eve/src/tracing/agent-trace-state.ts+++ b/packages/eve/src/tracing/agent-trace-state.ts@@ -12,6 +12,7 @@ import type { ChannelAudience } from "#shared/channel-audience.js";import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";export interface AgentSessionTraceState {+ readonly traceSessionId: string;readonly channelAudience?: ChannelAudience;readonly agentName?: string;readonly channelKind?: string;@@ -25,6 +26,7 @@ export interface AgentSessionTraceState {}export interface AgentTurnTraceState {+ readonly traceSessionId: string;readonly caller?: SpanContext;readonly channelDelivery?: AgentTurnChannelDeliveryTraceState;readonly context: SpanContext;@@ -51,6 +53,7 @@ export interface AgentTurnChannelDeliveryTraceState {}export interface AgentActionTraceState {+ readonly traceSessionId: string;readonly attemptIndex: number;readonly callId: string;readonly channelAudience?: ChannelAudience;