The Open Framework for Building Agents
refactor(eve): rely on native trace topology (#2458)
Chad Hietala7c5a69ec45d3
diff --git a/.changeset/remove-agent-trace-windowing.md b/.changeset/remove-agent-trace-windowing.mdnew file mode 100644index 000000000..3fa453ab8--- /dev/null+++ b/.changeset/remove-agent-trace-windowing.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Keep durable agent sessions on their persisted OpenTelemetry trace instead of rotating after 200 turns. Agent Trace schema version 2 relies on native trace parentage instead of window, root-session, and duplicated parent-lineage attributes.diff --git a/docs/reference/cli.md b/docs/reference/cli.mdindex 979beafc2..cd3666434 100644--- a/docs/reference/cli.md+++ b/docs/reference/cli.md@@ -296,11 +296,9 @@ Reads the immutable OTLP/JSON segments under `.eve/traces/v1`, so `eve dev` needSpan rows carry inline metrics when the span recorded them — `↑input`/`↓output` token counts, gateway cost, and the tool name for `ai.toolCall` spans — and the header aggregates models, token totals, cost, and error count across the trace's step spans. `--verbose` expands each span under its tree row: status (with the error message on failures), timing, ids, every attribute (prompts, responses, and tool payloads as transcripts or pretty-printed JSON), and every span event with its offset from span start. `--json` prints the same records as JSON, one object per selected trace.-A subagent keeps its own session id but records into the trace its parent had open at dispatch, so delegated work appears under the session that caused it, tagged with `agent.root.session.id`. Either session id resolves to that trace. A remote agent traces under its own deployment and is not recorded here.+A local subagent keeps its own session id but records into the parent trace. Its turn is parented to the `agent.action` span that dispatched it, so the span tree carries the relationship without duplicate lineage attributes; `agent.subagent.name` remains on the child turn as a standalone label. Either session id resolves to that trace. Remote agents propagate the parent trace context over `traceparent`.-A session long enough to outgrow one trace — far longer than anything you will drive locally — continues into a new one. Each is a session window, numbered from zero on `agent.session.window`; passing a session id shows every window it produced, oldest first, and a trace id shows just that window.--One parent turn can dispatch several subagents into the same window, so a child's turn spans name the dispatch: `agent.parent.session.id`, `agent.parent.turn.id`, and `agent.parent.call_id` identify the tool call that created the child, and `agent.subagent.name` the subagent it invoked. Top-level sessions carry none of these.+A durable session keeps one persisted trace context across turns and worker resumptions. Independently replayed attempts can still produce another trace; passing the session id shows every trace it produced, oldest first.Every span carries a real duration except `agent.session`: an idle session never closes, so it is recorded as a zero-duration marker and the span tree shows its descendant extent instead. A turn's span is written when the turn settles, so a running turn shows only its steps.diff --git a/packages/eve/src/cli/commands/trace.integration.test.ts b/packages/eve/src/cli/commands/trace.integration.test.tsindex 00adde570..d3d083a10 100644--- a/packages/eve/src/cli/commands/trace.integration.test.ts+++ b/packages/eve/src/cli/commands/trace.integration.test.ts@@ -76,14 +76,13 @@ describe("eve traces", () => {expect(() => resolveLocalTraces(traces, "missing")).toThrow(/No local trace matches/u);});- it("resolves a windowed session to every window, oldest first", async () => {+ it("resolves a session with multiple traces oldest first", async () => {const root = await createRoot();await writeSegment(root,TRACE_TWO,span("b", "agent.session", 100, 100, undefined, {"agent.session.id": "session-one",- "agent.session.window": 1,}),);await writeSegment(@@ -91,12 +90,10 @@ describe("eve traces", () => {TRACE_ONE,span("a", "agent.session", 10, 10, undefined, {"agent.session.id": "session-one",- "agent.session.window": 0,}),);const traces = await listLocalTraces(root);- expect(traces.map((trace) => trace.window)).toEqual([1, 0]);expect(ids(resolveLocalTraces(traces, "session-one"))).toEqual([TRACE_ONE, TRACE_TWO]);const output = collectingLogger();@@ -105,27 +102,23 @@ describe("eve traces", () => {expect(output.out[0]).toContain(TRACE_ONE);expect(output.out[0]).toContain(TRACE_TWO);expect(output.out[0]!.indexOf(TRACE_ONE)).toBeLessThan(output.out[0]!.indexOf(TRACE_TWO));- expect(output.out[0]).toContain("Window");});- it("resolves a subagent child to the parent window it recorded into", async () => {+ it("resolves a subagent child to the parent trace it recorded into", async () => {const root = await createRoot();- const window = "a".repeat(16);+ const session = "a".repeat(16);const child = "b".repeat(16);await writeSegment(root,TRACE_ONE,- span(window, "agent.session", 10, 10, undefined, {- "agent.root.session.id": "session-one",+ span(session, "agent.session", 10, 10, undefined, {"agent.session.id": "session-one",- "agent.session.window": 0,}),);await writeSegment(root,TRACE_ONE,- span(child, "agent.turn", 20, 30, window, {- "agent.root.session.id": "session-one",+ span(child, "agent.turn", 20, 30, session, {"agent.session.id": "child-one",}),);diff --git a/packages/eve/src/cli/commands/trace.ts b/packages/eve/src/cli/commands/trace.tsindex d7cae8401..3100da7a6 100644--- a/packages/eve/src/cli/commands/trace.ts+++ b/packages/eve/src/cli/commands/trace.ts@@ -168,7 +168,6 @@ function traceHeaderRows(trace: LocalTrace): { label: string; value: string }[]return [{ label: "Trace ID", value: trace.traceId },{ label: "Session ID", value: trace.sessionId ?? "unknown" },- ...(trace.window === undefined ? [] : [{ label: "Window", value: String(trace.window) }]),{ label: "Agent", value: trace.agentName ?? "unknown" },{ label: "Started", value: toDate(trace.startTimeNs).toISOString() },{@@ -221,7 +220,6 @@ function serializeTraceForJson(trace: LocalTrace): Record<string, unknown> {})),startedAt: toDate(trace.startTimeNs).toISOString(),traceId: trace.traceId,- window: trace.window ?? null,};}@@ -285,8 +283,8 @@ function renderSpanTree(/*** Extent of each span's own range unioned with its descendants', keyed by span id.*- * eve records a span with no guaranteed close — an `agent.session` window- * root, whose session may idle forever — as a zero-duration marker, because+ * eve records a span with no guaranteed close — an `agent.session` root,+ * whose session may idle forever — as a zero-duration marker, because* a span object cannot cross a durable worker boundary to be ended later.* The tree falls back to this extent for those rows so it shows where the* time went.diff --git a/packages/eve/src/cli/dev/tui/traces/trace-conversation.test.ts b/packages/eve/src/cli/dev/tui/traces/trace-conversation.test.tsindex eda777d88..7f8c6f4d4 100644--- a/packages/eve/src/cli/dev/tui/traces/trace-conversation.test.ts+++ b/packages/eve/src/cli/dev/tui/traces/trace-conversation.test.ts@@ -144,26 +144,24 @@ describe("buildConversationItems", () => {expect(items[4]?.name).toBe("get_weather");});- it("finds turns parented to a session window span", () => {- // Post-windowing capture: turns are children of the `agent.session` root,- // so turn discovery must go by name, not root position.- const window = span("0".repeat(16), "agent.session", 0, 0, undefined, {- "agent.session.window": 0,- });+ it("finds turns parented to a session span", () => {+ const session = span("0".repeat(16), "agent.session", 0, 0);const spans = weatherTurn().map((s) =>- s.name === "agent.turn" ? { ...s, parentSpanId: window.spanId } : s,+ s.name === "agent.turn" ? { ...s, parentSpanId: session.spanId } : s,);- const items = buildConversationItems(trace([window, ...spans]));+ const items = buildConversationItems(trace([session, ...spans]));expect(items.map((item) => item.kind)).toEqual(["user", "assistant", "tool"]);});it("marks turns dispatched by another turn as subagent items", () => {const parent = weatherTurn();- const childTurn = span("f".repeat(16), "agent.turn", 6000, 6000, undefined, {- "agent.parent.call_id": "call-7",- "agent.parent.session.id": "session-root",- "agent.parent.turn.id": "turn_0",- "agent.subagent.name": "echo-marker",+ const parentAction = span("e".repeat(16), "agent.action", 5900, 6000, parent[0]!.spanId, {+ "agent.action.call_id": "call-7",+ "agent.action.kind": "subagent-call",+ "agent.action.name": "echo-marker",+ "agent.turn.id": "turn_0",+ });+ const childTurn = span("f".repeat(16), "agent.turn", 6000, 6000, parentAction.spanId, {"agent.turn.id": "turn_child",});const childDelivery = delivery("3".repeat(16), 6000, "turn_child", "delegated task");@@ -180,7 +178,7 @@ describe("buildConversationItems", () => {},);const items = buildConversationItems(- trace([...parent, childTurn, childDelivery, childStep, childModel]),+ trace([...parent, parentAction, childTurn, childDelivery, childStep, childModel]),);const parentItems = items.filter((item) => item.subagent === undefined);const childItems = items.filter((item) => item.subagent !== undefined);@@ -206,11 +204,13 @@ describe("buildConversationItems", () => {"ai.prompt.messages": JSON.stringify([{ role: "user", content: "run the subagent" }]),"ai.response.text": "Dispatching.",});- const childTurn = span("f".repeat(16), "agent.turn", 30, 30, undefined, {- "agent.parent.call_id": "call-1",- "agent.parent.session.id": "session-root",- "agent.parent.turn.id": "turn_0",- "agent.subagent.name": "echo-marker",+ const parentAction = span("e".repeat(16), "agent.action", 20, 30, step1.spanId, {+ "agent.action.call_id": "call-1",+ "agent.action.kind": "subagent-call",+ "agent.action.name": "echo-marker",+ "agent.turn.id": "turn_0",+ });+ const childTurn = span("f".repeat(16), "agent.turn", 30, 30, parentAction.spanId, {"agent.turn.id": "turn_child",});const childDelivery = delivery("5".repeat(16), 30, "turn_child", "delegated task");@@ -229,6 +229,7 @@ describe("buildConversationItems", () => {parentDelivery,step1,dispatch,+ parentAction,childTurn,childDelivery,childStep,@@ -240,6 +241,7 @@ describe("buildConversationItems", () => {expect(items.map((item) => [item.kind, item.subagent !== undefined])).toEqual([["user", false],["assistant", false],+ ["tool", false],["user", true],["assistant", true],["assistant", false],diff --git a/packages/eve/src/cli/dev/tui/traces/trace-conversation.ts b/packages/eve/src/cli/dev/tui/traces/trace-conversation.tsindex fa3ebe4f8..148512fa5 100644--- a/packages/eve/src/cli/dev/tui/traces/trace-conversation.ts+++ b/packages/eve/src/cli/dev/tui/traces/trace-conversation.ts@@ -43,7 +43,7 @@ export interface ConversationItem {readonly error: boolean;}-/** Dispatch lineage for a subagent turn, read from the turn span. */+/** Dispatch lineage for a subagent turn, read from its parent action span. */export interface ConversationSubagent {/** Subagent name, when the turn arrived through the subagent adapter. */readonly name?: string;@@ -63,7 +63,7 @@ export function buildConversationItems(trace: LocalTrace): ConversationItem[] {for (const span of trace.spans) {if (span.name !== "agent.turn") continue;const turnId = stringAttribute(span, "agent.turn.id");- const subagent = turnSubagent(span);+ const subagent = turnSubagent(span, byId);if (turnId !== undefined && subagent !== undefined) subagents.set(turnId, subagent);}const entries: { readonly item: ConversationItem; readonly order: bigint }[] = [];@@ -192,14 +192,21 @@ function subagentFor(return undefined;}-/** Reads the dispatch lineage a subagent turn carries on its turn span. */-function turnSubagent(turn: LocalTraceSpan): ConversationSubagent | undefined {- const parentTurnId = stringAttribute(turn, "agent.parent.turn.id");+/** Reads subagent identity from the action span that directly parents its turn. */+function turnSubagent(+ turn: LocalTraceSpan,+ byId: ReadonlyMap<string, LocalTraceSpan>,+): ConversationSubagent | undefined {+ const parent = turn.parentSpanId === undefined ? undefined : byId.get(turn.parentSpanId);+ if (parent?.name !== "agent.action") return undefined;+ const kind = stringAttribute(parent, "agent.action.kind");+ if (kind !== "subagent-call" && kind !== "remote-agent-call") return undefined;+ const parentTurnId = stringAttribute(parent, "agent.turn.id");if (parentTurnId === undefined) return undefined;- const name = stringAttribute(turn, "agent.subagent.name");+ const name = stringAttribute(parent, "agent.action.name");return {name: name === undefined ? undefined : stripTerminalControls(name),- parentCallId: stringAttribute(turn, "agent.parent.call_id"),+ parentCallId: stringAttribute(parent, "agent.action.call_id"),parentTurnId,};}diff --git a/packages/eve/src/tracing/agent-action-instrumentation.ts b/packages/eve/src/tracing/agent-action-instrumentation.tsindex 83de88e60..166056de5 100644--- a/packages/eve/src/tracing/agent-action-instrumentation.ts+++ b/packages/eve/src/tracing/agent-action-instrumentation.ts@@ -126,7 +126,6 @@ export function createAgentActionInstrumentation(input: {"agent.action.name": state.name,"agent.framework.name": "eve","agent.framework.version": input.frameworkVersion,- "agent.root.session.id": state.rootSessionId,"agent.session.id": state.sessionId,"agent.step.attempt": state.attemptIndex,"agent.step.index": state.stepIndex,diff --git a/packages/eve/src/tracing/agent-approval-instrumentation.ts b/packages/eve/src/tracing/agent-approval-instrumentation.tsindex cff37245b..294ea6e17 100644--- a/packages/eve/src/tracing/agent-approval-instrumentation.ts+++ b/packages/eve/src/tracing/agent-approval-instrumentation.ts@@ -105,7 +105,6 @@ export function createAgentApprovalInstrumentation(input: {"agent.approval.request_id": state.requestId,"agent.framework.name": "eve","agent.framework.version": input.frameworkVersion,- "agent.root.session.id": state.rootSessionId,"agent.session.id": state.sessionId,"agent.step.attempt": state.attemptIndex,"agent.step.index": state.stepIndex,diff --git a/packages/eve/src/tracing/agent-channel-delivery-instrumentation.ts b/packages/eve/src/tracing/agent-channel-delivery-instrumentation.tsindex d363e9ac5..9da8c11a8 100644--- a/packages/eve/src/tracing/agent-channel-delivery-instrumentation.ts+++ b/packages/eve/src/tracing/agent-channel-delivery-instrumentation.ts@@ -30,7 +30,6 @@ interface ChannelDeliverySpanState {readonly requestTraceContext?: SpanContext;readonly spanId: string;readonly startTimeMs: number;- readonly window: number;}/** Builds durable channel delivery spans around the turn that consumes each request. */@@ -76,7 +75,6 @@ export function createAgentChannelDeliveryInstrumentation(input: {},spanId: input.idGenerator.deriveSpanId(`channel-delivery:${event.idempotencyKey}`),startTimeMs: Date.now(),- window: session.window,};if (inputAttribute !== undefined) state.inputAttribute = inputAttribute;if (event.delivery.requestTraceContext !== undefined) {@@ -99,7 +97,6 @@ export function createAgentChannelDeliveryInstrumentation(input: {event.turnId === undefined? undefined: await input.stateStore.getTurn(event.sessionId, event.turnId);- const session = await input.stateStore.getSession(event.sessionId);const parent =turn === undefined? state.parent@@ -125,9 +122,7 @@ export function createAgentChannelDeliveryInstrumentation(input: {"agent.framework.name": "eve","agent.framework.version": input.frameworkVersion,"agent.name": event.agentName,- "agent.root.session.id": event.rootSessionId,"agent.session.id": event.sessionId,- "agent.session.window": session?.window ?? state.window,"agent.turn.id": event.turnId,"agent.turn.sequence": event.sequence,},@@ -173,11 +168,7 @@ export function createAgentChannelDeliveryInstrumentation(input: {function readState(value: unknown): ChannelDeliverySpanState | undefined {if (!isRecord(value) || !isSpanContext(value.parent)) return undefined;- if (- typeof value.spanId !== "string" ||- typeof value.startTimeMs !== "number" ||- typeof value.window !== "number"- ) {+ if (typeof value.spanId !== "string" || typeof value.startTimeMs !== "number") {return undefined;}const requestTraceContext = isSpanContext(value.requestTraceContext)@@ -190,7 +181,6 @@ function readState(value: unknown): ChannelDeliverySpanState | undefined {requestTraceContext,spanId: value.spanId,startTimeMs: value.startTimeMs,- window: value.window,};}diff --git a/packages/eve/src/tracing/agent-otel-provider.test.ts b/packages/eve/src/tracing/agent-otel-provider.test.tsindex 849d4e849..a8dd88e78 100644--- a/packages/eve/src/tracing/agent-otel-provider.test.ts+++ b/packages/eve/src/tracing/agent-otel-provider.test.ts@@ -24,7 +24,6 @@ import { ContextAgentTraceStateStore } from "#tracing/agent-trace-context-store.import {type AgentTraceStateStore,InMemoryAgentTraceStateStore,- SESSION_WINDOW_TURN_LIMIT,} from "#tracing/agent-trace-state.js";import {createInstrumentationHooks,@@ -100,6 +99,7 @@ async function emitAttempt(input: {readonly attemptError?: Error;readonly channelAudience?: ChannelAudience;readonly hooks: InstrumentationHooks;+ readonly parentLineage?: InstrumentationParentLineage;readonly parentTraceContext?: InstrumentationTraceContext;readonly runInContext: InstrumentationContextRunner;readonly providerMetadata?: Readonly<Record<string, unknown>>;@@ -425,7 +425,7 @@ describe("createAgentOtelInstrumentation", () => {);});- it("maps channel delivery under the session window with an HTTP request link", async () => {+ it("maps channel delivery under the session trace with an HTTP request link", async () => {const runtime = createRuntime();const ctx = new ContextContainer();const requestTraceContext = {@@ -573,71 +573,6 @@ describe("createAgentOtelInstrumentation", () => {expect(turn.spanContext().traceId).toBe(parentTraceContext.traceId);});- it("moves a delivery into the same rolled window as its resulting turn", async () => {- const stateStore = new InMemoryAgentTraceStateStore();- const runtime = createRuntime(stateStore);- const ctx = new ContextContainer();- const delivery = {- channelKind: "channel:slack",- channelName: "slack",- deliveryId: "delivery-roll",- };- const idempotencyKey = `channel-delivery:session-1:${delivery.deliveryId}`;-- await contextStorage.run(ctx, async () => {- await runtime.hooks.publish({- agentName: "support",- channelKind: "channel:slack",- idempotencyKey: sessionIdempotencyKey("session-1"),- rootSessionId: "session-1",- sessionId: "session-1",- type: "session.started",- });- const session = stateStore.getSession("session-1")!;- stateStore.setSession("session-1", {- ...session,- turnsInWindow: SESSION_WINDOW_TURN_LIMIT,- });- await runtime.hooks.publish({- delivery,- idempotencyKey,- rootSessionId: "session-1",- sessionId: "session-1",- type: "channel.delivery.started",- });- await runtime.hooks.publish({- idempotencyKey: turnIdempotencyKey("session-1", "turn-roll"),- rootSessionId: "session-1",- sequence: SESSION_WINDOW_TURN_LIMIT,- sessionId: "session-1",- turnId: "turn-roll",- type: "turn.started",- });- await runtime.hooks.publish({- delivery,- idempotencyKey,- outcome: "completed",- rootSessionId: "session-1",- sequence: SESSION_WINDOW_TURN_LIMIT,- sessionId: "session-1",- turnId: "turn-roll",- type: "channel.delivery.completed",- });- await completeTurn(runtime.hooks, "session-1", "turn-roll");- });- await runtime.provider.forceFlush();-- const spans = runtime.exporter.getFinishedSpans();- const rolledSession = byName(spans, "agent.session").find(- (span) => span.attributes["agent.session.window"] === 1,- )!;- const channelDelivery = byName(spans, "agent.channel.delivery")[0]!;- const turn = byName(spans, "agent.turn")[0]!;- expect(channelDelivery.parentSpanContext?.spanId).toBe(rolledSession.spanContext().spanId);- expect(channelDelivery.spanContext().traceId).toBe(turn.spanContext().traceId);- expect(channelDelivery.attributes["agent.session.window"]).toBe(1);- });-it("emits the agent hierarchy in one session trace", async () => {const runtime = createRuntime();const delivery = runtime.tracer.startSpan("workflow.delivery");@@ -674,8 +609,7 @@ describe("createAgentOtelInstrumentation", () => {expect(session.attributes).toMatchObject({"agent.channel.audience": "public","agent.session.id": "session-1",- "agent.session.window": 0,- "agent.trace.schema.version": 1,+ "agent.trace.schema.version": 2,});expect(turn.parentSpanContext?.spanId).toBe(session.spanContext().spanId);expect(step.parentSpanContext?.spanId).toBe(turn.spanContext().spanId);@@ -708,14 +642,13 @@ describe("createAgentOtelInstrumentation", () => {expect(turn.events.map((event) => event.name)).toEqual(["turn.started", "turn.completed"]);// Turn timestamps are millisecond-quantized (`Date.now`), so the end// comparison against the step's sub-millisecond clock gets 1ms of slack.- expect(turn.attributes).toMatchObject({ "agent.name": "weather", "agent.session.window": 0 });+ expect(turn.attributes).toMatchObject({ "agent.name": "weather" });expect(nanos(turn.startTime)).toBeLessThanOrEqual(nanos(step.startTime));expect(nanos(turn.endTime)).toBeGreaterThanOrEqual(nanos(step.endTime) - 1_000_000n);expect(step.attributes).toMatchObject({"agent.framework.name": "eve","agent.model.id": "claude-test","agent.model.provider": "anthropic",- "agent.root.session.id": "session-1","agent.usage.input_tokens": 10,"agent.usage.output_tokens": 5,"gen_ai.usage.cache_creation.input_tokens": 2,@@ -725,7 +658,6 @@ describe("createAgentOtelInstrumentation", () => {"agent.action.kind": "tool-call","agent.action.name": "weather","agent.framework.name": "eve",- "agent.root.session.id": "session-1",});});@@ -1530,7 +1462,6 @@ describe("createAgentOtelInstrumentation", () => {];expect(turns).toHaveLength(2);expect(turns[0]!.spanContext().traceId).toBe(turns[1]!.spanContext().traceId);- expect(turns.every((turn) => turn.attributes["agent.session.window"] === 0)).toBe(true);const firstModel = byName(firstRuntime.exporter.getFinishedSpans(), "chat claude-test")[0]!;const secondModel = byName(secondRuntime.exporter.getFinishedSpans(), "chat claude-test")[0]!;expect(firstModel.attributes["ai.prompt.system"]).toBe(@@ -1587,7 +1518,7 @@ describe("createAgentOtelInstrumentation", () => {expect(step.spanContext().traceId).toBe(turn.spanContext().traceId);});- it("opens a fresh window when a durable attempt replays before its state checkpoints", async () => {+ it("opens a fresh trace when a durable attempt replays before its state checkpoints", async () => {const firstRuntime = createRuntime();const replayRuntime = createRuntime();await emitAttempt({@@ -1616,9 +1547,10 @@ describe("createAgentOtelInstrumentation", () => {);});- it("rolls to a new window trace once a session outgrows the turn limit", async () => {+ it("keeps a long session on one persisted trace", async () => {const runtime = createRuntime();- for (let sequence = 0; sequence <= SESSION_WINDOW_TURN_LIMIT; sequence += 1) {+ const turnCount = 201;+ for (let sequence = 0; sequence < turnCount; sequence += 1) {await publishTurnStarted({hooks: runtime.hooks,sessionId: "session-1",@@ -1633,23 +1565,14 @@ describe("createAgentOtelInstrumentation", () => {const sessions = byName(spans, "agent.session");const turns = byName(spans, "agent.turn");- expect(sessions.map((span) => span.attributes["agent.session.window"])).toEqual([0, 1]);- expect(sessions[1]!.parentSpanContext).toBeUndefined();- expect(sessions[1]!.events.map((event) => event.name)).toEqual(["session.window.opened"]);- expect(sessions[1]!.attributes["agent.session.window.previous.trace.id"]).toBe(- sessions[0]!.spanContext().traceId,- );- expect(sessions[0]!.spanContext().traceId).not.toBe(sessions[1]!.spanContext().traceId);-- // The limit counts turns per window, so the roll lands on the turn after it.- expect(turns).toHaveLength(SESSION_WINDOW_TURN_LIMIT + 1);- const rolled = turns.at(-1)!;- expect(rolled.attributes["agent.session.window"]).toBe(1);- expect(rolled.spanContext().traceId).toBe(sessions[1]!.spanContext().traceId);- expect(turns[0]!.spanContext().traceId).toBe(sessions[0]!.spanContext().traceId);+ expect(sessions).toHaveLength(1);+ expect(turns).toHaveLength(turnCount);+ expect(+ turns.every((turn) => turn.spanContext().traceId === sessions[0]!.spanContext().traceId),+ ).toBe(true);});- it("records a subagent child into the window its parent had open", async () => {+ it("records a subagent child into its parent's trace", async () => {const runtime = createRuntime();await publishTurnStarted({hooks: runtime.hooks,@@ -1658,11 +1581,17 @@ describe("createAgentOtelInstrumentation", () => {turnSequence: 0,});await runtime.provider.forceFlush();- const parentWindow = byName(runtime.exporter.getFinishedSpans(), "agent.session")[0]!;+ const parentSession = byName(runtime.exporter.getFinishedSpans(), "agent.session")[0]!;await publishTurnStarted({hooks: runtime.hooks,- parentTraceContext: parentWindow.spanContext(),+ parentLineage: {+ callId: "call-1",+ sessionId: "session-1",+ subagentName: "researcher",+ turnId: "turn-1",+ },+ parentTraceContext: parentSession.spanContext(),rootSessionId: "session-1",sessionId: "child-1",turnId: "child-turn-1",@@ -1676,11 +1605,12 @@ describe("createAgentOtelInstrumentation", () => {(span) => span.attributes["agent.session.id"] === "child-1",)!;- expect(childTurn.spanContext().traceId).toBe(parentWindow.spanContext().traceId);- expect(childTurn.parentSpanContext?.spanId).toBe(parentWindow.spanContext().spanId);- expect(childTurn.attributes["agent.root.session.id"]).toBe("session-1");- // The child adopts a window rather than opening one, so the trace still- // holds exactly the root's window span.+ expect(childTurn.spanContext().traceId).toBe(parentSession.spanContext().traceId);+ expect(childTurn.parentSpanContext?.spanId).toBe(parentSession.spanContext().spanId);+ expect(childTurn.attributes["agent.subagent.name"]).toBe("researcher");+ expect(childTurn.attributes).not.toHaveProperty("agent.parent.call_id");+ expect(childTurn.attributes).not.toHaveProperty("agent.parent.session.id");+ expect(childTurn.attributes).not.toHaveProperty("agent.parent.turn.id");expect(byName(spans, "agent.session")).toHaveLength(1);});@@ -1706,76 +1636,9 @@ describe("createAgentOtelInstrumentation", () => {const childTurn = byName(runtime.exporter.getFinishedSpans(), "agent.turn")[0]!;expect(childTurn.spanContext().traceId).toBe(parentTraceContext.traceId);expect(childTurn.parentSpanContext).toMatchObject(parentTraceContext);- expect(childTurn.attributes["agent.root.session.id"]).toBe("parent-session");});- it("attributes a child turn to the exact call that dispatched it", async () => {- const runtime = createRuntime();- await publishTurnStarted({- hooks: runtime.hooks,- parentLineage: {- callId: "call-7",- sessionId: "session-1",- subagentName: "researcher",- turnId: "turn-1",- },- rootSessionId: "session-1",- sessionId: "child-1",- turnId: "child-turn-1",- turnSequence: 0,- });- await completeTurn(runtime.hooks, "child-1", "child-turn-1");- await runtime.provider.forceFlush();-- const spans = runtime.exporter.getFinishedSpans();- const childTurn = byName(spans, "agent.turn").find(- (span) => span.attributes["agent.session.id"] === "child-1",- )!;- expect(childTurn.attributes["agent.parent.call_id"]).toBe("call-7");- expect(childTurn.attributes["agent.parent.session.id"]).toBe("session-1");- expect(childTurn.attributes["agent.parent.turn.id"]).toBe("turn-1");- expect(childTurn.attributes["agent.subagent.name"]).toBe("researcher");- });-- it("omits the subagent name when the dispatch did not carry one", async () => {- const runtime = createRuntime();- await publishTurnStarted({- hooks: runtime.hooks,- parentLineage: { callId: "call-7", sessionId: "session-1", turnId: "turn-1" },- rootSessionId: "session-1",- sessionId: "child-1",- turnId: "child-turn-1",- turnSequence: 0,- });- await completeTurn(runtime.hooks, "child-1", "child-turn-1");- await runtime.provider.forceFlush();-- const childTurn = byName(runtime.exporter.getFinishedSpans(), "agent.turn").find(- (span) => span.attributes["agent.session.id"] === "child-1",- )!;- expect(childTurn.attributes).not.toHaveProperty("agent.subagent.name");- expect(childTurn.attributes["agent.parent.call_id"]).toBe("call-7");- });-- it("leaves a top-level turn free of parent lineage attributes", async () => {- const runtime = createRuntime();- await publishTurnStarted({- hooks: runtime.hooks,- sessionId: "session-1",- turnId: "turn-1",- turnSequence: 0,- });- await completeTurn(runtime.hooks, "session-1", "turn-1");- await runtime.provider.forceFlush();-- const turn = byName(runtime.exporter.getFinishedSpans(), "agent.turn")[0]!;- expect(turn.attributes).not.toHaveProperty("agent.parent.call_id");- expect(turn.attributes).not.toHaveProperty("agent.parent.session.id");- expect(turn.attributes).not.toHaveProperty("agent.parent.turn.id");- expect(turn.attributes).not.toHaveProperty("agent.subagent.name");- });-- it("opens its own root when a child session is handed no parent window", async () => {+ it("opens its own root when a child session is handed no parent trace", async () => {const runtime = createRuntime();await publishTurnStarted({hooks: runtime.hooks,@@ -1792,7 +1655,7 @@ describe("createAgentOtelInstrumentation", () => {expect(sessions[0]!.parentSpanContext).toBeUndefined();});- it("rolls a long subagent child out of the window it adopted", async () => {+ it("keeps a long subagent child in its adopted trace", async () => {const runtime = createRuntime();await publishTurnStarted({hooks: runtime.hooks,@@ -1801,28 +1664,29 @@ describe("createAgentOtelInstrumentation", () => {turnSequence: 0,});await runtime.provider.forceFlush();- const parentWindow = byName(runtime.exporter.getFinishedSpans(), "agent.session")[0]!;+ const parentSession = byName(runtime.exporter.getFinishedSpans(), "agent.session")[0]!;- for (let sequence = 0; sequence <= SESSION_WINDOW_TURN_LIMIT; sequence += 1) {+ for (let sequence = 0; sequence < 201; sequence += 1) {await publishTurnStarted({hooks: runtime.hooks,- parentTraceContext: parentWindow.spanContext(),+ parentTraceContext: parentSession.spanContext(),rootSessionId: "session-1",sessionId: "child-1",turnId: `child-turn-${sequence}`,turnSequence: sequence,});+ await completeTurn(runtime.hooks, "child-1", `child-turn-${sequence}`);}await runtime.provider.forceFlush();- const rolled = byName(runtime.exporter.getFinishedSpans(), "agent.session").find(- (span) => span.attributes["agent.session.id"] === "child-1",- )!;- expect(rolled.attributes["agent.session.window"]).toBe(1);- expect(rolled.attributes["agent.session.window.previous.trace.id"]).toBe(- parentWindow.spanContext().traceId,- );- expect(rolled.spanContext().traceId).not.toBe(parentWindow.spanContext().traceId);+ const spans = runtime.exporter.getFinishedSpans();+ expect(byName(spans, "agent.session")).toHaveLength(1);+ expect(byName(spans, "agent.turn")).toHaveLength(201);+ expect(+ byName(spans, "agent.turn").every(+ (turn) => turn.spanContext().traceId === parentSession.spanContext().traceId,+ ),+ ).toBe(true);});it("marks a failed action without failing its turn", async () => {diff --git a/packages/eve/src/tracing/agent-otel-provider.ts b/packages/eve/src/tracing/agent-otel-provider.tsindex 2900345e0..a618e9fe9 100644--- a/packages/eve/src/tracing/agent-otel-provider.ts+++ b/packages/eve/src/tracing/agent-otel-provider.ts@@ -41,7 +41,6 @@ import type {InstrumentationModelCallStartedEvent,InstrumentationProviderDefinition,InstrumentationSessionStartedEvent,- InstrumentationParentLineage,InstrumentationTraceContext,InstrumentationSessionTransitionEvent,InstrumentationTurnStartedEvent,@@ -163,7 +162,6 @@ export function createAgentOtelInstrumentation("agent.session.id": event.scope.sessionId,"agent.framework.name": "eve","agent.framework.version": input.frameworkVersion,- "agent.root.session.id": event.scope.rootSessionId ?? event.scope.sessionId,"agent.step.attempt": event.scope.attemptIndex,"agent.step.index": event.scope.stepIndex,"agent.turn.id": event.scope.turnId,@@ -268,10 +266,8 @@ export function createAgentOtelInstrumentation("agent.framework.name": "eve","agent.framework.version": input.frameworkVersion,"agent.name": session?.agentName,- ...parentLineageAttributes(turn.lineage),- "agent.root.session.id": turn.rootSessionId,"agent.session.id": event.sessionId,- "agent.session.window": session?.window,+ "agent.subagent.name": turn.subagentName,"agent.turn.id": event.turnId,"agent.turn.sequence": turn.sequence,},@@ -535,21 +531,6 @@ function takeSpanState<T>(return state;}-function parentLineageAttributes(- lineage: InstrumentationParentLineage | undefined,-): Record<string, string> {- if (lineage === undefined) return {};- const attributes: Record<string, string> = {- "agent.parent.call_id": lineage.callId,- "agent.parent.session.id": lineage.sessionId,- "agent.parent.turn.id": lineage.turnId,- };- if (lineage.subagentName !== undefined) {- attributes["agent.subagent.name"] = lineage.subagentName;- }- return attributes;-}-function contextFromSpanContext(spanContext: SpanContext): Context {return trace.setSpan(ROOT_CONTEXT, trace.wrapSpanContext(spanContext));}diff --git a/packages/eve/src/tracing/agent-otel-session-context.ts b/packages/eve/src/tracing/agent-otel-session-context.tsindex c0f2dbeac..17c2651b8 100644--- a/packages/eve/src/tracing/agent-otel-session-context.ts+++ b/packages/eve/src/tracing/agent-otel-session-context.ts@@ -10,11 +10,7 @@ import type { AgentSpanIdGenerator } from "#tracing/agent-span-id-generator.js";import { normalizeChannelAudience } from "#shared/channel-audience.js";import type { ChannelAudience } from "#shared/channel-audience.js";import type { TraceCapturePolicy } from "#tracing/otel-declaration.js";-import {- SESSION_WINDOW_TURN_LIMIT,- type AgentSessionTraceState,- type AgentTraceStateStore,-} from "#tracing/agent-trace-state.js";+import type { AgentSessionTraceState, AgentTraceStateStore } from "#tracing/agent-trace-state.js";interface AgentOtelSessionContextInput {readonly frameworkVersion: string;@@ -39,18 +35,16 @@ interface AgentOtelSessionContext {export function createAgentOtelSessionContext(input: AgentOtelSessionContextInput,): AgentOtelSessionContext {- const openSessionWindow = (window: {+ const openSessionTrace = (session: {readonly agentName?: string;readonly channelAudience: ChannelAudience;- readonly index: number;- readonly previousTraceId?: string;readonly rootSessionId: string;readonly sessionId: string;}): SpanContext => {- if (!shouldTrace(input.tracePolicy, window)) {+ if (!shouldTrace(input.tracePolicy, session)) {return {isRemote: false,- spanId: input.idGenerator.deriveSpanId(`session:${window.sessionId}:${window.index}`),+ spanId: input.idGenerator.deriveSpanId(`session:${session.sessionId}`),traceFlags: 0,traceId: input.idGenerator.generateTraceId(),};@@ -59,20 +53,15 @@ export function createAgentOtelSessionContext(attributes: {"agent.framework.name": "eve","agent.framework.version": input.frameworkVersion,- "agent.channel.audience": window.channelAudience,- "agent.name": window.agentName,- "agent.root.session.id": window.rootSessionId,- "agent.session.id": window.sessionId,- "agent.session.window": window.index,- "agent.trace.schema.version": 1,- ...(window.previousTraceId === undefined- ? {}- : { "agent.session.window.previous.trace.id": window.previousTraceId }),+ "agent.channel.audience": session.channelAudience,+ "agent.name": session.agentName,+ "agent.session.id": session.sessionId,+ "agent.trace.schema.version": 2,},root: true,});- span.addEvent(window.index === 0 ? "session.started" : "session.window.opened");- // The window outlives this worker and has no guaranteed close — an idle+ span.addEvent("session.started");+ // The session outlives this worker and has no guaranteed close — an idle// session never ends — so the root is recorded as a zero-duration marker// and later spans parent through its persisted context.span.end();@@ -90,10 +79,9 @@ export function createAgentOtelSessionContext(channelKind: event.channelKind,context:event.parentTraceContext === undefined- ? openSessionWindow({+ ? openSessionTrace({agentName: event.agentName,channelAudience: normalizeChannelAudience(event.channelAudience),- index: 0,rootSessionId: event.rootSessionId,sessionId: event.sessionId,})@@ -107,35 +95,12 @@ export function createAgentOtelSessionContext(}),),rootSessionId: event.rootSessionId,- turnsInWindow: 0,- window: 0,};await input.stateStore.setSession(event.sessionId, state);}return state;};- const advanceSessionWindow = (- sessionId: string,- session: AgentSessionTraceState,- ): AgentSessionTraceState => {- if (session.turnsInWindow < SESSION_WINDOW_TURN_LIMIT) return session;- const index = session.window + 1;- return {- ...session,- context: openSessionWindow({- agentName: session.agentName,- channelAudience: normalizeChannelAudience(session.channelAudience),- index,- previousTraceId: session.context.traceId,- rootSessionId: session.rootSessionId,- sessionId,- }),- turnsInWindow: 0,- window: index,- };- };-const prepareSessionTrace = async (event: InstrumentationSessionStartedEvent,): Promise<InstrumentationTraceContext> => {@@ -154,19 +119,16 @@ export function createAgentOtelSessionContext(};}- const session = advanceSessionWindow(- event.sessionId,- await ensureSessionContext({- agentName: undefined,- channelAudience: "unknown",- channelKind: undefined,- idempotencyKey: sessionIdempotencyKey(event.sessionId),- parentTraceContext: event.parentTraceContext,- rootSessionId: event.rootSessionId,- sessionId: event.sessionId,- type: "session.started",- }),- );+ const session = await ensureSessionContext({+ agentName: undefined,+ channelAudience: "unknown",+ channelKind: undefined,+ idempotencyKey: sessionIdempotencyKey(event.sessionId),+ parentTraceContext: event.parentTraceContext,+ rootSessionId: event.rootSessionId,+ sessionId: event.sessionId,+ type: "session.started",+ });// The turn outlives this worker, so no live span can cover it: the span// id is allocated now for descendants to parent through, and the span// itself is emitted at the turn's session transition.@@ -176,18 +138,14 @@ export function createAgentOtelSessionContext(traceFlags: session.context.traceFlags,traceId: session.context.traceId,};- await input.stateStore.setSession(event.sessionId, {- ...session,- turnsInWindow: session.turnsInWindow + 1,- });await input.stateStore.setTurn(event.sessionId, event.turnId, {context: turnContext,- lineage: event.parentLineage,parentIsRemote: session.context.isRemote,parentSpanId: session.context.spanId,rootSessionId: event.rootSessionId,sequence: event.sequence,startTimeMs: Date.now(),+ subagentName: event.parentLineage?.subagentName,});return portableSpanContext(session.context);};diff --git a/packages/eve/src/tracing/agent-trace-context-store.test.ts b/packages/eve/src/tracing/agent-trace-context-store.test.tsindex 01c77b1d4..0a0f870a5 100644--- a/packages/eve/src/tracing/agent-trace-context-store.test.ts+++ b/packages/eve/src/tracing/agent-trace-context-store.test.ts@@ -18,22 +18,15 @@ describe("ContextAgentTraceStateStore", () => {agentName: "weather",context: spanContext("1", "2"),rootSessionId: "session-1",- turnsInWindow: 3,- window: 1,});store.setTurn("session-1", "turn-1", {context: spanContext("1", "3"),- lineage: {- callId: "call-1",- sessionId: "parent-session",- subagentName: "researcher",- turnId: "parent-turn",- },parentIsRemote: true,parentSpanId: "2".repeat(16),rootSessionId: "session-1",sequence: 0,startTimeMs: 1_700_000_000_000,+ subagentName: "researcher",terminal: { error: new Error("failed"), type: "turn.failed" },});});@@ -43,18 +36,12 @@ describe("ContextAgentTraceStateStore", () => {await contextStorage.run(restored, () => {const store = new ContextAgentTraceStateStore();expect(store.getSession("session-1")?.context).toEqual(spanContext("1", "2"));- expect(store.getSession("session-1")).toMatchObject({ turnsInWindow: 3, window: 1 });expect(store.getTurn("session-1", "turn-1")?.context).toEqual(spanContext("1", "3"));expect(store.getTurn("session-1", "turn-1")).toMatchObject({- lineage: {- callId: "call-1",- sessionId: "parent-session",- subagentName: "researcher",- turnId: "parent-turn",- },parentIsRemote: true,parentSpanId: "2".repeat(16),startTimeMs: 1_700_000_000_000,+ subagentName: "researcher",});const terminal = store.getTurn("session-1", "turn-1")?.terminal;expect(terminal?.type).toBe("turn.failed");@@ -70,8 +57,6 @@ describe("ContextAgentTraceStateStore", () => {store.setSession("session-1", {context: spanContext("1", "2"),rootSessionId: "session-1",- turnsInWindow: 0,- window: 0,});store.setTurn("session-1", "turn-1", {context: spanContext("1", "3"),@@ -95,8 +80,6 @@ describe("ContextAgentTraceStateStore", () => {new ContextAgentTraceStateStore().setSession("session-1", {context: spanContext("1", "2"),rootSessionId: "session-1",- turnsInWindow: 0,- window: 0,});});@@ -109,14 +92,12 @@ describe("ContextAgentTraceStateStore", () => {});describe("readSessionTraceContext", () => {- it("reads one session's window out of a serialized context", async () => {+ it("reads one session's trace context out of a serialized context", async () => {const context = new ContextContainer();await contextStorage.run(context, () => {new ContextAgentTraceStateStore().setSession("session-1", {context: spanContext("1", "2"),rootSessionId: "session-1",- turnsInWindow: 0,- window: 0,});});const serialized = await serializeContext(context);diff --git a/packages/eve/src/tracing/agent-trace-context-store.ts b/packages/eve/src/tracing/agent-trace-context-store.tsindex eba434d30..8ef719627 100644--- a/packages/eve/src/tracing/agent-trace-context-store.ts+++ b/packages/eve/src/tracing/agent-trace-context-store.ts@@ -2,7 +2,6 @@ import type { SpanContext } from "#compiled/@opentelemetry/api/index.js";import { contextStorage, loadContext } from "#context/container.js";import { ContextKey } from "#context/key.js";-import type { InstrumentationParentLineage } from "#harness/instrumentation/lifecycle.js";import type {AgentActionTraceState,AgentSessionTraceState,@@ -36,7 +35,7 @@ export function preserveSerializedAgentTraceState(}/**- * Reads a named session's trace window straight out of a serialized context,+ * Reads a named session's trace context straight out of a serialized context,* which {@link ContextAgentTraceStateStore} cannot do — its reads are scoped* to the ambient session.*/@@ -196,8 +195,6 @@ function deserializeState(data: unknown): AgentTraceContextState {channelKind: typeof value.channelKind === "string" ? value.channelKind : undefined,context: value.context,rootSessionId: typeof value.rootSessionId === "string" ? value.rootSessionId : "",- turnsInWindow: typeof value.turnsInWindow === "number" ? value.turnsInWindow : 0,- window: typeof value.window === "number" ? value.window : 0,} satisfies AgentSessionTraceState;});const turns = deserializeRecord(data.turns, (value) => {@@ -207,12 +204,12 @@ function deserializeState(data: unknown): AgentTraceContextState {}return {context: value.context,- lineage: deserializeLineage(value.lineage),parentIsRemote: typeof value.parentIsRemote === "boolean" ? value.parentIsRemote : undefined,parentSpanId: value.parentSpanId,rootSessionId: typeof value.rootSessionId === "string" ? value.rootSessionId : "",sequence: typeof value.sequence === "number" ? value.sequence : 0,startTimeMs: value.startTimeMs,+ subagentName: typeof value.subagentName === "string" ? value.subagentName : undefined,terminal: deserializeTerminal(value.terminal),} satisfies AgentTurnTraceState;});@@ -275,23 +272,6 @@ function deserializeRecord<T>(return result;}-function deserializeLineage(value: unknown): InstrumentationParentLineage | undefined {- if (- !isRecord(value) ||- typeof value.callId !== "string" ||- typeof value.sessionId !== "string" ||- typeof value.turnId !== "string"- ) {- return undefined;- }- return {- callId: value.callId,- sessionId: value.sessionId,- subagentName: typeof value.subagentName === "string" ? value.subagentName : undefined,- turnId: value.turnId,- };-}-function deserializeTerminal(value: unknown): AgentTurnTraceState["terminal"] {if (!isRecord(value) || typeof value.type !== "string") return undefined;const type = value.type;diff --git a/packages/eve/src/tracing/agent-trace-span-processor.test.ts b/packages/eve/src/tracing/agent-trace-span-processor.test.tsindex 1287deba0..c4abcb93e 100644--- a/packages/eve/src/tracing/agent-trace-span-processor.test.ts+++ b/packages/eve/src/tracing/agent-trace-span-processor.test.ts@@ -42,11 +42,11 @@ describe("AgentTraceSpanProcessor", () => {expect([...processor.activeTraceIds()]).toEqual(["trace-2"]);});- it("releases every window a session owns", () => {+ it("releases every trace a session owns", () => {const processor = new AgentTraceSpanProcessor([]);- processor.onStart(span("window-0", { "agent.session.id": "session-1" }), {});- processor.onStart(span("window-1", { "agent.session.id": "session-1" }), {});- expect([...processor.activeTraceIds()].sort()).toEqual(["window-0", "window-1"]);+ processor.onStart(span("trace-1", { "agent.session.id": "session-1" }), {});+ processor.onStart(span("trace-2", { "agent.session.id": "session-1" }), {});+ expect([...processor.activeTraceIds()].sort()).toEqual(["trace-1", "trace-2"]);expect(processor.releaseSession("session-1")).toBe(true);expect([...processor.activeTraceIds()]).toEqual([]);@@ -66,14 +66,8 @@ describe("AgentTraceSpanProcessor", () => {shutdown: vi.fn(async () => {}),};const processor = new AgentTraceSpanProcessor([child]);- const owned = {- "agent.root.session.id": "session-1",- "agent.session.id": "session-1",- };- const delegated = {- "agent.root.session.id": "session-1",- "agent.session.id": "child-1",- };+ const owned = { "agent.session.id": "session-1" };+ const delegated = { "agent.session.id": "child-1" };processor.onStart(span("trace-1", owned), {});processor.onStart(span("trace-1", delegated), {});diff --git a/packages/eve/src/tracing/agent-trace-span-processor.ts b/packages/eve/src/tracing/agent-trace-span-processor.tsindex 4b63a09e7..1b27d922c 100644--- a/packages/eve/src/tracing/agent-trace-span-processor.ts+++ b/packages/eve/src/tracing/agent-trace-span-processor.ts@@ -11,6 +11,7 @@ export class AgentTraceSpanProcessor implements SpanProcessor {readonly #children: readonly SpanProcessor[];readonly #ownedTraceIds = new Set<string>();readonly #sessionTraceIds = new Map<string, Set<string>>();+ readonly #traceOwners = new Map<string, string>();constructor(children: readonly SpanProcessor[]) {this.#children = children;}@@ -23,13 +24,14 @@ export class AgentTraceSpanProcessor implements SpanProcessor {if (!isSpanLike(span)) return;const sessionId = span.attributes["agent.session.id"];if (typeof sessionId === "string") {- const rootSessionId = span.attributes["agent.root.session.id"];- const owner = typeof rootSessionId === "string" ? rootSessionId : sessionId;const traceId = span.spanContext().traceId;this.#ownedTraceIds.add(traceId);- const owned = this.#sessionTraceIds.get(owner) ?? new Set<string>();- owned.add(traceId);- this.#sessionTraceIds.set(owner, owned);+ if (!this.#traceOwners.has(traceId)) {+ this.#traceOwners.set(traceId, sessionId);+ const owned = this.#sessionTraceIds.get(sessionId) ?? new Set<string>();+ owned.add(traceId);+ this.#sessionTraceIds.set(sessionId, owned);+ }}if (!this.#accepts(span)) return;for (const child of this.#children) child.onStart(span, parentContext);@@ -53,7 +55,10 @@ export class AgentTraceSpanProcessor implements SpanProcessor {releaseSession(sessionId: string): boolean {const owned = this.#sessionTraceIds.get(sessionId);if (owned === undefined) return false;- for (const traceId of owned) this.#ownedTraceIds.delete(traceId);+ for (const traceId of owned) {+ this.#ownedTraceIds.delete(traceId);+ this.#traceOwners.delete(traceId);+ }this.#sessionTraceIds.delete(sessionId);return true;}diff --git a/packages/eve/src/tracing/agent-trace-state.ts b/packages/eve/src/tracing/agent-trace-state.tsindex 84f0d32cd..3c58760c5 100644--- a/packages/eve/src/tracing/agent-trace-state.ts+++ b/packages/eve/src/tracing/agent-trace-state.ts@@ -2,34 +2,28 @@ import type { SpanContext } from "#compiled/@opentelemetry/api/index.js";import type {InstrumentationActionKind,- InstrumentationParentLineage,InstrumentationTraceContext,InstrumentationTurnFailedEvent,InstrumentationTurnSettledEvent,} from "#harness/instrumentation/lifecycle.js";import type { ChannelAudience } from "#shared/channel-audience.js";-/** Sized so an ordinary session stays one trace and only an outsized one rolls. */-export const SESSION_WINDOW_TURN_LIMIT = 200;-export interface AgentSessionTraceState {readonly channelAudience?: ChannelAudience;readonly agentName?: string;readonly channelKind?: string;readonly context: SpanContext;readonly rootSessionId: string;- readonly turnsInWindow: number;- readonly window: number;}export interface AgentTurnTraceState {readonly context: SpanContext;- readonly lineage?: InstrumentationParentLineage;readonly parentIsRemote?: boolean;readonly parentSpanId: string;readonly rootSessionId: string;readonly sequence: number;readonly startTimeMs: number;+ readonly subagentName?: string;readonly terminal?:| { readonly error: unknown; readonly type: InstrumentationTurnFailedEvent["type"] }| { readonly type: InstrumentationTurnSettledEvent["type"] };diff --git a/packages/eve/src/tracing/local-trace-reader.ts b/packages/eve/src/tracing/local-trace-reader.tsindex 5b3cac83b..3d316cab2 100644--- a/packages/eve/src/tracing/local-trace-reader.ts+++ b/packages/eve/src/tracing/local-trace-reader.ts@@ -52,15 +52,13 @@ export interface LocalTrace {/*** Every session recorded in the trace, opener first.*- * A subagent child records into the window its parent had open, so one+ * A subagent child records into the trace its parent opened, so one* trace can hold several sessions and any of their ids resolves to it.*/readonly sessionIds: readonly string[];readonly spans: readonly LocalTraceSpan[];readonly startTimeNs: bigint;readonly traceId: string;- /** Zero-based session window this trace holds, when the spans record one. */- readonly window?: number;}/**@@ -200,7 +198,6 @@ export function assembleLocalTrace(traceId: string, spans: readonly LocalTraceSpordered[0]!.startTimeNs,),traceId,- window: firstNumberAttribute(attributes, "agent.session.window"),};}@@ -370,18 +367,6 @@ function firstAttribute(return undefined;}-function firstNumberAttribute(- attributes: readonly Readonly<Record<string, unknown>>[],- key: string,-): number | undefined {- for (const values of attributes) {- const value = values[key];- if (typeof value === "number") return value;- if (typeof value === "bigint") return Number(value);- }- return undefined;-}-function distinctAttributes(attributes: readonly Readonly<Record<string, unknown>>[],key: string,diff --git a/packages/eve/test/tui-client/tui-traces.ts b/packages/eve/test/tui-client/tui-traces.tsindex eb674bb1e..bb4d815bf 100644--- a/packages/eve/test/tui-client/tui-traces.ts+++ b/packages/eve/test/tui-client/tui-traces.ts@@ -58,23 +58,22 @@ void (async () => {const runPromise = runner.run();try {- const sessionWindow = "9".repeat(16);+ const sessionRoot = "9".repeat(16);const turn = "a".repeat(16);const delivery = "0".repeat(16);const step = "b".repeat(16);const model = "c".repeat(16);const action = "e".repeat(16);- // A real capture roots turns under the session's window span, so the+ // A real capture roots turns under the session span, so the// fixture does too — turn discovery must not depend on root position.await writeSegment(appRoot, TRACE_ONE, {- spanId: sessionWindow,+ spanId: sessionRoot,name: "agent.session",start: 900,end: 900,attributes: {"agent.session.id": "session-smoke","agent.name": "smoke-agent",- "agent.session.window": 0,},});await writeSegment(appRoot, TRACE_ONE, {@@ -82,7 +81,7 @@ void (async () => {name: "agent.turn",start: 1_000,end: 1_000,- parentSpanId: sessionWindow,+ parentSpanId: sessionRoot,attributes: {"agent.session.id": "session-smoke","agent.name": "smoke-agent",@@ -94,7 +93,7 @@ void (async () => {name: "agent.channel.delivery",start: 1_000,end: 1_000,- parentSpanId: sessionWindow,+ parentSpanId: sessionRoot,attributes: {"agent.channel.delivery.input": JSON.stringify({ message: "smoke prompt" }),"agent.turn.id": "turn_0",@@ -133,20 +132,30 @@ void (async () => {"gen_ai.tool.call.result": '{"temperature":72}',},});- // A subagent child turn recorded into the same trace, carrying its- // dispatch lineage (#1433 attributes).+ const subagentAction = "d".repeat(16);+ await writeSegment(appRoot, TRACE_ONE, {+ spanId: subagentAction,+ name: "agent.action",+ start: 6_500,+ end: 7_000,+ parentSpanId: turn,+ attributes: {+ "agent.action.call_id": "call-1",+ "agent.action.kind": "subagent-call",+ "agent.action.name": "echo",+ "agent.turn.id": "turn_0",+ },+ });+ // A subagent child turn recorded into the same trace and parented to its+ // dispatch action.await writeSegment(appRoot, TRACE_ONE, {spanId: "8".repeat(16),name: "agent.turn",start: 7_000,end: 7_000,- parentSpanId: sessionWindow,+ parentSpanId: subagentAction,attributes: {"agent.session.id": "child-session",- "agent.parent.session.id": "session-smoke",- "agent.parent.turn.id": "turn_0",- "agent.parent.call_id": "call-1",- "agent.subagent.name": "echo","agent.turn.id": "turn_child",},});@@ -155,7 +164,7 @@ void (async () => {name: "agent.channel.delivery",start: 7_000,end: 7_000,- parentSpanId: sessionWindow,+ parentSpanId: sessionRoot,attributes: {"agent.channel.delivery.input": JSON.stringify({ message: "delegated task" }),"agent.turn.id": "turn_child",diff --git a/research/provider-neutral-local-observability.md b/research/provider-neutral-local-observability.mdindex 76eec2920..e951fdcfb 100644--- a/research/provider-neutral-local-observability.md+++ b/research/provider-neutral-local-observability.md@@ -74,7 +74,7 @@ or tool more than once.## Agent OTel semantics```text-agent.session {agent.session.id, agent.session.window}+agent.session {agent.session.id}+-- agent.turn {agent.turn.id, agent.turn.sequence}+-- agent.step {agent.step.index, agent.step.attempt}+-- model-provider spans@@ -87,47 +87,27 @@ covers one model call and the actions it requests through their resolution. `agean open discriminator — `tool` today, with `skill`, `subagent`, and `remote-agent` reserved.The `agent.*` namespace carries cheap structural attributes only: session/turn/step/attempt-identity, action identity, agent and framework identity, channel and environment, principal, and-parent/root lineage. Message content, model output, and tool payloads are optional capture, off by+identity, action identity, and agent and framework identity. Message content, model output, and tool payloads are optional capture, off bydefault. The OTel provider owns this mapping; the bridge and hooks contain no span names,attributes, or parent contexts.-### Session windows--A session is one trace until it outgrows one. Sessions run for thousands of turns across days, and a-single unbounded trace serves nobody: the local store evicts whole traces, and exporters cap spans-per trace and assemble within a bounded time window, so late children get dropped. No local session-is long enough to reach that, so windowing is for the production providers of phase 7; it is settled-here because the window is what a subagent adopts and what a sampler decides on.--A session therefore maps to a sequence of windowed traces. A window rolls on a turn count, chosen so-ordinary sessions stay exactly one trace, and rolls only between turns so a turn's spans always-share a trace. Turn count is the sole criterion because it is derived from state eve already-persists, so a replaying worker reaches the same decision — an elapsed-time rule could not.-`agent.session.window` is the zero-based index; each window's root records-`agent.session.window.previous.trace.id`.--Session identity does not live in the trace id. Every span carries `agent.session.id`, and eve's-inspection path resolves a session to its windows through that attribute.--### The window root is a real span+### The session root is a real span`agent.session` is a real root span opened with OTel's `root` option, not a synthesized parentcontext. eve persists its span context — including the sampling decision it actually received — and-later turns in the window parent to that stored context.+later turns parent to that stored context.This is what makes an authored sampler work. A synthesized parent asserting a sampled flag is avalid parent to `ParentBasedSampler`, which resolves through a parent branch and never consults theconfigured root rule. Asserting unsampled instead selects `localParentNotSampled`, which dropseverything. A genuine root avoids both.-Sampling is therefore per window, not per session: a ratio sampler may keep some windows of a long-session and drop others. `agent.session.id` is a creation-time attribute, so an author who needs-whole sessions can key a sampler on it.+Sampling is therefore per session trace. `agent.session.id` is a creation-time attribute, so an+author can key a sampler on it.### Marker spans-The window root is recorded and ended immediately, as `agent.turn` already is. A window outlives the+The session root is recorded and ended immediately, as `agent.turn` already is. A session outlives theworker that opened it and a span object cannot cross that boundary, so eve records the root,persists its span context, and parents later spans through it.@@ -135,26 +115,20 @@ The cost is that a backend reports the root's duration rather than the window's.durations, where the time actually is, are unaffected, and `eve traces` renders a marker'sdescendant extent in place of its zero duration.-A real duration would mean emitting the span once at window close, with explicit timestamps and a+A real duration would mean emitting the span once at session close, with explicit timestamps and aspan id chosen before the span exists. The ids are reachable — `registerOTel` accepts an`idGenerator` — but the close is not: a session that goes idle and never resumes closes on nothing,so its root would never be emitted and every span in the trace would reference a parent that neverarrives. A marker is the only representation that is always emitted. `agent.turn` does have aguaranteed close and could carry a real duration; that is tracked separately.-Cross-window grouping relies on `agent.session.id` plus the previous-trace-id chain. Span links are-the richer form but are not in eve's vendored OTel surface. Vercel Agent Runs is assembled from-Workflow run tags rather than spans and is unaffected.-### Subagents-A subagent keeps its own session identity but records into the window its parent had open, so-delegated work appears in the trace that caused it. Durable trace state is scoped to one session's-context, so the window's `SpanContext` is handed down at dispatch rather than looked up by the-child, and the child snapshots it — a later roll on the parent does not move work already recorded.-A child with no handed-down window (a remote agent, running under its own deployment's tracing)-opens its own root. A child that outgrows the adopted window rolls into its own, chained like any-other roll. `eve traces` resolves any session recorded in a trace, not only the one that opened it.+A local subagent keeps its own session identity but adopts the parent action's `SpanContext`, so+delegated work appears directly beneath the action that caused it. Remote dispatch sends the same+context as `traceparent`; the receiver adopts it when available. A child with no propagated context+opens its own root. `eve traces` resolves any session recorded in a trace, not only the one that+opened it.## Runtime integration