Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): record otelIntegration runtimeContext on model-call spans (#2138)

Chad Hietala480de61703c1
diff --git a/packages/eve/src/harness/ai-sdk-hook-bridge.test.ts b/packages/eve/src/harness/ai-sdk-hook-bridge.test.ts
index 001dfcb5f..754bd31e6 100644
--- a/packages/eve/src/harness/ai-sdk-hook-bridge.test.ts
+++ b/packages/eve/src/harness/ai-sdk-hook-bridge.test.ts
@@ -154,6 +154,53 @@ describe("createAiSdkHookBridge", () => {
expect(keys).toEqual([modelCallIdempotencyKey(scope, 2), modelCallIdempotencyKey(scope, 2)]);
});
+ it("attaches merged runtime context to step and model started events", async () => {
+ const stepStarted: InstrumentationStepAttemptStartedEvent[] = [];
+ const modelStarted: InstrumentationModelCallStartedEvent[] = [];
+ const hooks = createInstrumentationHooks([
+ {
+ events: {
+ "model.call.started": (event) => void modelStarted.push(event),
+ "step.attempt.started": (event) => void stepStarted.push(event),
+ },
+ name: "context",
+ },
+ ]);
+ const runtimeContext = { "eve.session.id": "session-1", "posthog.distinct_id": "user-1" };
+ const bridge = createAiSdkHookBridge(scope, hooks, undefined, runtimeContext);
+
+ await Reflect.apply(bridge.onStart!, bridge, [
+ { callId: "call-1", modelId: "model", operationId: "ai.streamText", provider: "test" },
+ ]);
+ await Reflect.apply(bridge.onStepStart!, bridge, [{ callId: "call-1", stepNumber: 0 }]);
+ await Reflect.apply(bridge.onLanguageModelCallStart!, bridge, [
+ { callId: "call-1", messages: [], modelId: "model", provider: "test", tools: undefined },
+ ]);
+
+ expect(stepStarted).toHaveLength(1);
+ expect(stepStarted[0]!.runtimeContext).toEqual(runtimeContext);
+ expect(modelStarted).toHaveLength(1);
+ expect(modelStarted[0]!.runtimeContext).toEqual(runtimeContext);
+ });
+
+ it("omits runtime context from started events when the merged record is empty", async () => {
+ const modelStarted: InstrumentationModelCallStartedEvent[] = [];
+ const hooks = createInstrumentationHooks([
+ {
+ events: { "model.call.started": (event) => void modelStarted.push(event) },
+ name: "context",
+ },
+ ]);
+ const bridge = createAiSdkHookBridge(scope, hooks, undefined, {});
+
+ await Reflect.apply(bridge.onLanguageModelCallStart!, bridge, [
+ { callId: "call-1", messages: [], modelId: "model", provider: "test", tools: undefined },
+ ]);
+
+ expect(modelStarted).toHaveLength(1);
+ expect(modelStarted[0]!.runtimeContext).toBeUndefined();
+ });
+
it("publishes step provider metadata as step.metadata, skipping steps without any", async () => {
const events: InstrumentationStepAttemptMetadataEvent[] = [];
const hooks = createInstrumentationHooks([
diff --git a/packages/eve/src/harness/ai-sdk-hook-bridge.ts b/packages/eve/src/harness/ai-sdk-hook-bridge.ts
index 7851fb5b6..8aef26bdb 100644
--- a/packages/eve/src/harness/ai-sdk-hook-bridge.ts
+++ b/packages/eve/src/harness/ai-sdk-hook-bridge.ts
@@ -27,6 +27,7 @@ interface AttemptState {
/** False when no provider asked for content, so none is projected at all. */
readonly capturesContent: boolean;
readonly modelKeys: Map<string, string>;
+ readonly runtimeContext?: Readonly<Record<string, unknown>>;
readonly scope: InstrumentationAttemptScope;
readonly toolKeys: Map<string, string>;
operation?: InstrumentationOperationRef;
@@ -39,10 +40,15 @@ export function createAiSdkHookBridge(
scope: InstrumentationAttemptScope,
hooks: InstrumentationHooks,
runInContext: InstrumentationContextRunner = directRunInContext,
+ runtimeContext?: Readonly<Record<string, unknown>>,
): Telemetry {
const state: AttemptState = {
capturesContent: hooks.capturesContent,
modelKeys: new Map(),
+ runtimeContext:
+ runtimeContext !== undefined && Object.keys(runtimeContext).length > 0
+ ? Object.freeze({ ...runtimeContext })
+ : undefined,
scope,
toolKeys: new Map(),
};
@@ -155,6 +161,7 @@ function toStepAttemptStarted(
return Object.freeze({
idempotencyKey: attemptIdempotencyKey(state.scope),
operation: state.operation,
+ runtimeContext: state.runtimeContext,
scope: state.scope,
type: "step.attempt.started",
});
@@ -174,6 +181,7 @@ function toModelCallStarted(
})
: undefined,
model: Object.freeze({ modelId: source.modelId, provider: source.provider }),
+ runtimeContext: state.runtimeContext,
scope: state.scope,
type: "model.call.started",
});
diff --git a/packages/eve/src/harness/instrumentation/lifecycle.ts b/packages/eve/src/harness/instrumentation/lifecycle.ts
index 6297dcbd4..239e64a5a 100644
--- a/packages/eve/src/harness/instrumentation/lifecycle.ts
+++ b/packages/eve/src/harness/instrumentation/lifecycle.ts
@@ -273,6 +273,7 @@ export interface InstrumentationStepAttemptStartedEvent {
readonly type: "step.attempt.started";
readonly idempotencyKey: string;
readonly operation: InstrumentationOperationRef;
+ readonly runtimeContext?: Readonly<Record<string, unknown>>;
readonly scope: InstrumentationAttemptScope;
}
@@ -400,6 +401,7 @@ export interface InstrumentationModelCallStartedEvent {
/** Content. Absent unless this provider declared `capture: "content"`. */
readonly input?: InstrumentationModelInput;
readonly model: InstrumentationModelRef;
+ readonly runtimeContext?: Readonly<Record<string, unknown>>;
readonly scope: InstrumentationAttemptScope;
}
diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.ts
index b84bb3a41..389f50a34 100644
--- a/packages/eve/src/harness/tool-loop.test.ts
+++ b/packages/eve/src/harness/tool-loop.test.ts
@@ -10398,6 +10398,7 @@ describe("createToolLoopHarness", () => {
}),
hooks,
runInContext,
+ {},
);
const bridge = mockCreateAiSdkHookBridge.mock.results[0]!.value;
const agentCall = vi.mocked(ToolLoopAgent).mock.calls[0]?.[0] as {
diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.ts
index 1a7e5b1f7..a764b210f 100644
--- a/packages/eve/src/harness/tool-loop.ts
+++ b/packages/eve/src/harness/tool-loop.ts
@@ -1432,6 +1432,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
attemptScope,
instrumentationHooks,
config.instrumentation?.runInContext,
+ telemetryRuntimeContext,
);
const hooks = buildStepHooks({
diff --git a/packages/eve/src/tracing/agent-otel-provider.test.ts b/packages/eve/src/tracing/agent-otel-provider.test.ts
index 618c32600..6af342eb7 100644
--- a/packages/eve/src/tracing/agent-otel-provider.test.ts
+++ b/packages/eve/src/tracing/agent-otel-provider.test.ts
@@ -93,6 +93,7 @@ async function emitAttempt(input: {
readonly runInContext: InstrumentationContextRunner;
readonly providerMetadata?: Readonly<Record<string, unknown>>;
readonly actionKind?: InstrumentationActionKind;
+ readonly runtimeContext?: Readonly<Record<string, unknown>>;
readonly sessionId: string;
readonly skipModelTerminal?: boolean;
readonly skipToolTerminal?: boolean;
@@ -113,7 +114,12 @@ async function emitAttempt(input: {
await publishTurnStarted(input);
}
- const bridge = createAiSdkHookBridge(scope, input.hooks, input.runInContext);
+ const bridge = createAiSdkHookBridge(
+ scope,
+ input.hooks,
+ input.runInContext,
+ input.runtimeContext,
+ );
Reflect.apply(bridge.onStart!, bridge, [
{
callId: "call-1",
@@ -704,6 +710,61 @@ describe("createAgentOtelInstrumentation", () => {
});
});
+ it("writes merged runtime context onto the step, operation, and chat spans", async () => {
+ const runtime = createRuntime();
+
+ await emitAttempt({
+ hooks: runtime.hooks,
+ runInContext: runtime.runInContext,
+ runtimeContext: {
+ "eve.session.id": "session-1",
+ "posthog.distinct_id": "user-123",
+ nested: { ignored: undefined, team: "platform" },
+ tags: ["a", "b"],
+ },
+ sessionId: "session-1",
+ turnId: "turn-1",
+ turnSequence: 0,
+ });
+ await runtime.provider.forceFlush();
+
+ const spans = runtime.exporter.getFinishedSpans();
+ const step = byName(spans, "agent.step")[0]!;
+ const operation = byName(spans, "ai.streamText")[0]!;
+ const model = byName(spans, "chat claude-test")[0]!;
+ for (const span of [step, operation, model]) {
+ expect(span.attributes).toMatchObject({
+ "ai.settings.context.eve.session.id": "session-1",
+ "ai.settings.context.posthog.distinct_id": "user-123",
+ "ai.settings.context.nested.team": "platform",
+ "ai.settings.context.tags": ["a", "b"],
+ });
+ }
+ });
+
+ it("omits context attributes when no runtime context is merged", async () => {
+ const runtime = createRuntime();
+
+ await emitAttempt({
+ hooks: runtime.hooks,
+ runInContext: runtime.runInContext,
+ sessionId: "session-1",
+ turnId: "turn-1",
+ turnSequence: 0,
+ });
+ await runtime.provider.forceFlush();
+
+ const spans = runtime.exporter.getFinishedSpans();
+ const step = byName(spans, "agent.step")[0]!;
+ const operation = byName(spans, "ai.streamText")[0]!;
+ const model = byName(spans, "chat claude-test")[0]!;
+ for (const span of [step, operation, model]) {
+ expect(
+ Object.keys(span.attributes).some((key) => key.startsWith("ai.settings.context.")),
+ ).toBe(false);
+ }
+ });
+
it("keeps logical ids stable but separates physical redeliveries", async () => {
const first = createRuntime();
const redelivery = createRuntime();
diff --git a/packages/eve/src/tracing/agent-otel-provider.ts b/packages/eve/src/tracing/agent-otel-provider.ts
index e71da5a47..7b87ef11a 100644
--- a/packages/eve/src/tracing/agent-otel-provider.ts
+++ b/packages/eve/src/tracing/agent-otel-provider.ts
@@ -158,6 +158,7 @@ export function createAgentOtelInstrumentation(
"agent.step.index": event.scope.stepIndex,
"agent.turn.id": event.scope.turnId,
"agent.name": event.scope.functionId,
+ ...runtimeContextAttributes(event.runtimeContext),
},
links:
activeSpanContext === undefined || activeSpanContext.traceId === turn.context.traceId
@@ -181,6 +182,7 @@ export function createAgentOtelInstrumentation(
"ai.operation.name": operationName,
"ai.provider.name": event.operation.provider,
"ai.request.model": event.operation.modelId,
+ ...runtimeContextAttributes(event.runtimeContext),
},
},
stepContext,
@@ -304,6 +306,7 @@ export function createAgentOtelInstrumentation(
"gen_ai.operation.name": "chat",
"gen_ai.provider.name": event.model.provider,
"gen_ai.request.model": event.model.modelId,
+ ...runtimeContextAttributes(event.runtimeContext),
},
},
attempt.operation.context,
@@ -566,6 +569,54 @@ function modelSpanName(modelId: string): string {
return `chat ${modelId}`;
}
+type SpanAttributePrimitive = string | number | boolean;
+type SpanAttributeValue = SpanAttributePrimitive | SpanAttributePrimitive[];
+
+/**
+ * Flattens merged runtime context into `ai.settings.context.*` span
+ * attributes, the same key convention the AI SDK's own OTel integration used
+ * for the legacy `step.started` return. Records recurse with dotted keys;
+ * arrays pass through only when homogeneous primitives, matching OTel's
+ * attribute value contract.
+ */
+function runtimeContextAttributes(
+ runtimeContext: Readonly<Record<string, unknown>> | undefined,
+): Record<string, SpanAttributeValue> {
+ const attributes: Record<string, SpanAttributeValue> = {};
+ if (runtimeContext === undefined) return attributes;
+ for (const [key, value] of Object.entries(runtimeContext)) {
+ flattenContextAttribute(attributes, `ai.settings.context.${key}`, value);
+ }
+ return attributes;
+}
+
+function flattenContextAttribute(
+ attributes: Record<string, SpanAttributeValue>,
+ key: string,
+ value: unknown,
+): void {
+ if (value == null) return;
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
+ attributes[key] = value;
+ return;
+ }
+ if (Array.isArray(value)) {
+ const primitives = value.filter(
+ (entry): entry is SpanAttributePrimitive =>
+ typeof entry === "string" || typeof entry === "number" || typeof entry === "boolean",
+ );
+ if (primitives.length !== value.length) return;
+ if (new Set(primitives.map((entry) => typeof entry)).size !== 1) return;
+ attributes[key] = primitives;
+ return;
+ }
+ if (typeof value === "object") {
+ for (const [nestedKey, nestedValue] of Object.entries(value)) {
+ flattenContextAttribute(attributes, `${key}.${nestedKey}`, nestedValue);
+ }
+ }
+}
+
function errorText(error: unknown): unknown {
return error instanceof Error ? error.message : error;
}