The Open Framework for Building Agents
feat(eve): open a real session root span and window long traces (#1410)
Chad Hietala275271d20550
diff --git a/.changeset/windowed-session-traces.md b/.changeset/windowed-session-traces.mdnew file mode 100644index 000000000..2537ddc30--- /dev/null+++ b/.changeset/windowed-session-traces.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Subagent runs now record into the trace of the session that dispatched them instead of a disconnected trace of their own, and `eve traces` resolves either session id to it. Local traces also open a real `agent.session` root span rather than a synthesized parent, so an authored OTel sampler's root rule decides whether a session is sampled, and a session long enough to outgrow one trace rolls into numbered windows that `eve traces <session-id>` lists oldest first. Rows whose lifetime outlives the worker that opened them — `agent.session` and `agent.turn` — now show the extent of their descendants instead of `0ms`.diff --git a/docs/reference/cli.md b/docs/reference/cli.mdindex ad3cf1022..25aaa98ed 100644--- a/docs/reference/cli.md+++ b/docs/reference/cli.md@@ -252,7 +252,13 @@ eve traces # show the most recent span treeeve traces <trace> # show one span tree```-`eve traces ls` reads the immutable OTLP/JSON segments captured under `.eve/traces/v1`; `eve dev` does not need to be running. `eve traces` accepts a full trace id, an `agent.session.id`, or an unambiguous prefix of either. Malformed or incomplete segments are skipped without hiding valid spans from the same trace.+Reads the immutable OTLP/JSON segments under `.eve/traces/v1`, so `eve dev` need not be running. Accepts a full trace id, an `agent.session.id`, or an unambiguous prefix of either. Malformed segments are skipped without hiding valid spans from the same 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 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.++`agent.session` and `agent.turn` outlive the worker that opened them, so they are recorded as zero-duration markers. The span tree shows their descendant extent instead; `agent.step` and the model and tool spans beneath it carry real durations. A third-party OTel backend reports zero for the markers.## `eve link`diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.tsindex b21987e82..e93c85b2e 100644--- a/packages/eve/src/channel/types.ts+++ b/packages/eve/src/channel/types.ts@@ -84,6 +84,17 @@ export interface SessionParent {readonly turn: SessionTurn;}+/**+ * Serializable W3C span context identifying a parent's open trace window.+ * Structural rather than an OTel `SpanContext` so the channel surface stays+ * free of tracing dependencies.+ */+export interface SessionTraceContext {+ readonly spanId: string;+ readonly traceFlags: number;+ readonly traceId: string;+}+// ---------------------------------------------------------------------------// Auth// ---------------------------------------------------------------------------@@ -336,6 +347,11 @@ export interface RunInput {};readonly mode: RunMode;readonly parent?: SessionParent;+ /**+ * Dispatching parent's open trace window. Handed down rather than looked up+ * because trace state is scoped to one session's context.+ */+ readonly parentTraceContext?: SessionTraceContext;/*** Runtime-supplied session limits. Delegated local subagents use this to* carry the parent's remaining quota and delegation caps with the same limitdiff --git a/packages/eve/src/cli/commands/trace.integration.test.ts b/packages/eve/src/cli/commands/trace.integration.test.tsindex 92f7f0791..5e80f9f5f 100644--- a/packages/eve/src/cli/commands/trace.integration.test.ts+++ b/packages/eve/src/cli/commands/trace.integration.test.ts@@ -6,7 +6,7 @@ import { afterEach, describe, expect, it } from "vitest";import {listLocalTraces,- resolveLocalTrace,+ resolveLocalTraces,runTraceListCommand,runTraceShowCommand,} from "./trace.js";@@ -72,11 +72,72 @@ describe("eve traces", () => {);const traces = await listLocalTraces(root);- expect(resolveLocalTrace(traces, TRACE_ONE).traceId).toBe(TRACE_ONE);- expect(resolveLocalTrace(traces, "session-two").traceId).toBe(TRACE_TWO);- expect(resolveLocalTrace(traces, "session-o").traceId).toBe(TRACE_ONE);- expect(() => resolveLocalTrace(traces, "session-")).toThrow(/matches 2 local traces/u);- expect(() => resolveLocalTrace(traces, "missing")).toThrow(/No local trace matches/u);+ expect(ids(resolveLocalTraces(traces, TRACE_ONE))).toEqual([TRACE_ONE]);+ expect(ids(resolveLocalTraces(traces, "session-two"))).toEqual([TRACE_TWO]);+ expect(ids(resolveLocalTraces(traces, "session-o"))).toEqual([TRACE_ONE]);+ expect(() => resolveLocalTraces(traces, "session-")).toThrow(/matches 2 local traces/u);+ expect(() => resolveLocalTraces(traces, "missing")).toThrow(/No local trace matches/u);+ });++ it("resolves a windowed session to every window, 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(+ root,+ 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();+ await runTraceShowCommand(output.logger, root, "session-one");++ 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 () => {+ const root = await createRoot();+ const window = "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",+ "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",+ "agent.session.id": "child-one",+ }),+ );+ const traces = await listLocalTraces(root);++ // The opener still names the trace, so `eve trace ls` reads unchanged.+ expect(traces[0]!.sessionId).toBe("session-one");+ expect(ids(resolveLocalTraces(traces, "child-one"))).toEqual([TRACE_ONE]);+ expect(ids(resolveLocalTraces(traces, "session-one"))).toEqual([TRACE_ONE]);});it("renders a parented span tree and tolerates missing parents", async () => {@@ -126,6 +187,47 @@ describe("eve traces", () => {expect(output.out[0]).not.toContain("\u001B");});+ it("shows subtree extent for a marker span instead of no duration", async () => {+ const root = await createRoot();+ const session = "a".repeat(16);+ const turn = "b".repeat(16);+ const step = "c".repeat(16);+ const terminal = "d".repeat(16);+ await writeSegment(+ root,+ TRACE_ONE,+ span(session, "agent.session", 10, 10, undefined, {+ "agent.session.id": "session-one",+ }),+ );+ await writeSegment(+ root,+ TRACE_ONE,+ span(turn, "agent.turn", 10, 10, session, { "agent.session.id": "session-one" }),+ );+ await writeSegment(+ root,+ TRACE_ONE,+ span(step, "agent.step", 20, 90, turn, { "agent.session.id": "session-one" }),+ );+ await writeSegment(+ root,+ TRACE_ONE,+ span(terminal, "agent.turn.terminal", 95, 95, turn, {+ "agent.session.id": "session-one",+ }),+ );+ const output = collectingLogger();++ await runTraceShowCommand(output.logger, root, "session-one");++ expect(output.out[0]).toContain("agent.session 85ms");+ expect(output.out[0]).toContain("agent.turn 85ms");+ expect(output.out[0]).toContain("agent.step 70ms");+ // A marker with no descendants has no extent to borrow.+ expect(output.out[0]).toContain("agent.turn.terminal 0ms");+ });+it("prints empty and JSON list output", async () => {const root = await createRoot();const empty = collectingLogger();@@ -160,6 +262,10 @@ describe("eve traces", () => {}});+function ids(traces: readonly { readonly traceId: string }[]): string[] {+ return traces.map((trace) => trace.traceId);+}+function collectingLogger() {const out: string[] = [];return {diff --git a/packages/eve/src/cli/commands/trace.ts b/packages/eve/src/cli/commands/trace.tsindex f77f6eee3..a9bd71729 100644--- a/packages/eve/src/cli/commands/trace.ts+++ b/packages/eve/src/cli/commands/trace.ts@@ -28,13 +28,20 @@ export interface LocalTraceSpan {readonly traceId: string;}+interface SpanExtent {+ readonly endTimeNs: bigint;+ readonly startTimeNs: bigint;+}+export interface LocalTrace {readonly agentName?: string;readonly endTimeNs: bigint;readonly sessionId?: string;+ readonly sessionIds: readonly string[];readonly spans: readonly LocalTraceSpan[];readonly startTimeNs: bigint;readonly traceId: string;+ readonly window?: number;}/** Reads valid local traces, newest first, while ignoring malformed segments. */@@ -63,31 +70,50 @@ export async function listLocalTraces(appRoot: string): Promise<LocalTrace[]> {);}-/** Resolves an exact trace/session id or an unambiguous prefix. */-export function resolveLocalTrace(traces: readonly LocalTrace[], reference: string): LocalTrace {+/**+ * Resolves an exact trace/session id or an unambiguous prefix. One session id+ * can match several traces, since a long session windows into more than one.+ */+export function resolveLocalTraces(+ traces: readonly LocalTrace[],+ reference: string,+): readonly LocalTrace[] {const raw = reference.replaceAll("\\", "/");const normalized = basename(raw);const references = raw === normalized ? [raw] : [raw, normalized];const exactTrace = traces.find((trace) => references.includes(trace.traceId));- if (exactTrace !== undefined) return exactTrace;- const exactSessions = traces.filter(- (trace) => trace.sessionId !== undefined && references.includes(trace.sessionId),+ if (exactTrace !== undefined) return [exactTrace];+ const exactSessions = traces.filter((trace) =>+ trace.sessionIds.some((sessionId) => references.includes(sessionId)),);- if (exactSessions.length === 1) return exactSessions[0]!;- if (exactSessions.length > 1) throw ambiguousTraceError(exactSessions, reference);+ if (exactSessions.length > 0) return orderWindows(exactSessions);const matches = traces.filter((trace) =>references.some(- (candidate) => trace.traceId.startsWith(candidate) || trace.sessionId?.startsWith(candidate),+ (candidate) =>+ trace.traceId.startsWith(candidate) ||+ trace.sessionIds.some((sessionId) => sessionId.startsWith(candidate)),),);- if (matches.length === 1) return matches[0]!;if (matches.length === 0) {throw new Error(`No local trace matches "${sanitizeForTerminal(reference)}". Run \`eve traces ls\` to list traces.`,);}- throw ambiguousTraceError(matches, reference);+ if (matches.length === 1) return matches;+ const sessions = new Set(matches.map((trace) => trace.sessionId ?? trace.traceId));+ if (sessions.size > 1) throw ambiguousTraceError(matches, reference);+ return orderWindows(matches);+}++function orderWindows(traces: readonly LocalTrace[]): readonly LocalTrace[] {+ return [...traces].sort((left, right) =>+ left.startTimeNs === right.startTimeNs+ ? left.traceId.localeCompare(right.traceId)+ : left.startTimeNs < right.startTimeNs+ ? -1+ : 1,+ );}export async function runTraceListCommand(@@ -154,26 +180,33 @@ export async function runTraceShowCommand(logger.log(message);return;}- const trace = reference === undefined ? traces[0]! : resolveLocalTrace(traces, reference);+ const selected = reference === undefined ? [traces[0]!] : resolveLocalTraces(traces, reference);const theme = createCliTheme();logger.log(- [- renderCliSection(theme, {- rows: [- { label: "Trace ID", value: trace.traceId },- { label: "Session ID", value: trace.sessionId ?? "unknown" },- { label: "Agent", value: trace.agentName ?? "unknown" },- { label: "Started", value: toDate(trace.startTimeNs).toISOString() },- {- label: "Duration",- value: formatElapsed(durationMs(trace.startTimeNs, trace.endTimeNs)),- },- { label: "Spans", value: String(trace.spans.length) },- ],- title: "Trace",- }),- `${theme.accent("Spans")}\n${renderSpanTree(trace.spans)}`,- ].join("\n\n"),+ selected+ .map((trace) =>+ [+ renderCliSection(theme, {+ rows: [+ { 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() },+ {+ label: "Duration",+ value: formatElapsed(durationMs(trace.startTimeNs, trace.endTimeNs)),+ },+ { label: "Spans", value: String(trace.spans.length) },+ ],+ title: "Trace",+ }),+ `${theme.accent("Spans")}\n${renderSpanTree(trace.spans)}`,+ ].join("\n\n"),+ )+ .join("\n\n"),);}@@ -204,19 +237,22 @@ async function readTrace(root: string, traceId: string): Promise<LocalTrace | unif (spans.size === 0) return undefined;const ordered = [...spans.values()].sort(compareSpans);const attributes = ordered.map((span) => span.attributes);+ const sessionIds = distinctAttributes(attributes, "agent.session.id");return {agentName: firstAttribute(attributes, "agent.name"),endTimeNs: ordered.reduce((value, span) => (span.endTimeNs > value ? span.endTimeNs : value),0n,),- sessionId: firstAttribute(attributes, "agent.session.id"),+ sessionId: sessionIds[0],+ sessionIds,spans: ordered,startTimeNs: ordered.reduce((value, span) => (span.startTimeNs < value ? span.startTimeNs : value),ordered[0]!.startTimeNs,),traceId,+ window: firstNumberAttribute(attributes, "agent.session.window"),};}@@ -315,13 +351,14 @@ function renderSpanTree(spans: readonly LocalTraceSpan[]): string {}roots.sort(compareSpans);for (const siblings of children.values()) siblings.sort(compareSpans);+ const extents = subtreeExtents(spans, children);const lines: string[] = [];const visited = new Set<string>();const render = (span: LocalTraceSpan, prefix: string, connector: string): void => {if (visited.has(span.spanId)) return;visited.add(span.spanId);- lines.push(`${prefix}${connector}${spanLabel(span)}`);+ lines.push(`${prefix}${connector}${spanLabel(span, extents.get(span.spanId))}`);const descendants = children.get(span.spanId) ?? [];descendants.forEach((child, index) => {const last = index === descendants.length - 1;@@ -339,7 +376,35 @@ function renderSpanTree(spans: readonly LocalTraceSpan[]): string {return lines.join("\n");}-function spanLabel(span: LocalTraceSpan): string {+function subtreeExtents(+ spans: readonly LocalTraceSpan[],+ children: ReadonlyMap<string, readonly LocalTraceSpan[]>,+): ReadonlyMap<string, SpanExtent> {+ const extents = new Map<string, SpanExtent>();+ const pending = new Set<string>();+ const visit = (span: LocalTraceSpan): SpanExtent => {+ const cached = extents.get(span.spanId);+ if (cached !== undefined) return cached;+ if (pending.has(span.spanId))+ return { endTimeNs: span.endTimeNs, startTimeNs: span.startTimeNs };+ pending.add(span.spanId);+ let endTimeNs = span.endTimeNs;+ let startTimeNs = span.startTimeNs;+ for (const child of children.get(span.spanId) ?? []) {+ const extent = visit(child);+ if (extent.startTimeNs < startTimeNs) startTimeNs = extent.startTimeNs;+ if (extent.endTimeNs > endTimeNs) endTimeNs = extent.endTimeNs;+ }+ pending.delete(span.spanId);+ const extent = { endTimeNs, startTimeNs };+ extents.set(span.spanId, extent);+ return extent;+ };+ for (const span of spans) visit(span);+ return extents;+}++function spanLabel(span: LocalTraceSpan, extent?: SpanExtent): string {const details: string[] = [];const turnId = stringAttribute(span, "agent.turn.id");const stepIndex = valueAttribute(span, "agent.step.index");@@ -368,7 +433,12 @@ function spanLabel(span: LocalTraceSpan): string {}const detail = details.length === 0 ? "" : ` [${details.join(", ")}]`;const error = span.statusCode === 2 ? " ERROR" : "";- return `${sanitizeForTerminal(span.name)}${detail} ${formatElapsed(durationMs(span.startTimeNs, span.endTimeNs))}${error}`;+ const recorded = durationMs(span.startTimeNs, span.endTimeNs);+ const elapsed =+ recorded === 0 && extent !== undefined+ ? durationMs(extent.startTimeNs, extent.endTimeNs)+ : recorded;+ return `${sanitizeForTerminal(span.name)}${detail} ${formatElapsed(elapsed)}${error}`;}function compareSpans(left: LocalTraceSpan, right: LocalTraceSpan): number {@@ -377,6 +447,30 @@ function compareSpans(left: LocalTraceSpan, right: LocalTraceSpan): number {return left.name.localeCompare(right.name) || left.spanId.localeCompare(right.spanId);}+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,+): readonly string[] {+ const values = new Set<string>();+ for (const entry of attributes) {+ const value = entry[key];+ if (typeof value === "string" && value.length > 0) values.add(value);+ }+ return [...values];+}+function firstAttribute(attributes: readonly Readonly<Record<string, unknown>>[],key: string,diff --git a/packages/eve/src/context/keys.ts b/packages/eve/src/context/keys.tsindex a198e1db6..81e388872 100644--- a/packages/eve/src/context/keys.ts+++ b/packages/eve/src/context/keys.ts@@ -13,6 +13,7 @@ import type {SessionCallback,SessionCapabilities,SessionParent,+ SessionTraceContext,SessionTurn,} from "#channel/types.js";import { ContextKey } from "#context/key.js";@@ -67,6 +68,8 @@ export const ChannelInstrumentationKey = new ContextKey<ChannelInstrumentationPr);export const ModeKey = new ContextKey<RunMode>("eve.mode");export const ParentSessionKey = new ContextKey<SessionParent>("eve.parentSession");+/** Separate from {@link ParentSessionKey} so it stays out of what extensions read. */+export const ParentTraceContextKey = new ContextKey<SessionTraceContext>("eve.parentTraceContext");export const SubagentDepthKey = new ContextKey<number>("eve.subagentDepth");/**diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.tsindex eb6d15222..35145513c 100644--- a/packages/eve/src/execution/dispatch-runtime-actions-step.ts+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.ts@@ -46,6 +46,7 @@ import { buildSubagentRunInput, type SubagentInputSource } from "#execution/subaimport { createWorkflowRuntime, workflowEntryReference } from "#execution/workflow-runtime.js";import { createLogger, logError } from "#internal/logging.js";import { toErrorMessage } from "#shared/errors.js";+import { readSessionTraceContext } from "#harness/agent-trace-context-store.js";import { resolveSubagentDepth } from "#harness/subagent-depth.js";const log = createLogger("execution.dispatch-runtime-actions");@@ -88,6 +89,9 @@ export async function dispatchRuntimeActionsStep(input: {const adapterCtx = buildAdapterContext(adapter, ctx);const subagentDepth = resolveSubagentDepth(session);+ // Read here, not in the child: trace state is scoped to one session's+ // context, so this is the last place the parent's window is visible.+ const parentTraceContext = readSessionTraceContext(input.serializedContext, session.sessionId);// Split the parent's remaining token quota across the batch's local// subagent calls, the children that actually receive an enforced cap.// Remote agents run on their own deployment under their own limits and@@ -138,6 +142,7 @@ export async function dispatchRuntimeActionsStep(input: {fanoutSize,initiatorAuth,parentContinuationToken: input.parentContinuationToken,+ parentTraceContext,session,source,});diff --git a/packages/eve/src/execution/runtime-context.ts b/packages/eve/src/execution/runtime-context.tsindex db18fd854..2a88efa9a 100644--- a/packages/eve/src/execution/runtime-context.ts+++ b/packages/eve/src/execution/runtime-context.ts@@ -10,6 +10,7 @@ import {InitiatorAuthKey,ModeKey,ParentSessionKey,+ ParentTraceContextKey,SessionCallbackKey,SubagentDepthKey,} from "#context/keys.js";@@ -58,6 +59,10 @@ export function buildRunContext(input: {ctx.set(ParentSessionKey, run.parent);}+ if (run.parentTraceContext !== undefined) {+ ctx.set(ParentTraceContextKey, run.parentTraceContext);+ }+if (run.subagentDepth !== undefined) {ctx.set(SubagentDepthKey, run.subagentDepth);}diff --git a/packages/eve/src/execution/subagent-tool.test.ts b/packages/eve/src/execution/subagent-tool.test.tsindex d18f05f92..658f61ee2 100644--- a/packages/eve/src/execution/subagent-tool.test.ts+++ b/packages/eve/src/execution/subagent-tool.test.ts@@ -208,6 +208,28 @@ describe("buildSubagentRunInput", () => {expect(runInput.input.outputSchema).toEqual(schema);});+ it("hands the parent's trace window down to the child, and omits it when absent", () => {+ const traceContext = { spanId: "2".repeat(16), traceFlags: 1, traceId: "1".repeat(32) };+ const { runInput } = buildRuntimeSubagentRunInput({+ action: makeAction(),+ auth: null,+ batchEvent: { sequence: 0, turnId: "turn-0" },+ initiatorAuth: null,+ parentTraceContext: traceContext,+ session: makeSession(),+ });+ expect(runInput.parentTraceContext).toEqual(traceContext);++ const untraced = buildRuntimeSubagentRunInput({+ action: makeAction(),+ auth: null,+ batchEvent: { sequence: 0, turnId: "turn-0" },+ initiatorAuth: null,+ session: makeSession(),+ });+ expect(untraced.runInput.parentTraceContext).toBeUndefined();+ });+it("passes a resolved local subagent description into the child message", () => {const { runInput } = buildSubagentRunInput({action: {diff --git a/packages/eve/src/execution/subagent-tool.ts b/packages/eve/src/execution/subagent-tool.tsindex 35dd63c0f..4ebc717c2 100644--- a/packages/eve/src/execution/subagent-tool.ts+++ b/packages/eve/src/execution/subagent-tool.ts@@ -9,6 +9,7 @@ import type {RunSessionLimits,SessionAuthContext,SessionCapabilities,+ SessionTraceContext,} from "#channel/types.js";import type { HarnessSession } from "#harness/types.js";import type { RuntimeSubagentCallActionRequest } from "#runtime/actions/types.js";@@ -69,6 +70,7 @@ export function buildSubagentRunInput(input: {readonly initiatorAuth: SessionAuthContext | null;/** Hook token owned by the workflow currently waiting for this child. */readonly parentContinuationToken?: string;+ readonly parentTraceContext?: SessionTraceContext;readonly session: HarnessSession;readonly source: SubagentInputSource;}): SubagentRunInputBuild {@@ -136,6 +138,7 @@ export function buildSubagentRunInput(input: {sequence: batchEvent.sequence,},},+ parentTraceContext: input.parentTraceContext,subagentDepth: subagentDepth.nextChildDepth,};diff --git a/packages/eve/src/harness/agent-otel-provider.test.ts b/packages/eve/src/harness/agent-otel-provider.test.tsindex dcc6e545f..d755e3a63 100644--- a/packages/eve/src/harness/agent-otel-provider.test.ts+++ b/packages/eve/src/harness/agent-otel-provider.test.ts@@ -11,12 +11,14 @@ import { createAiSdkHookBridge } from "#harness/ai-sdk-hook-bridge.js";import {createAgentOtelInstrumentation,InMemoryAgentTraceStateStore,+ SESSION_WINDOW_TURN_LIMIT,} from "#harness/agent-otel-provider.js";import {createInstrumentationHooks,type InstrumentationAttemptScope,type InstrumentationContextRunner,type InstrumentationHooks,+ type InstrumentationTraceContext,} from "#harness/instrumentation-lifecycle.js";interface TestRuntime {@@ -140,19 +142,24 @@ async function emitAttempt(input: {async function publishTurnStarted(input: {readonly hooks: InstrumentationHooks;+ readonly parentTraceContext?: InstrumentationTraceContext;+ readonly rootSessionId?: string;readonly sessionId: string;readonly turnId: string;readonly turnSequence: number;}): Promise<void> {+ const rootSessionId = input.rootSessionId ?? input.sessionId;await input.hooks.publish({agentName: "weather",channelKind: "http",- rootSessionId: input.sessionId,+ parentTraceContext: input.parentTraceContext,+ rootSessionId,sessionId: input.sessionId,type: "session.started",});await input.hooks.publish({- rootSessionId: input.sessionId,+ parentTraceContext: input.parentTraceContext,+ rootSessionId,sequence: input.turnSequence,sessionId: input.sessionId,turnId: input.turnId,@@ -185,8 +192,14 @@ describe("createAgentOtelInstrumentation", () => {const action = byName(spans, "agent.action")[0]!;const tool = byName(spans, "ai.toolCall")[0]!;- expect(byName(spans, "agent.session")).toHaveLength(0);- expect(turn.parentSpanContext?.spanId).toBeDefined();+ const session = byName(spans, "agent.session")[0]!;+ expect(session.parentSpanContext).toBeUndefined();+ expect(session.events.map((event) => event.name)).toEqual(["session.started"]);+ expect(session.attributes).toMatchObject({+ "agent.session.id": "session-1",+ "agent.session.window": 0,+ });+ expect(turn.parentSpanContext?.spanId).toBe(session.spanContext().spanId);expect(turnTerminal.parentSpanContext?.spanId).toBe(turn.spanContext().spanId);expect(step.parentSpanContext?.spanId).toBe(turn.spanContext().spanId);expect(operation.parentSpanContext?.spanId).toBe(step.spanContext().spanId);@@ -194,7 +207,7 @@ describe("createAgentOtelInstrumentation", () => {expect(action.parentSpanContext?.spanId).toBe(step.spanContext().spanId);expect(tool.parentSpanContext?.spanId).toBe(action.spanContext().spanId);expect(new Set(spans.map((span) => span.spanContext().traceId))).toHaveLength(1);- expect(turn.events.map((event) => event.name)).toEqual(["turn.started", "session.started"]);+ expect(turn.events.map((event) => event.name)).toEqual(["turn.started"]);expect(turnTerminal.events.map((event) => event.name)).toEqual(["turn.completed","session.waiting",@@ -296,9 +309,11 @@ describe("createAgentOtelInstrumentation", () => {];expect(turns).toHaveLength(2);expect(turns[0]!.spanContext().traceId).toBe(turns[1]!.spanContext().traceId);- expect(- turns.flatMap((turn) => turn.events).filter((event) => event.name === "session.started"),- ).toHaveLength(1);+ expect(turns.every((turn) => turn.attributes["agent.session.window"] === 0)).toBe(true);+ expect([+ ...byName(firstRuntime.exporter.getFinishedSpans(), "agent.session"),+ ...byName(secondRuntime.exporter.getFinishedSpans(), "agent.session"),+ ]).toHaveLength(1);});it("restores durable turn context when a replacement worker runs the attempt", async () => {@@ -333,7 +348,7 @@ describe("createAgentOtelInstrumentation", () => {expect(step.spanContext().traceId).toBe(turn.spanContext().traceId);});- it("derives the same session trace id when a durable attempt replays before checkpoint", async () => {+ it("opens a fresh window when a durable attempt replays before its state checkpoints", async () => {const firstRuntime = createRuntime();const replayRuntime = createRuntime();await emitAttempt({@@ -353,7 +368,129 @@ describe("createAgentOtelInstrumentation", () => {const firstTurn = byName(firstRuntime.exporter.getFinishedSpans(), "agent.turn")[0]!;const replayTurn = byName(replayRuntime.exporter.getFinishedSpans(), "agent.turn")[0]!;- expect(replayTurn.spanContext().traceId).toBe(firstTurn.spanContext().traceId);+ // The abandoned attempt keeps its own trace rather than interleaving with+ // the retry. Both carry `agent.session.id`, so the session view still+ // resolves to every trace the session produced.+ expect(replayTurn.spanContext().traceId).not.toBe(firstTurn.spanContext().traceId);+ expect(replayTurn.attributes["agent.session.id"]).toBe(+ firstTurn.attributes["agent.session.id"],+ );+ });++ it("rolls to a new window trace once a session outgrows the turn limit", async () => {+ const runtime = createRuntime();+ for (let sequence = 0; sequence <= SESSION_WINDOW_TURN_LIMIT; sequence += 1) {+ await publishTurnStarted({+ hooks: runtime.hooks,+ sessionId: "session-1",+ turnId: `turn-${sequence}`,+ turnSequence: sequence,+ });+ }+ await runtime.provider.forceFlush();++ const spans = runtime.exporter.getFinishedSpans();+ 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);+ });++ it("records a subagent child into the window its parent had open", async () => {+ const runtime = createRuntime();+ await publishTurnStarted({+ hooks: runtime.hooks,+ sessionId: "session-1",+ turnId: "turn-1",+ turnSequence: 0,+ });+ await runtime.provider.forceFlush();+ const parentWindow = byName(runtime.exporter.getFinishedSpans(), "agent.session")[0]!;++ await publishTurnStarted({+ hooks: runtime.hooks,+ parentTraceContext: parentWindow.spanContext(),+ rootSessionId: "session-1",+ sessionId: "child-1",+ turnId: "child-turn-1",+ turnSequence: 0,+ });+ 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.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(byName(spans, "agent.session")).toHaveLength(1);+ });++ it("opens its own root when a child session is handed no parent window", async () => {+ const runtime = createRuntime();+ await publishTurnStarted({+ hooks: runtime.hooks,+ rootSessionId: "session-1",+ sessionId: "child-1",+ turnId: "child-turn-1",+ turnSequence: 0,+ });+ await runtime.provider.forceFlush();++ const sessions = byName(runtime.exporter.getFinishedSpans(), "agent.session");+ expect(sessions).toHaveLength(1);+ expect(sessions[0]!.attributes["agent.session.id"]).toBe("child-1");+ expect(sessions[0]!.parentSpanContext).toBeUndefined();+ });++ it("rolls a long subagent child out of the window it adopted", async () => {+ const runtime = createRuntime();+ await publishTurnStarted({+ hooks: runtime.hooks,+ sessionId: "session-1",+ turnId: "turn-1",+ turnSequence: 0,+ });+ await runtime.provider.forceFlush();+ const parentWindow = byName(runtime.exporter.getFinishedSpans(), "agent.session")[0]!;++ for (let sequence = 0; sequence <= SESSION_WINDOW_TURN_LIMIT; sequence += 1) {+ await publishTurnStarted({+ hooks: runtime.hooks,+ parentTraceContext: parentWindow.spanContext(),+ rootSessionId: "session-1",+ sessionId: "child-1",+ turnId: `child-turn-${sequence}`,+ turnSequence: 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);});it("marks a failed action without failing its turn", async () => {diff --git a/packages/eve/src/harness/agent-otel-provider.ts b/packages/eve/src/harness/agent-otel-provider.tsindex 45fffec3e..8807d1714 100644--- a/packages/eve/src/harness/agent-otel-provider.ts+++ b/packages/eve/src/harness/agent-otel-provider.ts@@ -1,5 +1,3 @@-import { createHash } from "node:crypto";-import {ROOT_CONTEXT,SpanStatusCode,@@ -21,6 +19,7 @@ import type {InstrumentationModelCallStartedEvent,InstrumentationProviderDefinition,InstrumentationSessionStartedEvent,+ InstrumentationTraceContext,InstrumentationSessionTransitionEvent,InstrumentationToolCallStartedEvent,InstrumentationToolCallTerminalEvent,@@ -42,12 +41,16 @@ interface ToolSpanState extends SpanState {readonly toolSpan: Span;}+/** 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 agentName?: string;readonly channelKind?: string;readonly context: SpanContext;- readonly pendingStarted: boolean;readonly rootSessionId: string;+ readonly turnsInWindow: number;+ readonly window: number;}export interface AgentTurnTraceState {@@ -135,13 +138,17 @@ export function createAgentOtelInstrumentation(};const onTurnStarted = async (event: InstrumentationTurnStartedEvent): Promise<void> => {- const session = await ensureSessionContext({- agentName: undefined,- channelKind: undefined,- rootSessionId: event.rootSessionId,- sessionId: event.sessionId,- type: "session.started",- });+ const session = advanceSessionWindow(+ event.sessionId,+ await ensureSessionContext({+ agentName: undefined,+ channelKind: undefined,+ parentTraceContext: event.parentTraceContext,+ rootSessionId: event.rootSessionId,+ sessionId: event.sessionId,+ type: "session.started",+ }),+ );const span = input.tracer.startSpan("agent.turn",{@@ -151,6 +158,7 @@ export function createAgentOtelInstrumentation("agent.name": session.agentName,"agent.root.session.id": event.rootSessionId,"agent.session.id": event.sessionId,+ "agent.session.window": session.window,"agent.turn.id": event.turnId,"agent.turn.sequence": event.sequence,},@@ -158,12 +166,9 @@ export function createAgentOtelInstrumentation(contextFromSpanContext(session.context),);span.addEvent("turn.started");- if (session.pendingStarted) {- span.addEvent("session.started");- }await input.stateStore.setSession(event.sessionId, {...session,- pendingStarted: false,+ turnsInWindow: session.turnsInWindow + 1,});await input.stateStore.setTurn(event.sessionId, event.turnId, {context: span.spanContext(),@@ -371,6 +376,34 @@ export function createAgentOtelInstrumentation(state.span.end();};+ const openSessionWindow = (window: {+ readonly agentName?: string;+ readonly index: number;+ readonly previousTraceId?: string;+ readonly rootSessionId: string;+ readonly sessionId: string;+ }): SpanContext => {+ const span = input.tracer.startSpan("agent.session", {+ attributes: {+ "agent.framework.name": "eve",+ "agent.framework.version": input.frameworkVersion,+ "agent.name": window.agentName,+ "agent.root.session.id": window.rootSessionId,+ "agent.session.id": window.sessionId,+ "agent.session.window": window.index,+ ...(window.previousTraceId === undefined+ ? {}+ : { "agent.session.window.previous.trace.id": window.previousTraceId }),+ },+ root: true,+ });+ span.addEvent(window.index === 0 ? "session.started" : "session.window.opened");+ // The window outlives this worker, so the root is recorded as a marker and+ // later spans parent through its persisted context, as `agent.turn` does.+ span.end();+ return span.spanContext();+ };+const ensureSessionContext = async (event: InstrumentationSessionStartedEvent,): Promise<AgentSessionTraceState> => {@@ -379,15 +412,44 @@ export function createAgentOtelInstrumentation(state = {agentName: event.agentName,channelKind: event.channelKind,- context: sessionTraceContext(event.sessionId),- pendingStarted: true,+ context:+ event.parentTraceContext === undefined+ ? openSessionWindow({+ agentName: event.agentName,+ index: 0,+ rootSessionId: event.rootSessionId,+ sessionId: event.sessionId,+ })+ : adoptedSpanContext(event.parentTraceContext),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,+ index,+ previousTraceId: session.context.traceId,+ rootSessionId: session.rootSessionId,+ sessionId,+ }),+ turnsInWindow: 0,+ window: index,+ };+ };+const onAttemptMetadata = (event: InstrumentationAttemptMetadataEvent): void => {const attempt = steps.get(event.scope);if (attempt === undefined) return;@@ -447,18 +509,17 @@ function turnKey(sessionId: string, turnId: string): string {return `${sessionId}:${turnId}`;}-function sessionTraceContext(sessionId: string): SpanContext {+function adoptedSpanContext(handed: InstrumentationTraceContext): SpanContext {return {- spanId: digestId(`eve:session-parent:${sessionId}`, 16),- traceFlags: 1,- traceId: digestId(`eve:session:${sessionId}`, 32),+ // Not remote: a subagent crosses the same worker boundary every restored+ // session context does, not the wire.+ isRemote: false,+ spanId: handed.spanId,+ traceFlags: handed.traceFlags,+ traceId: handed.traceId,};}-function digestId(value: string, length: number): string {- return createHash("sha256").update(value).digest("hex").slice(0, length);-}-function contextFromSpanContext(spanContext: SpanContext): Context {return trace.setSpan(ROOT_CONTEXT, trace.wrapSpanContext(spanContext));}diff --git a/packages/eve/src/harness/agent-trace-context-store.test.ts b/packages/eve/src/harness/agent-trace-context-store.test.tsindex e2155d9ee..f95856b3e 100644--- a/packages/eve/src/harness/agent-trace-context-store.test.ts+++ b/packages/eve/src/harness/agent-trace-context-store.test.ts@@ -5,6 +5,7 @@ import { deserializeContext, serializeContext } from "#context/serialize.js";import {ContextAgentTraceStateStore,preserveSerializedAgentTraceState,+ readSessionTraceContext,} from "#harness/agent-trace-context-store.js";describe("ContextAgentTraceStateStore", () => {@@ -15,8 +16,9 @@ describe("ContextAgentTraceStateStore", () => {store.setSession("session-1", {agentName: "weather",context: spanContext("1", "2"),- pendingStarted: false,rootSessionId: "session-1",+ turnsInWindow: 3,+ window: 1,});store.setTurn("session-1", "turn-1", {context: spanContext("1", "3"),@@ -31,6 +33,7 @@ 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")?.terminal?.error).toMatchObject({message: "failed",@@ -43,8 +46,9 @@ describe("ContextAgentTraceStateStore", () => {const store = new ContextAgentTraceStateStore();store.setSession("session-1", {context: spanContext("1", "2"),- pendingStarted: true,rootSessionId: "session-1",+ turnsInWindow: 0,+ window: 0,});store.setTurn("session-1", "turn-1", {context: spanContext("1", "3"),@@ -65,8 +69,9 @@ describe("ContextAgentTraceStateStore", () => {await contextStorage.run(context, () => {new ContextAgentTraceStateStore().setSession("session-1", {context: spanContext("1", "2"),- pendingStarted: true,rootSessionId: "session-1",+ turnsInWindow: 0,+ window: 0,});});@@ -78,6 +83,25 @@ describe("ContextAgentTraceStateStore", () => {});});+describe("readSessionTraceContext", () => {+ it("reads one session's window 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);++ expect(readSessionTraceContext(serialized, "session-1")).toEqual(spanContext("1", "2"));+ expect(readSessionTraceContext(serialized, "session-2")).toBeUndefined();+ expect(readSessionTraceContext({}, "session-1")).toBeUndefined();+ });+});+function spanContext(traceId: string, spanId: string) {return { spanId: spanId.repeat(16), traceFlags: 1, traceId: traceId.repeat(32) };}diff --git a/packages/eve/src/harness/agent-trace-context-store.ts b/packages/eve/src/harness/agent-trace-context-store.tsindex c0decc981..8fa4e24d1 100644--- a/packages/eve/src/harness/agent-trace-context-store.ts+++ b/packages/eve/src/harness/agent-trace-context-store.ts@@ -31,6 +31,20 @@ export function preserveSerializedAgentTraceState(: { ...original, [AgentTraceContextKey.name]: traceState };}+/**+ * Reads a named session's trace window straight out of a serialized context,+ * which {@link ContextAgentTraceStateStore} cannot do — its reads are scoped+ * to the ambient session.+ */+export function readSessionTraceContext(+ serializedContext: Readonly<Record<string, unknown>>,+ sessionId: string,+): SpanContext | undefined {+ const raw = serializedContext[AgentTraceContextKey.name];+ if (raw === undefined) return undefined;+ return deserializeState(raw).sessions[sessionId]?.context;+}+/** Durable trace state backed by eve's serialized Workflow context. */export class ContextAgentTraceStateStore implements AgentTraceStateStore {deleteSession(sessionId: string): void {@@ -115,8 +129,9 @@ function deserializeState(data: unknown): AgentTraceContextState {agentName: typeof value.agentName === "string" ? value.agentName : undefined,channelKind: typeof value.channelKind === "string" ? value.channelKind : undefined,context: value.context,- pendingStarted: value.pendingStarted === true,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) => {diff --git a/packages/eve/src/harness/agent-trace-span-processor.test.ts b/packages/eve/src/harness/agent-trace-span-processor.test.tsindex 3cbac6c22..4aa5d788d 100644--- a/packages/eve/src/harness/agent-trace-span-processor.test.ts+++ b/packages/eve/src/harness/agent-trace-span-processor.test.ts@@ -42,12 +42,53 @@ describe("AgentTraceSpanProcessor", () => {expect([...processor.activeTraceIds()]).toEqual(["trace-2"]);});+ it("releases every window 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"]);++ expect(processor.releaseSession("session-1")).toBe(true);+ expect([...processor.activeTraceIds()]).toEqual([]);+ });+it("reports no release for a session it never owned", () => {const processor = new AgentTraceSpanProcessor([]);expect(processor.releaseSession("session-unknown")).toBe(false);});+ it("keeps a shared trace pinned when a subagent child finishes first", () => {+ const child = {+ forceFlush: vi.fn(async () => {}),+ onEnd: vi.fn(),+ onStart: vi.fn(),+ 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",+ };+ processor.onStart(span("trace-1", owned), {});+ processor.onStart(span("trace-1", delegated), {});++ expect(processor.releaseSession("child-1")).toBe(false);+ expect([...processor.activeTraceIds()]).toEqual(["trace-1"]);++ // The parent is still writing to the trace the child recorded into.+ const later = span("trace-1", owned);+ processor.onEnd(later);+ expect(child.onEnd).toHaveBeenCalledWith(later);++ expect(processor.releaseSession("session-1")).toBe(true);+ expect([...processor.activeTraceIds()]).toEqual([]);+ });+it("excludes Workflow instrumentation from an agent trace", () => {const child = {forceFlush: vi.fn(async () => {}),diff --git a/packages/eve/src/harness/agent-trace-span-processor.ts b/packages/eve/src/harness/agent-trace-span-processor.tsindex 39ea26ff3..99daa8065 100644--- a/packages/eve/src/harness/agent-trace-span-processor.ts+++ b/packages/eve/src/harness/agent-trace-span-processor.ts@@ -10,7 +10,7 @@ interface SpanLike {export class AgentTraceSpanProcessor implements SpanProcessor {readonly #children: readonly SpanProcessor[];readonly #ownedTraceIds = new Set<string>();- readonly #sessionTraceIds = new Map<string, string>();+ readonly #sessionTraceIds = new Map<string, Set<string>>();#attached = false;constructor(children: readonly SpanProcessor[]) {@@ -30,9 +30,13 @@ 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);- this.#sessionTraceIds.set(sessionId, traceId);+ const owned = this.#sessionTraceIds.get(owner) ?? new Set<string>();+ owned.add(traceId);+ this.#sessionTraceIds.set(owner, owned);}if (!this.#accepts(span)) return;for (const child of this.#children) child.onStart(span, parentContext);@@ -48,11 +52,15 @@ export class AgentTraceSpanProcessor implements SpanProcessor {return this.#ownedTraceIds;}- /** Forgets one session's trace, reporting whether it owned one. */+ /**+ * Forgets every trace one root session owned, reporting whether it owned any.+ * A subagent child owns none, so releasing one reports `false` and leaves the+ * shared trace pinned until its root finishes.+ */releaseSession(sessionId: string): boolean {- const traceId = this.#sessionTraceIds.get(sessionId);- if (traceId === undefined) return false;- this.#ownedTraceIds.delete(traceId);+ const owned = this.#sessionTraceIds.get(sessionId);+ if (owned === undefined) return false;+ for (const traceId of owned) this.#ownedTraceIds.delete(traceId);this.#sessionTraceIds.delete(sessionId);return true;}diff --git a/packages/eve/src/harness/instrumentation-lifecycle.ts b/packages/eve/src/harness/instrumentation-lifecycle.tsindex 828a30693..ff9f3d57c 100644--- a/packages/eve/src/harness/instrumentation-lifecycle.ts+++ b/packages/eve/src/harness/instrumentation-lifecycle.ts@@ -26,10 +26,17 @@ export interface InstrumentationSessionStartedEvent {readonly type: "session.started";readonly agentName?: string;readonly channelKind?: string;+ readonly parentTraceContext?: InstrumentationTraceContext;readonly rootSessionId: string;readonly sessionId: string;}+export interface InstrumentationTraceContext {+ readonly spanId: string;+ readonly traceFlags: number;+ readonly traceId: string;+}+export interface InstrumentationSessionTransitionEvent {readonly type: "session.completed" | "session.failed" | "session.waiting";readonly error?: unknown;@@ -39,6 +46,7 @@ export interface InstrumentationSessionTransitionEvent {export interface InstrumentationTurnStartedEvent {readonly type: "turn.started";+ readonly parentTraceContext?: InstrumentationTraceContext;readonly rootSessionId: string;readonly sequence: number;readonly sessionId: string;diff --git a/packages/eve/src/harness/instrumentation-native-events.ts b/packages/eve/src/harness/instrumentation-native-events.tsindex ff8289cb5..b5063baaa 100644--- a/packages/eve/src/harness/instrumentation-native-events.ts+++ b/packages/eve/src/harness/instrumentation-native-events.ts@@ -2,6 +2,7 @@ import type { UnstampedMessageStreamEvent } from "#protocol/message.js";import type {InstrumentationHooks,InstrumentationPointEvent,+ InstrumentationTraceContext,} from "#harness/instrumentation-lifecycle.js";import type { HandleEventFn } from "#harness/types.js";@@ -9,6 +10,7 @@ export interface CreateInstrumentationHandleEventInput {readonly agentName?: string;readonly handleEvent?: HandleEventFn;readonly hooks?: InstrumentationHooks;+ readonly parentTraceContext?: InstrumentationTraceContext;readonly rootSessionId?: string;readonly sessionId: string;readonly turnId?: string;@@ -41,6 +43,7 @@ function toLifecycleEvent(case "session.started":return {agentName: input.agentName,+ parentTraceContext: input.parentTraceContext,rootSessionId: input.rootSessionId ?? input.sessionId,sessionId: input.sessionId,type: "session.started",@@ -57,6 +60,7 @@ function toLifecycleEvent(};case "turn.started":return {+ parentTraceContext: input.parentTraceContext,rootSessionId: input.rootSessionId ?? input.sessionId,sequence: event.data.sequence,sessionId: input.sessionId,diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.tsindex 9851260cc..b4e4599dc 100644--- a/packages/eve/src/harness/tool-loop.ts+++ b/packages/eve/src/harness/tool-loop.ts@@ -30,7 +30,7 @@ import {} from "#internal/logging.js";import { formatLanguageModelGatewayId } from "#internal/runtime-model.js";import { contextStorage } from "#context/container.js";-import { AuthKey, ParentSessionKey } from "#context/keys.js";+import { AuthKey, ParentSessionKey, ParentTraceContextKey } from "#context/keys.js";import { buildDynamicInstructionMessages } from "#context/dynamic-instruction-lifecycle.js";import { getActiveDynamicModelSelection } from "#context/dynamic-model-lifecycle.js";import { buildDynamicTools } from "#context/build-dynamic-tools.js";@@ -536,11 +536,13 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {}let emissionState = getHarnessEmissionState(session.state);- const parent = contextStorage.getStore()?.get(ParentSessionKey);+ const store = contextStorage.getStore();+ const parent = store?.get(ParentSessionKey);const emit = createInstrumentationHandleEvent({agentName: config.runtimeIdentity?.agentName,handleEvent: baseEmit,hooks: config.instrumentation?.hooks,+ parentTraceContext: store?.get(ParentTraceContextKey),rootSessionId: parent?.rootSessionId,sessionId: session.sessionId,turnId: activeTurnId(emissionState),diff --git a/research/provider-neutral-local-observability.md b/research/provider-neutral-local-observability.mdindex 8f597c2f0..76eec2920 100644--- a/research/provider-neutral-local-observability.md+++ b/research/provider-neutral-local-observability.md@@ -1,126 +1,80 @@---issue: TBD-status: proposed-last_updated: "2026-07-24"+status: in-progress+last_updated: "2026-07-30"---# Provider-neutral local observability## Summary-eve should produce useful local traces without depending on Workflow tracing, changing production-instrumentation, or coupling observability providers directly to the AI SDK.--The first consumer is zero-config tracing in `eve dev`, but the lifecycle contract must support-OTel, Vercel, Braintrust, and custom providers.--## Desired flow+eve produces local traces without depending on Workflow tracing, changing production+instrumentation, or coupling observability providers to the AI SDK. The first consumer is+zero-config tracing in `eve dev`; the lifecycle contract must also support OTel, Vercel,+Braintrust, and custom providers.```text-eve lifecycle boundaries -------------------+- +--> eve lifecycle hooks-AI SDK callbacks -> per-attempt bridge -------+ |- +--> local OTel provider-AI SDK execute() -> eve-owned context runner +--> Vercel provider- +--> Braintrust provider- +--> custom providers+eve lifecycle boundaries ------------------++ +--> eve lifecycle hooks --> providers+AI SDK callbacks -> per-attempt bridge -----+ (local OTel, Vercel, Braintrust, custom)+AI SDK execute() -> eve-owned context runner```-The AI SDK bridge is an adapter, not an instrumentation provider. It translates AI SDK callbacks-into immutable, eve-owned lifecycle events.--Providers never receive raw AI SDK event types or execution functions.-## Lifecycle contract-The bridge receives stable attempt scope and typed lifecycle hooks:-```tscreateAiSdkHookBridge(scope, hooks, runInContext): Telemetry;-```--```ts-interface LifecycleHooks {- publish(event: LifecycleEvent): Promise<void>;-- before(name: "model.call", event: ModelCallStartedEvent): Promise<void>;- after(name: "model.call", event: ModelCallTerminalEvent): Promise<void>;- before(name: "tool.call", event: ToolCallStartedEvent): Promise<void>;- after(name: "tool.call", event: ToolCallTerminalEvent): Promise<void>;+interface InstrumentationHooks {+ publish(event: InstrumentationPointEvent): Promise<void>;+ before(name: "model.call" | "tool.call", event: StartEvent): Promise<void>;+ after(name: "model.call" | "tool.call", event: TerminalEvent): Promise<void>;}```-Lifecycle events use eve-owned identities and payloads. AI SDK `callId` values are bridge-correlation details, not provider run identities.+The bridge is an adapter, not a provider. It maps AI SDK callbacks into eve-owned lifecycle+events, assigns stable attempt/model-call/tool-call identities, terminalizes open operations on+error and abort, and invokes the trusted `runInContext` while calling execution exactly once. AI+SDK `callId` values are bridge correlation details, not provider run identities.-Related `before` state is retained per provider and operation, then supplied only to that-provider's `after`. Attempt state is scoped by object identity and WeakMap-backed so abandoned-attempts do not leak state.+The bridge does not create spans, export records, apply capture policy, or publish durable+eve-native events. Session, turn, compaction, suspension, and canonical step-terminal events are+published by the harness.-## Bridge responsibilities+Attempt state is WeakMap-keyed by scope identity so abandoned attempts do not leak. `before` state+is retained per provider and operation and supplied only to that provider's `after`.-The bridge:+## Providers-- snapshots AI SDK callbacks;-- maps them into eve-owned lifecycle events;-- assigns stable attempt, model-call, and tool-call identities;-- publishes starts and terminals through typed hooks;-- terminalizes open operations on errors and aborts;-- invokes trusted `runInContext` with a typed model or tool operation while calling execution- exactly once.+A provider is a hook definition: handlers for the eve-owned events it cares about. An OTel provider+may return spans from `before` and close them in `after`; Braintrust may retain row handles; Vercel+may enqueue records.-The bridge does not create spans, export records, apply provider capture policy, or publish durable-eve-native events.+Each provider owns an independent trace graph, rooted from its own serializable session state — not+from ambient Workflow context or another provider's active context.-Session, turn, compaction, suspension, and canonical step-terminal events are published directly-by the eve harness.--## Provider responsibilities--Providers are ordinary lifecycle hook definitions. Each provider subscribes by defining handlers-only for the eve-owned events it cares about; the lifecycle dispatcher invokes those handlers when-the corresponding boundaries occur.--An OTel provider may return spans from `before` and close them in `after`. Braintrust may retain-native row handles. Vercel may enqueue normalized records.--Each provider owns an independent trace graph. It creates or restores its root from provider-owned,-serializable session state and derives later parentage from that state. Providers do not use ambient-Workflow context, or another provider's active context, as their trace parent.--Providers never receive an execution function. A built-in integration that needs ambient context-may register a trusted internal `runInContext` alongside its event definition; it is passed directly-to the bridge and is not part of the provider or hook contract.+Providers never receive an execution function. A built-in integration needing ambient context may+register a trusted internal `runInContext` alongside its event definition; that is not part of the+provider contract.## Local tracing-`eve dev` registers a private local OTel provider that consumes the same lifecycle events as other-providers.--The local provider:+In `eve dev` eve registers the process tracer provider (`registerOTel`) with a private span+processor consuming the same lifecycle events as any other provider, so nested AI SDK and user+spans share agent context. It creates one trace per session window, explicitly roots that window+rather than inheriting the ambient Workflow span, drops spans from the `workflow` instrumentation+scope, and persists OTLP/JSON segments under `.eve/traces/v1`.-- is registered privately by eve while using the process OTel runtime so nested user spans share- agent context;-- creates one trace per eve session, independently from Workflow context;-- explicitly roots session context instead of inheriting the ambient Workflow span;-- never captures Workflow spans;-- persists traces as OTLP/JSON for later inspection.+Those immutable segments are the canonical local store. A future index or dashboard is a+rebuildable consumer of the spool, not a second source of trace identity.-Immutable OTLP/JSON segments are the canonical local store. A future DuckDB or dashboard index is a-rebuildable consumer of that spool, not a second source of trace identity or Workflow continuation-state.--Authored instrumentation and local capture may observe the same attempt concurrently without-executing the model or tool more than once.+Authored instrumentation and local capture may observe the same attempt without executing the model+or tool more than once.## Agent OTel semantics-The local OTel provider emits an agent-first structural convention. GenAI spans may remain nested-implementation detail, but they do not define the agent run.-```text-session trace {agent.session.id}+agent.session {agent.session.id, agent.session.window}+-- agent.turn {agent.turn.id, agent.turn.sequence}+-- agent.step {agent.step.index, agent.step.attempt}+-- model-provider spans@@ -128,89 +82,136 @@ session trace {agent.session.id}+-- tool-provider spans```-The session is the trace, not a long-lived span. All turns share its trace id. Session lifecycle-events attach to the turn that causes the transition; a transition without a turn may use a-zero-duration marker span.+GenAI spans stay nested implementation detail; they do not define the agent run. An `agent.step`+covers one model call and the actions it requests through their resolution. `agent.action.kind` is+an open discriminator — `tool` today, with `skill`, `subagent`, and `remote-agent` reserved.-An `agent.step` covers one model call and the actions it requests through their resolution.-`agent.action.kind` is an open discriminator for `tool`, `skill`, `subagent`, and `remote-agent`.-Subagents use their own session trace and link back to the calling action.+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+default. The OTel provider owns this mapping; the bridge and hooks contain no span names,+attributes, or parent contexts.-The `agent.*` namespace contains cheap structural attributes: session, turn, step and attempt-identity; action identity; agent/framework identity; channel and environment; principal; and-parent/root lineage. Message content, model output, tool arguments, and tool results are optional-capture, off by default.+### Session windows-The OTel provider owns this mapping. The AI SDK bridge and lifecycle hooks do not contain OTel span-names, attributes, or parent contexts.+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.-## Runtime integration+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++`agent.session` is a real root span opened with OTel's `root` option, not a synthesized parent+context. eve persists its span context — including the sampling decision it actually received — and+later turns in the window parent to that stored context.++This is what makes an authored sampler work. A synthesized parent asserting a sampled flag is a+valid parent to `ParentBasedSampler`, which resolves through a parent branch and never consults the+configured root rule. Asserting unsampled instead selects `localParentNotSampled`, which drops+everything. 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.++### Marker spans++The window root is recorded and ended immediately, as `agent.turn` already is. A window outlives the+worker 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.++The cost is that a backend reports the root's duration rather than the window's. Turn and step+durations, where the time actually is, are unaffected, and `eve traces` renders a marker's+descendant extent in place of its zero duration.-The bridge is injected per actual model attempt:+A real duration would mean emitting the span once at window close, with explicit timestamps and a+span 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 never+arrives. A marker is the only representation that is always emitted. `agent.turn` does have a+guaranteed 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.++## Runtime integration```textrunModelCallWithRetries(attempt)-> create stable AttemptScope-> createAiSdkHookBridge(scope, hooks, runInContext)-> telemetry.integrations = [bridge, authoredOtel?]- -> AI SDK invokes callbacks and trusted runInContext```-The harness supplies `sessionId`, `turnId`, logical step index, and retry attempt index. The bridge-derives stable model/tool identities once at their start callbacks and stores callback snapshots in-invocation-local attempt state. `onStepEnd` and `onEnd` only snapshot results; the harness later-publishes the canonical terminal event after durable actions are emitted. On replay, the harness-recreates this attempt state; only provider-owned serializable context crosses Workflow boundaries.--The existing eve stream keeps its current `step.started` boundary. AI SDK `onStepStart` is named-`attempt.started` in the instrumentation lifecycle because it begins one concrete model attempt;-retries and recovery calls therefore have distinct starts and terminals without introducing a-second meaning for `step.started`.+The harness supplies session id, turn id, logical step index, and retry attempt index. The bridge+derives model/tool identities at their start callbacks and keeps callback snapshots in+invocation-local state; `onStepEnd` and `onEnd` only snapshot, and the harness publishes the+canonical terminal after durable actions are emitted. On replay the harness recreates attempt state;+only provider-owned serializable context crosses Workflow boundaries.-AI SDK per-call integrations replace its global list. eve explicitly composes the bridge with its-known `@ai-sdk/otel` adapter when the documented `instrumentation.ts` OTel path is active. Direct-AI SDK `registerTelemetry()` calls are not part of eve's supported customization surface.+AI SDK `onStepStart` is named `attempt.started` because it begins one concrete model attempt, so+retries have distinct starts and terminals without overloading the stream's `step.started`.-Braintrust's documented eve integration uses eve hooks and `defineInstrumentation`, so per-call-bridge injection does not disable it.+Per-call integrations replace the AI SDK global list; eve composes the bridge with `@ai-sdk/otel`+when the documented `instrumentation.ts` path is active. Direct `registerTelemetry()` calls are not+a supported customization surface. Braintrust's documented integration uses eve hooks and+`defineInstrumentation`, so per-call injection does not disable it.## CompatibilityProduction keeps its current `defineInstrumentation` and `@ai-sdk/otel` behavior until provider-migration is explicitly shipped.--Without lifecycle hooks, no bridge override is present and production follows its existing authored-instrumentation path unchanged.--Existing stream hooks and current `step.started` semantics remain unchanged during the initial-local-tracing work.+migration ships. Without lifecycle hooks no bridge is installed and production follows the existing+authored path unchanged. Stream hooks and `step.started` semantics are unchanged.## Delivery phases-1. **Lifecycle bridge.** Land the unused attempt scope, WeakMap-backed state, typed hooks, related- before/after correlation, a trusted context runner, and the AI SDK callback adapter. No- runtime wiring.-2. **Per-attempt wiring.** Add optional internal lifecycle hooks to the harness and pass one bridge- through `telemetry.integrations` per retry attempt, composing authored OTel when active. No- provider or trace output yet.-3. **Local OTel provider.** Add a private provider that maps lifecycle events to the `agent.*`- convention and proves the trace tree in memory. Production remains unchanged.-4. **Persistence.** Write session traces as OTLP/JSON, restore provider-owned session context across- dev worker restarts, and apply payload capture policy. No browser UI.-5. **Inspection.** Add minimal `eve traces ls` and `eve traces [trace]` commands. A graphical viewer is a- separate design after the trace model stabilizes.-6. **Public providers.** Promote the proven lifecycle contract into public hooks and migrate OTel,- Vercel, Braintrust, and custom instrumentation onto it.--The current bridge PR is phase 1 only: it lands unused primitives and cannot emit a trace.+1. **Lifecycle bridge.** — _landed._ Attempt scope, WeakMap state, typed hooks, before/after+ correlation, trusted context runner, AI SDK callback adapter.+2. **Per-attempt wiring.** — _landed._ One bridge per retry attempt through+ `telemetry.integrations`, composing authored OTel when active.+3. **Local OTel provider.** — _landed._ Lifecycle events mapped to the `agent.*` convention.+4. **Persistence.** — _landed._ OTLP/JSON segments, session context restored across dev worker+ restarts, retention bounds, capture policy.+5. **Inspection.** — _landed._ `eve traces ls` and `eve traces [trace]`.+6. **Session windows.** — _in review._ Real `agent.session` root with its recorded sampling+ decision, window rolling, subagent adoption, session-to-windows resolution in `eve traces`.+7. **Public providers.** — _not started._ Promote the lifecycle contract into public hooks and+ migrate OTel, Vercel, Braintrust, and custom instrumentation onto it.## Acceptance criteria-- The provider-neutral lifecycle layer imports no AI SDK or OTel types.+- The lifecycle layer imports no OTel types. It does derive AI SDK callback payload shapes from+ `Telemetry`, so `attempt`, `model.call`, and `tool.call` events currently expose AI SDK types to+ providers — a known deviation from provider neutrality, to close in phase 7.- Multiple providers observe one attempt while execution occurs exactly once.- No provider definition receives model or tool execution functions.- Documented authored instrumentation continues to observe eve calls.-- Each eve provider can build its trace without inheriting Workflow or another provider's trace.+- Each provider builds its trace without inheriting Workflow or another provider's trace.+- No eve span inherits a synthesized parent, so an authored sampler's root rule is consulted.+- A session of ordinary length is exactly one trace; a session of any length has bounded traces.+- `eve traces <session>` resolves every window of a session.- Parallel tool calls retain independent provider state.- Errors and aborts terminalize all started model and tool operations.- Local traces contain no Workflow spans.