Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): isolate provider capture from OTel policy (#2697)

Chad Hietala05b12e3beb66
diff --git a/.changeset/preserve-rejected-trace-bridge.md b/.changeset/preserve-rejected-trace-bridge.md
new file mode 100644
index 000000000..a65801a32
--- /dev/null
+++ b/.changeset/preserve-rejected-trace-bridge.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Instrumentation-provider content delivery now depends only on each provider's `capture` declaration: providers that declare `capture: "content"` receive full event content regardless of channel audience or OpenTelemetry `tracePolicy`. Separately, a `tracePolicy` that drops the eve trace no longer disables AI SDK telemetry: metadata-only AI spans (model, tokens, and timing, without message content) are still emitted into the ambient Workflow trace, and `agent.session` is not emitted.
diff --git a/packages/eve/src/execution/eve-workflow-attributes.ts b/packages/eve/src/execution/eve-workflow-attributes.ts
index 67c5d0384..c8d6d542b 100644
--- a/packages/eve/src/execution/eve-workflow-attributes.ts
+++ b/packages/eve/src/execution/eve-workflow-attributes.ts
@@ -40,7 +40,7 @@ import {
ScheduleIdKey,
type SessionTraceSeed,
} from "#context/keys.js";
-import { shouldCaptureInstrumentationContent } from "#harness/instrumentation/content-policy.js";
+import { shouldCaptureInstrumentationContent } from "#shared/instrumentation-content.js";
import { isSampledTrace } from "#tracing/sampled-trace.js";
import type { EveAttributeValue } from "#runtime/attributes/normalize.js";
import { normalizeChannelAudience } from "#shared/channel-audience.js";
diff --git a/packages/eve/src/harness/ai-sdk-telemetry.test.ts b/packages/eve/src/harness/ai-sdk-telemetry.test.ts
index 6049c90ca..3eccc9e09 100644
--- a/packages/eve/src/harness/ai-sdk-telemetry.test.ts
+++ b/packages/eve/src/harness/ai-sdk-telemetry.test.ts
@@ -1,13 +1,29 @@
+import { OpenTelemetry } from "#compiled/@ai-sdk/otel/index.js";
+import {
+ BasicTracerProvider,
+ InMemorySpanExporter,
+ SimpleSpanProcessor,
+} from "@opentelemetry/sdk-trace-base";
import type { Telemetry } from "ai";
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
-import { getRegisteredTelemetryIntegrations } from "#harness/ai-sdk-telemetry.js";
+const logWarn = vi.hoisted(() => vi.fn());
+vi.mock("#internal/logging.js", () => ({
+ createLogger: () => ({ warn: logWarn }),
+}));
+
+import {
+ ensureOtelIntegration,
+ getRegisteredTelemetryIntegrations,
+ telemetryWithoutErrorContent,
+} from "#harness/ai-sdk-telemetry.js";
describe("getRegisteredTelemetryIntegrations", () => {
const original = globalThis.AI_SDK_TELEMETRY_INTEGRATIONS;
afterEach(() => {
globalThis.AI_SDK_TELEMETRY_INTEGRATIONS = original;
+ logWarn.mockClear();
});
it("is empty when nothing has registered", () => {
@@ -22,4 +38,114 @@ describe("getRegisteredTelemetryIntegrations", () => {
expect(getRegisteredTelemetryIntegrations()).toEqual([first, second]);
});
+
+ it("warns once when eve's integration cannot be identity-matched", () => {
+ const foreign: Telemetry = { onStart() {} };
+ globalThis.AI_SDK_TELEMETRY_INTEGRATIONS = [foreign];
+
+ expect(getRegisteredTelemetryIntegrations({ sanitizeEveOtelErrors: true })).toEqual([foreign]);
+ expect(getRegisteredTelemetryIntegrations({ sanitizeEveOtelErrors: true })).toEqual([foreign]);
+ expect(logWarn).toHaveBeenCalledOnce();
+ });
+
+ it("replaces only eve's OTel integration in error-safe mode", () => {
+ const authored: Telemetry = { onStart() {} };
+ globalThis.AI_SDK_TELEMETRY_INTEGRATIONS = [];
+ ensureOtelIntegration();
+ globalThis.AI_SDK_TELEMETRY_INTEGRATIONS.push(authored);
+
+ const registered = getRegisteredTelemetryIntegrations();
+ const errorSafe = getRegisteredTelemetryIntegrations({ sanitizeEveOtelErrors: true });
+ expect(errorSafe).toHaveLength(2);
+ expect(errorSafe[0]).not.toBe(registered[0]);
+ expect(errorSafe[1]).toBe(authored);
+ });
+});
+
+describe("telemetryWithoutErrorContent", () => {
+ it("replaces operation and tool errors without changing correlation", async () => {
+ const onError = vi.fn();
+ const onToolExecutionEnd = vi.fn();
+ const telemetry = telemetryWithoutErrorContent({ onError, onToolExecutionEnd });
+
+ await telemetry.onError?.({ callId: "call-1", error: new Error("private response body") });
+ await telemetry.onToolExecutionEnd?.({
+ callId: "call-1",
+ messages: [],
+ toolCall: { input: {}, toolCallId: "tool-1", toolName: "weather", type: "tool-call" },
+ toolContext: undefined,
+ toolExecutionMs: 1,
+ toolOutput: {
+ error: new Error("private tool output"),
+ input: {},
+ toolCallId: "tool-1",
+ toolName: "weather",
+ type: "tool-error",
+ },
+ });
+
+ expect(onError.mock.calls[0]?.[0]).toMatchObject({
+ callId: "call-1",
+ error: expect.objectContaining({ message: "AI SDK operation failed" }),
+ });
+ expect(onToolExecutionEnd.mock.calls[0]?.[0]).toMatchObject({
+ callId: "call-1",
+ toolOutput: {
+ error: expect.objectContaining({ message: "AI SDK operation failed" }),
+ type: "tool-error",
+ },
+ });
+ });
+
+ it("keeps sentinel errors out of real OpenTelemetry spans", async () => {
+ const exporter = new InMemorySpanExporter();
+ const provider = new BasicTracerProvider({
+ spanProcessors: [new SimpleSpanProcessor(exporter)],
+ });
+ const telemetry = telemetryWithoutErrorContent(
+ new OpenTelemetry({ tracer: provider.getTracer("test") }),
+ );
+ const callId = "call-1";
+ const error = new Error("SECRET-ERROR-BODY");
+
+ await Reflect.apply(telemetry.onStart!, telemetry, [
+ {
+ callId,
+ messages: [],
+ modelId: "test-model",
+ operationId: "ai.streamText",
+ provider: "test-provider",
+ recordInputs: false,
+ recordOutputs: false,
+ },
+ ]);
+ await Reflect.apply(telemetry.onToolExecutionStart!, telemetry, [
+ {
+ callId,
+ toolCall: { input: {}, toolCallId: "tool-1", toolName: "weather" },
+ },
+ ]);
+ await Reflect.apply(telemetry.onToolExecutionEnd!, telemetry, [
+ {
+ callId,
+ messages: [],
+ toolCall: { input: {}, toolCallId: "tool-1", toolName: "weather" },
+ toolExecutionMs: 1,
+ toolOutput: { error, type: "tool-error" },
+ },
+ ]);
+ await Reflect.apply(telemetry.onError!, telemetry, [{ callId, error }]);
+ await provider.forceFlush();
+
+ const exported = JSON.stringify(
+ exporter.getFinishedSpans().map((span) => ({
+ attributes: span.attributes,
+ events: span.events,
+ status: span.status,
+ })),
+ );
+ expect(exported).not.toContain("SECRET-ERROR-BODY");
+ expect(exported).toContain("AI SDK operation failed");
+ await provider.shutdown();
+ });
});
diff --git a/packages/eve/src/harness/ai-sdk-telemetry.ts b/packages/eve/src/harness/ai-sdk-telemetry.ts
index 02954907f..0e8b17cb4 100644
--- a/packages/eve/src/harness/ai-sdk-telemetry.ts
+++ b/packages/eve/src/harness/ai-sdk-telemetry.ts
@@ -1,7 +1,12 @@
import { OpenTelemetry } from "#compiled/@ai-sdk/otel/index.js";
import { registerTelemetry, type Telemetry } from "ai";
+import { createLogger } from "#internal/logging.js";
+const log = createLogger("harness.ai-sdk-telemetry");
let registered = false;
+let eveOtelIntegration: Telemetry | undefined;
+let errorSafeEveOtelIntegration: Telemetry | undefined;
+let warnedMissingEveOtelIntegration = false;
/**
* Registers the AI SDK OpenTelemetry integration once so that model
@@ -16,7 +21,9 @@ export function ensureOtelIntegration(): void {
return;
}
registered = true;
- registerTelemetry(new OpenTelemetry({ runtimeContext: true }));
+ eveOtelIntegration = new OpenTelemetry({ runtimeContext: true });
+ errorSafeEveOtelIntegration = telemetryWithoutErrorContent(eveOtelIntegration);
+ registerTelemetry(eveOtelIntegration);
}
/**
@@ -27,6 +34,54 @@ export function ensureOtelIntegration(): void {
* adding to them, so anything that passes integrations per call has to carry
* these forward or they stop receiving events.
*/
-export function getRegisteredTelemetryIntegrations(): readonly Telemetry[] {
- return globalThis.AI_SDK_TELEMETRY_INTEGRATIONS ?? [];
+export function getRegisteredTelemetryIntegrations(options?: {
+ readonly sanitizeEveOtelErrors?: boolean;
+}): readonly Telemetry[] {
+ const integrations = globalThis.AI_SDK_TELEMETRY_INTEGRATIONS ?? [];
+ if (options?.sanitizeEveOtelErrors !== true) return integrations;
+ let matched = false;
+ const sanitized = integrations.map((integration) => {
+ if (integration !== eveOtelIntegration || errorSafeEveOtelIntegration === undefined) {
+ return integration;
+ }
+ matched = true;
+ return errorSafeEveOtelIntegration;
+ });
+ if (!matched && !warnedMissingEveOtelIntegration) {
+ warnedMissingEveOtelIntegration = true;
+ log.warn("could not sanitize eve's AI SDK OpenTelemetry integration", {
+ reason:
+ eveOtelIntegration === undefined
+ ? "eve OpenTelemetry integration was not registered"
+ : "registered integration identity did not match",
+ });
+ }
+ return sanitized;
+}
+
+/** @internal */
+export function telemetryWithoutErrorContent(integration: Telemetry): Telemetry {
+ const genericError = (): Error => new Error("AI SDK operation failed");
+ return new Proxy(integration, {
+ get(target, property) {
+ if (property === "onError" && target.onError !== undefined) {
+ return (event: unknown) =>
+ target.onError!(
+ typeof event === "object" && event !== null
+ ? { ...event, error: genericError() }
+ : genericError(),
+ );
+ }
+ if (property === "onToolExecutionEnd" && target.onToolExecutionEnd !== undefined) {
+ return (event: Parameters<NonNullable<Telemetry["onToolExecutionEnd"]>>[0]) =>
+ target.onToolExecutionEnd!(
+ event.toolOutput.type === "tool-error"
+ ? { ...event, toolOutput: { ...event.toolOutput, error: genericError() } }
+ : event,
+ );
+ }
+ const value = Reflect.get(target, property) as unknown;
+ return typeof value === "function" ? value.bind(target) : value;
+ },
+ });
}
diff --git a/packages/eve/src/harness/channel-delivery-instrumentation.test.ts b/packages/eve/src/harness/channel-delivery-instrumentation.test.ts
index 7405323b0..67f34b946 100644
--- a/packages/eve/src/harness/channel-delivery-instrumentation.test.ts
+++ b/packages/eve/src/harness/channel-delivery-instrumentation.test.ts
@@ -84,7 +84,7 @@ describe("channel delivery instrumentation", () => {
expect(metadata[0]).toMatchObject({ input: undefined });
});
- it("keeps a private delivery redacted inside a content-enabled session", async () => {
+ it("keeps provider content independent from the OTel audience ceiling", async () => {
const events: InstrumentationEvent[] = [];
const hooks = createInstrumentationHooks([
{
@@ -132,6 +132,6 @@ describe("channel delivery instrumentation", () => {
}),
);
- expect(events[0]).toMatchObject({ input: undefined });
+ expect(events[0]).toMatchObject({ input: { message: "secret" } });
});
});
diff --git a/packages/eve/src/harness/channel-delivery-instrumentation.ts b/packages/eve/src/harness/channel-delivery-instrumentation.ts
index 2b7b24197..4de3835ab 100644
--- a/packages/eve/src/harness/channel-delivery-instrumentation.ts
+++ b/packages/eve/src/harness/channel-delivery-instrumentation.ts
@@ -13,10 +13,6 @@ import type {
InstrumentationHooks,
} from "#harness/instrumentation/lifecycle.js";
import { channelDeliveryIdempotencyKey } from "#harness/instrumentation/lifecycle.js";
-import {
- instrumentationHooksForAudience,
- instrumentationHooksForDecision,
-} from "#harness/instrumentation/content-policy.js";
import { normalizeChannelAudience } from "#shared/channel-audience.js";
interface ChannelDeliveryStartInstrumentation {
@@ -54,12 +50,7 @@ export async function instrumentChannelDelivery(
const type =
`channel.delivery.${input.outcome}` as InstrumentationChannelDeliveryTerminalEvent["type"];
for (const item of active) {
- const hooks = hooksForContext(
- input.ctx,
- input.hooks,
- normalizeChannelAudience(item.delivery.channelAudience),
- );
- await hooks?.publish({
+ await input.hooks.publish({
agentName: item.agentName,
delivery: item.delivery,
error: input.error,
@@ -83,7 +74,7 @@ export async function instrumentChannelDelivery(
const channelAudience = normalizeChannelAudience(
input.ctx.get(ChannelInstrumentationKey)?.metadata.audience,
);
- const hooks = hooksForContext(input.ctx, input.hooks, channelAudience);
+ const hooks = input.hooks;
for (const metadata of input.delivery.deliveryMetadata) {
const payload = input.delivery.payloads[metadata.payloadIndex];
const delivery = {
@@ -120,17 +111,6 @@ export async function instrumentChannelDelivery(
if (active.length > 0) input.ctx.set(ActiveChannelDeliveriesKey, active);
}
-function hooksForContext(
- ctx: AlsContext,
- hooks: InstrumentationHooks,
- audience: ReturnType<typeof normalizeChannelAudience>,
-): InstrumentationHooks | undefined {
- const decision = ctx.get(SessionTraceSeedKey)?.decision;
- return decision === undefined
- ? instrumentationHooksForAudience(hooks, audience)
- : instrumentationHooksForDecision(hooks, decision, audience);
-}
-
function projectDeliveryInput(payload: DeliverPayload) {
const projected: {
context?: DeliverPayload["context"];
diff --git a/packages/eve/src/harness/instrumentation/content-policy.test.ts b/packages/eve/src/harness/instrumentation/content-policy.test.ts
index 42f30e46f..e266e7db9 100644
--- a/packages/eve/src/harness/instrumentation/content-policy.test.ts
+++ b/packages/eve/src/harness/instrumentation/content-policy.test.ts
@@ -1,129 +1,80 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
+import { describe, expect, it } from "vitest";
-import {
- instrumentationHooksForAudience,
- instrumentationHooksForDecision,
- shouldCaptureInstrumentationContent,
-} from "#harness/instrumentation/content-policy.js";
-import type { InstrumentationHooks } from "#harness/instrumentation/lifecycle.js";
+import { instrumentationEventForTraceDecision } from "#harness/instrumentation/content-policy.js";
+import type { InstrumentationEvent } from "#harness/instrumentation/lifecycle.js";
-afterEach(() => {
- vi.unstubAllEnvs();
-});
+const event: InstrumentationEvent = {
+ idempotencyKey: "model:session-1:turn-1:0:0:0",
+ input: { instructions: "private prompt", messages: [] },
+ model: { modelId: "test", provider: "test" },
+ scope: {
+ attemptId: "session-1:turn-1:0:0",
+ attemptIndex: 0,
+ sessionId: "session-1",
+ stepIndex: 0,
+ turnId: "turn-1",
+ },
+ type: "model.call.started",
+};
-describe("instrumentation content policy", () => {
- it("captures only public content in hosted workers", () => {
- expect(shouldCaptureInstrumentationContent("public")).toBe(true);
- expect(shouldCaptureInstrumentationContent("private")).toBe(false);
- expect(shouldCaptureInstrumentationContent("unknown")).toBe(false);
+describe("instrumentationEventForTraceDecision", () => {
+ it("applies directional OTel content decisions", () => {
+ expect(
+ instrumentationEventForTraceDecision(
+ event,
+ { action: "record", recordInputs: false, recordOutputs: true },
+ "public",
+ ),
+ ).toMatchObject({ input: undefined });
});
- it("keeps the local unknown-audience exception without admitting private content", () => {
- vi.stubEnv("EVE_DEV", "1");
-
- expect(shouldCaptureInstrumentationContent("public")).toBe(true);
- expect(shouldCaptureInstrumentationContent("private")).toBe(false);
- expect(shouldCaptureInstrumentationContent("unknown")).toBe(true);
+ it("classifies approval requests as outputs and responses as inputs", () => {
+ const decision = { action: "record", recordInputs: false, recordOutputs: true } as const;
+ expect(
+ instrumentationEventForTraceDecision(
+ {
+ action: { callId: "call-1", name: "weather" },
+ idempotencyKey: "input-1",
+ kind: "tool-approval",
+ request: { prompt: "Approve weather?" },
+ requestId: "request-1",
+ scope: event.scope,
+ type: "input.requested",
+ },
+ decision,
+ "public",
+ ),
+ ).toMatchObject({ request: { prompt: "Approve weather?" } });
+ expect(
+ instrumentationEventForTraceDecision(
+ {
+ idempotencyKey: "input-1",
+ kind: "tool-approval",
+ outcome: "approved",
+ requestId: "request-1",
+ response: { optionId: "approve" },
+ scope: event.scope,
+ type: "input.resolved",
+ },
+ decision,
+ "public",
+ ),
+ ).toMatchObject({ response: undefined });
});
- it("strips content before publishing to hosted providers", async () => {
- const publish = vi.fn();
- const hooks: InstrumentationHooks = { capturesContent: true, publish };
- const restricted = instrumentationHooksForAudience(hooks, "private");
-
- await restricted?.publish({
- callId: "call-1",
- idempotencyKey: "action-1",
- input: { secret: "value" },
- kind: "tool-call",
- name: "lookup",
- scope: {
- attemptId: "attempt-1",
- attemptIndex: 0,
- sessionId: "session-1",
- stepIndex: 0,
- turnId: "turn-1",
- },
- type: "action.started",
- });
-
- expect(restricted?.capturesContent).toBe(false);
- expect(publish).toHaveBeenCalledWith(expect.objectContaining({ input: undefined }));
+ it("applies the OTel audience ceiling", () => {
+ expect(
+ instrumentationEventForTraceDecision(
+ event,
+ { action: "record", recordInputs: true, recordOutputs: true },
+ "private",
+ ),
+ ).toMatchObject({ input: undefined });
});
- it("applies directional trace capture before publishing", async () => {
- const publish = vi.fn();
- const hooks: InstrumentationHooks = { capturesContent: true, publish };
- const restricted = instrumentationHooksForDecision(
- hooks,
- {
- action: "record",
- recordInputs: true,
- recordOutputs: false,
- },
- "public",
- );
-
- await restricted?.publish({
- callId: "call-1",
- idempotencyKey: "action-1",
- input: { secret: "input" },
- kind: "tool-call",
- name: "lookup",
- scope: {
- attemptId: "attempt-1",
- attemptIndex: 0,
- sessionId: "session-1",
- stepIndex: 0,
- turnId: "turn-1",
- },
- type: "action.started",
- });
- await restricted?.publish({
- idempotencyKey: "action-1",
- outcome: "completed",
- output: { output: { secret: "output" }, type: "result" },
- scope: {
- attemptId: "attempt-1",
- attemptIndex: 0,
- sessionId: "session-1",
- stepIndex: 0,
- turnId: "turn-1",
- },
- type: "action.completed",
- });
-
- expect(restricted?.capturesContent).toBe(true);
- expect(publish.mock.calls[0]?.[0]).toEqual(
- expect.objectContaining({ input: { secret: "input" } }),
- );
- expect(publish.mock.calls[1]?.[0]).toEqual(
- expect.objectContaining({ output: { type: "result" } }),
+ it("removes content from dropped OTel traces", () => {
+ expect(instrumentationEventForTraceDecision(event, { action: "drop" }, "public")).toMatchObject(
+ { input: undefined },
);
});
-
- it("keeps lifecycle delivery when the trace decision drops", async () => {
- const publish = vi.fn();
- const hooks: InstrumentationHooks = { capturesContent: true, publish };
- const restricted = instrumentationHooksForDecision(hooks, { action: "drop" }, "private");
-
- await restricted?.publish({
- callId: "call-1",
- idempotencyKey: "action-1",
- input: { secret: "value" },
- kind: "tool-call",
- name: "lookup",
- scope: {
- attemptId: "attempt-1",
- attemptIndex: 0,
- sessionId: "session-1",
- stepIndex: 0,
- turnId: "turn-1",
- },
- type: "action.started",
- });
-
- expect(restricted).toBeDefined();
- expect(publish).toHaveBeenCalledWith(expect.objectContaining({ input: undefined }));
- });
});
diff --git a/packages/eve/src/harness/instrumentation/content-policy.ts b/packages/eve/src/harness/instrumentation/content-policy.ts
index 346535306..4f55c2b19 100644
--- a/packages/eve/src/harness/instrumentation/content-policy.ts
+++ b/packages/eve/src/harness/instrumentation/content-policy.ts
@@ -1,52 +1,20 @@
-import type { InstrumentationHooks } from "#harness/instrumentation/lifecycle.js";
import {
withInstrumentationDecision,
withoutInstrumentationContent,
} from "#harness/instrumentation/content.js";
+import type { InstrumentationEvent } from "#harness/instrumentation/lifecycle.js";
import type { ChannelAudience } from "#shared/channel-audience.js";
-import {
- applyAudienceCeiling,
- shouldCaptureInstrumentationContent,
-} from "#shared/instrumentation-content.js";
+import { applyAudienceCeiling } from "#shared/instrumentation-content.js";
import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";
-export { shouldCaptureInstrumentationContent } from "#shared/instrumentation-content.js";
-export function instrumentationHooksForDecision(
- hooks: InstrumentationHooks | undefined,
+/** Applies OpenTelemetry's trace content ceiling to one OTel provider event. */
+export function instrumentationEventForTraceDecision(
+ event: InstrumentationEvent,
decision: InstrumentationDecision,
audience: ChannelAudience,
-): InstrumentationHooks | undefined {
- if (decision.action === "drop") return instrumentationHooksForAudience(hooks, audience);
+): InstrumentationEvent {
const effective = applyAudienceCeiling(decision, audience);
- if (
- effective.action === "drop" ||
- hooks === undefined ||
- !hooks.capturesContent ||
- (effective.recordInputs && effective.recordOutputs)
- ) {
- return hooks;
- }
- return {
- capturesContent: effective.recordInputs || effective.recordOutputs,
- publish: (event) => hooks.publish(withInstrumentationDecision(event, effective)),
- };
-}
-
-/** Applies the audience ceiling before any content-capable provider sees an event. */
-export function instrumentationHooksForAudience(
- hooks: InstrumentationHooks | undefined,
- audience: ChannelAudience,
-): InstrumentationHooks | undefined {
- if (
- hooks === undefined ||
- !hooks.capturesContent ||
- shouldCaptureInstrumentationContent(audience)
- ) {
- return hooks;
- }
-
- return {
- capturesContent: false,
- publish: (event) => hooks.publish(withoutInstrumentationContent(event)),
- };
+ return effective.action === "drop"
+ ? withoutInstrumentationContent(event)
+ : withInstrumentationDecision(event, effective);
}
diff --git a/packages/eve/src/harness/instrumentation/dispatch.ts b/packages/eve/src/harness/instrumentation/dispatch.ts
index 3cd405a88..c85a3d129 100644
--- a/packages/eve/src/harness/instrumentation/dispatch.ts
+++ b/packages/eve/src/harness/instrumentation/dispatch.ts
@@ -182,8 +182,15 @@ async function dispatchToProvider(
const state = instrumentationStateSlot(stateNamespace, event.idempotencyKey, owner);
try {
const settled = await withTimeout(
- () =>
- (handler as InstrumentationEventHandler<InstrumentationEvent>)(visibleEvent(), { state }),
+ async () => {
+ const eventForProvider = visibleEvent();
+ await (handler as InstrumentationEventHandler<InstrumentationEvent>)(
+ provider.projectEvent === undefined
+ ? eventForProvider
+ : await provider.projectEvent(eventForProvider),
+ { state },
+ );
+ },
handlerTimeoutMs,
() => {
state.revoke();
diff --git a/packages/eve/src/harness/instrumentation/lifecycle.ts b/packages/eve/src/harness/instrumentation/lifecycle.ts
index 671f6e1f0..e7901942d 100644
--- a/packages/eve/src/harness/instrumentation/lifecycle.ts
+++ b/packages/eve/src/harness/instrumentation/lifecycle.ts
@@ -2,6 +2,7 @@ import { createInstrumentationDispatcher } from "#harness/instrumentation/dispat
import type { InstrumentationStateSlot } from "#harness/instrumentation/state.js";
import type { RuntimeTraceContext } from "#protocol/message.js";
import type { ChannelAudience } from "#shared/channel-audience.js";
+import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";
/**
* Stable eve identity for one actual model attempt.
@@ -113,8 +114,8 @@ export type InstrumentationActionOutput =
* some provider asked for it, and a provider that did not ask never receives
* it — which is the same guarantee a destination that declines content gets,
* one layer lower and without an OpenTelemetry pipeline to route it through.
- * Runtime audience policy can still lower hosted private or unknown events to
- * metadata before this provider-level projection.
+ * OpenTelemetry trace policy is applied only inside the OTel provider and does
+ * not narrow this provider-level projection.
*/
export type InstrumentationCapture = "content" | "metadata";
@@ -187,7 +188,7 @@ interface InstrumentationChannelDeliveryScope {
readonly rootSessionId: string;
readonly sequence?: number;
readonly sessionId: string;
- readonly traceSeed?: InstrumentationTraceContext;
+ readonly traceSeed?: InstrumentationTraceSeed;
readonly turnId?: string;
}
@@ -293,10 +294,13 @@ export interface InstrumentationSessionStartedEvent {
readonly parentTraceContext?: InstrumentationTraceContext;
readonly rootSessionId: string;
readonly sessionId: string;
- readonly traceSeed?: InstrumentationTraceContext;
+ readonly traceSeed?: InstrumentationTraceSeed;
}
export type InstrumentationTraceContext = RuntimeTraceContext;
+export interface InstrumentationTraceSeed extends InstrumentationTraceContext {
+ readonly decision?: InstrumentationDecision;
+}
/**
* Which tool call dispatched a subagent child. The trace structure alone
@@ -536,6 +540,10 @@ export interface InstrumentationProviderDefinition {
readonly name: string;
/** Durable state identity, separate from the human-readable log name. */
readonly stateNamespace?: string;
+ /** Internal provider-specific projection applied after capture filtering. */
+ readonly projectEvent?: (
+ event: InstrumentationEvent,
+ ) => InstrumentationEvent | PromiseLike<InstrumentationEvent>;
/** Defaults to `"metadata"`. See {@link InstrumentationCapture}. */
readonly capture?: InstrumentationCapture;
readonly events?: {
diff --git a/packages/eve/src/harness/instrumentation/providers-otel-policy.test.ts b/packages/eve/src/harness/instrumentation/providers-otel-policy.test.ts
new file mode 100644
index 000000000..f1d693753
--- /dev/null
+++ b/packages/eve/src/harness/instrumentation/providers-otel-policy.test.ts
@@ -0,0 +1,82 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { ContextContainer, contextStorage } from "#context/container.js";
+import {
+ finalizeInstrumentationProviders,
+ registerInstrumentationProvider,
+} from "#harness/instrumentation/providers.js";
+import { defineInstrumentation } from "#public/instrumentation/index.js";
+import { otel, type TracePolicyDecision } from "#public/instrumentation/otel.js";
+
+vi.mock("#tracing/otel-registration.js", () => ({
+ registerOtelPipeline: () => ({
+ forceFlush: async () => undefined,
+ idGenerator: {
+ deriveSpanId: () => "2".repeat(16),
+ generateTraceId: () => "1".repeat(32),
+ withSpanId: (_spanId: string, run: () => unknown) => run(),
+ withTraceId: (_traceId: string, run: () => unknown) => run(),
+ },
+ shutdown: async () => undefined,
+ }),
+}));
+
+const REGISTRY_GLOBAL_KEY = Symbol.for("eve.harness-instrumentation-providers");
+const RUNTIME_GLOBAL_KEY = Symbol.for("eve.instrumentation-runtime");
+
+describe("otel and authored provider composition", () => {
+ beforeEach(() => {
+ delete (globalThis as Record<symbol, unknown>)[REGISTRY_GLOBAL_KEY];
+ delete (globalThis as Record<symbol, unknown>)[RUNTIME_GLOBAL_KEY];
+ });
+
+ it.each([
+ ["redacted", { emit: true, recordInputs: false, recordOutputs: false }],
+ ["dropped", { emit: false }],
+ ] as const)(
+ "keeps content-provider events independent from a %s OTel trace",
+ async (_name, policy) => {
+ const modelStarted = vi.fn();
+ await registerInstrumentationProvider({
+ agentName: "weather-agent",
+ slot: "otel",
+ value: otel({ tracePolicy: () => policy as TracePolicyDecision }),
+ });
+ await registerInstrumentationProvider({
+ agentName: "weather-agent",
+ slot: "rows",
+ value: defineInstrumentation({
+ capture: "content",
+ events: { "model.call.started": modelStarted },
+ }),
+ });
+ const runtime = finalizeInstrumentationProviders({ serviceName: "weather-agent" });
+
+ await contextStorage.run(new ContextContainer(), () =>
+ runtime.hooks.publish({
+ idempotencyKey: "model:session-1:turn-1:0:0:0",
+ input: {
+ instructions: "private instructions",
+ messages: [{ content: "private user message", role: "user" }],
+ },
+ model: { modelId: "test-model", provider: "test-provider" },
+ scope: {
+ attemptId: "session-1:turn-1:0:0",
+ attemptIndex: 0,
+ channelAudience: "private",
+ sessionId: "session-1",
+ stepIndex: 0,
+ turnId: "turn-1",
+ },
+ type: "model.call.started",
+ }),
+ );
+
+ expect(modelStarted).toHaveBeenCalledOnce();
+ expect(modelStarted.mock.calls[0]?.[0].input).toEqual({
+ instructions: "private instructions",
+ messages: [{ content: "private user message", role: "user" }],
+ });
+ },
+ );
+});
diff --git a/packages/eve/src/harness/instrumentation/runtime-context.ts b/packages/eve/src/harness/instrumentation/runtime-context.ts
index 7bb16d59e..054558b75 100644
--- a/packages/eve/src/harness/instrumentation/runtime-context.ts
+++ b/packages/eve/src/harness/instrumentation/runtime-context.ts
@@ -12,7 +12,7 @@ import {
import type { HarnessEmissionState } from "#harness/emission.js";
import type { HarnessSession } from "#harness/types.js";
import type { RuntimeContextResolver } from "#tracing/otel-declaration.js";
-import { shouldCaptureInstrumentationContent } from "#harness/instrumentation/content-policy.js";
+import { shouldCaptureInstrumentationContent } from "#shared/instrumentation-content.js";
import {
normalizeInstrumentationChannelKind,
resolveInstrumentationProjection,
diff --git a/packages/eve/src/harness/instrumentation/runtime.ts b/packages/eve/src/harness/instrumentation/runtime.ts
index 4871c6c7d..4c45c879d 100644
--- a/packages/eve/src/harness/instrumentation/runtime.ts
+++ b/packages/eve/src/harness/instrumentation/runtime.ts
@@ -2,7 +2,7 @@ import type {
InstrumentationContextRunner,
InstrumentationHooks,
InstrumentationSessionStartedEvent,
- InstrumentationTraceContext,
+ InstrumentationTraceSeed,
InstrumentationTurnStartedEvent,
} from "#harness/instrumentation/lifecycle.js";
import type { AgentSpanIdGenerator } from "#tracing/agent-span-id-generator.js";
@@ -17,10 +17,10 @@ export interface InstrumentationRuntime {
readonly idGenerator?: AgentSpanIdGenerator;
readonly prepareSessionTrace?: (
event: InstrumentationSessionStartedEvent,
- ) => Promise<InstrumentationTraceContext>;
+ ) => Promise<InstrumentationTraceSeed>;
readonly prepareTurnTrace?: (
event: InstrumentationTurnStartedEvent,
- ) => Promise<InstrumentationTraceContext>;
+ ) => Promise<InstrumentationTraceSeed>;
otelSettings: OtelHarnessSettings | undefined;
readonly runtimeContextResolvers?: readonly RuntimeContextResolver[];
readonly runInContext: InstrumentationContextRunner;
diff --git a/packages/eve/src/harness/prepare-trace-context.test.ts b/packages/eve/src/harness/prepare-trace-context.test.ts
new file mode 100644
index 000000000..0c46496c8
--- /dev/null
+++ b/packages/eve/src/harness/prepare-trace-context.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from "vitest";
+
+import { ContextContainer, contextStorage } from "#context/container.js";
+import { SessionTraceSeedKey } from "#context/keys.js";
+import { createInstrumentationHooks } from "#harness/instrumentation/lifecycle.js";
+import { prepareTurnTraceContext } from "#harness/prepare-trace-context.js";
+
+describe("prepareTurnTraceContext", () => {
+ it("backfills a persisted trace decision for pre-seed workflow contexts", async () => {
+ const context = new ContextContainer();
+ const seed = {
+ decision: { action: "record", recordInputs: false, recordOutputs: true } as const,
+ spanId: "2".repeat(16),
+ traceFlags: 1,
+ traceId: "1".repeat(32),
+ };
+
+ await contextStorage.run(context, () =>
+ prepareTurnTraceContext({
+ instrumentation: {
+ hooks: createInstrumentationHooks([]),
+ prepareSessionTrace: async () => seed,
+ runInContext: (_operation, execute) => execute(),
+ },
+ rootSessionId: "session-1",
+ sequence: 0,
+ sessionId: "session-1",
+ sessionStarted: false,
+ turnId: "turn-1",
+ }),
+ );
+
+ expect(context.get(SessionTraceSeedKey)).toEqual(seed);
+ });
+});
diff --git a/packages/eve/src/harness/prepare-trace-context.ts b/packages/eve/src/harness/prepare-trace-context.ts
index cfbd29578..7d8f93b2e 100644
--- a/packages/eve/src/harness/prepare-trace-context.ts
+++ b/packages/eve/src/harness/prepare-trace-context.ts
@@ -1,13 +1,14 @@
import { createLogger, formatError } from "#internal/logging.js";
+import { contextStorage } from "#context/container.js";
import type { RuntimeTraceContext } from "#protocol/message.js";
import type {
InstrumentationParentLineage,
- InstrumentationTraceContext,
+ InstrumentationTraceSeed,
} from "#harness/instrumentation/lifecycle.js";
import { sessionIdempotencyKey, turnIdempotencyKey } from "#harness/instrumentation/lifecycle.js";
import type { HarnessInstrumentation } from "#harness/instrumentation/runtime.js";
import type { ChannelAudience } from "#shared/channel-audience.js";
-import type { SessionTraceSeed } from "#context/keys.js";
+import { SessionTraceSeedKey, type SessionTraceSeed } from "#context/keys.js";
const log = createLogger("harness.prepare-trace-context");
@@ -18,7 +19,7 @@ export async function prepareTurnTraceContext(input: {
readonly channelType?: string;
readonly instrumentation?: HarnessInstrumentation;
readonly parentLineage?: InstrumentationParentLineage;
- readonly parentTraceContext?: InstrumentationTraceContext;
+ readonly parentTraceContext?: InstrumentationTraceSeed;
readonly rootSessionId: string;
readonly sequence: number;
readonly sessionId: string;
@@ -27,7 +28,7 @@ export async function prepareTurnTraceContext(input: {
readonly traceSeed?: SessionTraceSeed;
readonly turnId: string;
}): Promise<RuntimeTraceContext | undefined> {
- let prepared: RuntimeTraceContext | undefined;
+ let prepared: InstrumentationTraceSeed | undefined;
if (!input.sessionStarted && input.instrumentation?.prepareSessionTrace !== undefined) {
try {
@@ -64,6 +65,10 @@ export async function prepareTurnTraceContext(input: {
}
}
+ if (input.traceSeed === undefined && prepared?.decision !== undefined) {
+ contextStorage.getStore()?.set(SessionTraceSeedKey, prepared);
+ }
+
return input.traceContext ?? prepared;
}
diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.ts
index 87d09779b..59fa8df3b 100644
--- a/packages/eve/src/harness/tool-loop.test.ts
+++ b/packages/eve/src/harness/tool-loop.test.ts
@@ -106,7 +106,9 @@ const {
registeredOtelIntegration,
} = vi.hoisted(() => ({
mockCreateAiSdkHookBridge: vi.fn((..._args: unknown[]) => ({ onStart: vi.fn() })),
- mockGetRegisteredTelemetryIntegrations: vi.fn((): unknown[] => []),
+ mockGetRegisteredTelemetryIntegrations: vi.fn(
+ (_options?: { readonly sanitizeEveOtelErrors?: boolean }): unknown[] => [],
+ ),
registeredAuthorIntegration: { onStart: vi.fn() },
registeredOtelIntegration: { onStart: vi.fn() },
}));
@@ -117,7 +119,8 @@ vi.mock("./ai-sdk-hook-bridge.js", () => ({
vi.mock("./ai-sdk-telemetry.js", () => ({
ensureOtelIntegration: vi.fn(),
- getRegisteredTelemetryIntegrations: () => mockGetRegisteredTelemetryIntegrations(),
+ getRegisteredTelemetryIntegrations: (options?: { readonly sanitizeEveOtelErrors?: boolean }) =>
+ mockGetRegisteredTelemetryIntegrations(options),
}));
const mockGetInstrumentationConfig = vi.fn().mockReturnValue(undefined);
@@ -10938,7 +10941,7 @@ describe("createToolLoopHarness", () => {
});
describe("telemetry metadata", () => {
- it("does not enable AI SDK telemetry when the trace policy rejects the trace", async () => {
+ it("keeps integrations metadata-only on a rejected trace", async () => {
setupMockAgent({
finishReason: "stop",
response: { messages: [{ content: "Hello!", role: "assistant" }] },
@@ -10951,18 +10954,72 @@ describe("createToolLoopHarness", () => {
recordOutputs: true,
tracePolicy: () => false,
});
- const runStep = createToolLoopHarness(createTestConfig());
+ mockGetRegisteredTelemetryIntegrations.mockReturnValue([
+ registeredOtelIntegration,
+ registeredAuthorIntegration,
+ ]);
+ const runStep = createToolLoopHarness(
+ createTestConfig("conversation", undefined, {
+ instrumentation: {
+ hooks: createInstrumentationHooks([]),
+ runInContext: (_operation, execute) => execute(),
+ },
+ }),
+ );
await runStep(createTestSession(), { message: "private" });
const agentCall = vi.mocked(ToolLoopAgent).mock.calls[0]?.[0] as {
- telemetry?: unknown;
+ telemetry?: {
+ integrations?: unknown[];
+ recordInputs?: boolean;
+ recordOutputs?: boolean;
+ };
};
- expect(agentCall.telemetry).toBeUndefined();
- expect(mockCreateAiSdkHookBridge).not.toHaveBeenCalled();
+ expect(agentCall.telemetry).toMatchObject({
+ integrations: [
+ mockCreateAiSdkHookBridge.mock.results[0]!.value,
+ registeredOtelIntegration,
+ registeredAuthorIntegration,
+ ],
+ recordInputs: false,
+ recordOutputs: false,
+ });
+ expect(mockGetRegisteredTelemetryIntegrations).toHaveBeenCalledWith({
+ sanitizeEveOtelErrors: true,
+ });
+ });
+
+ it("keeps compaction telemetry metadata-only on a rejected trace", async () => {
+ vi.mocked(shouldCompact).mockReturnValueOnce(true);
+ vi.mocked(compactMessages).mockResolvedValueOnce([
+ { content: "Summary of our conversation so far:", role: "user" },
+ { content: "summary", role: "assistant" },
+ ]);
+ setupMockAgent({
+ finishReason: "stop",
+ response: { messages: [{ content: "Hello!", role: "assistant" }] },
+ text: "Hello!",
+ toolCalls: [],
+ toolResults: [],
+ });
+ declareTelemetry({
+ recordInputs: true,
+ recordOutputs: true,
+ tracePolicy: () => false,
+ });
+ const runStep = createToolLoopHarness(createTestConfig());
+
+ await runStep(createTestSession(), { message: "private" });
+
+ expect(vi.mocked(compactMessages).mock.calls[0]?.[4]).toMatchObject({
+ isEnabled: true,
+ recordInputs: false,
+ recordOutputs: false,
+ });
});
- it("keeps lifecycle providers active when the trace policy rejects the trace", async () => {
+ it("keeps the content-capable lifecycle bridge active on a rejected trace", async () => {
setupMockAgent({
finishReason: "stop",
response: { messages: [{ content: "Hello!", role: "assistant" }] },
@@ -10973,21 +11030,65 @@ describe("createToolLoopHarness", () => {
declareTelemetry({ tracePolicy: () => false });
const attemptCompleted = vi.fn();
const hooks = createInstrumentationHooks([
- { events: { "step.attempt.completed": attemptCompleted }, name: "analytics" },
+ {
+ capture: "content",
+ events: { "step.attempt.completed": attemptCompleted },
+ name: "analytics",
+ },
]);
const runStep = createToolLoopHarness(
createTestConfig("conversation", undefined, {
instrumentation: { hooks, runInContext: (_operation, execute) => execute() },
}),
);
+ const ctx = new ContextContainer();
+ ctx.set(ChannelInstrumentationKey, {
+ kind: "channel:private",
+ metadata: { audience: "private" },
+ });
- await runStep(createTestSession(), { message: "private" });
+ await contextStorage.run(ctx, () => runStep(createTestSession(), { message: "private" }));
expect(attemptCompleted).toHaveBeenCalledOnce();
+ expect(mockCreateAiSdkHookBridge.mock.calls[0]?.[1]).toBe(hooks);
const agentCall = vi.mocked(ToolLoopAgent).mock.calls[0]?.[0] as {
- telemetry?: unknown;
+ telemetry?: { integrations?: unknown[] };
};
- expect(agentCall.telemetry).toBeUndefined();
+ expect(agentCall.telemetry?.integrations).toEqual([
+ mockCreateAiSdkHookBridge.mock.results[0]!.value,
+ ]);
+ });
+
+ it("keeps provider content independent from emitted OTel content policy", async () => {
+ setupMockAgent({
+ finishReason: "stop",
+ response: { messages: [{ content: "Hello!", role: "assistant" }] },
+ text: "Hello!",
+ toolCalls: [],
+ toolResults: [],
+ });
+ declareTelemetry({
+ recordInputs: true,
+ recordOutputs: true,
+ tracePolicy: () => ({ emit: true, recordInputs: false, recordOutputs: false }),
+ });
+ const hooks = createInstrumentationHooks([{ capture: "content", name: "analytics" }]);
+ const runStep = createToolLoopHarness(
+ createTestConfig("conversation", undefined, {
+ instrumentation: { hooks, runInContext: (_operation, execute) => execute() },
+ }),
+ );
+
+ await runStep(createTestSession(), { message: "private" });
+
+ expect(mockCreateAiSdkHookBridge.mock.calls[0]?.[1]).toBe(hooks);
+ const agentCall = vi.mocked(ToolLoopAgent).mock.calls[0]?.[0] as {
+ telemetry?: { recordInputs?: boolean; recordOutputs?: boolean };
+ };
+ expect(agentCall.telemetry).toMatchObject({
+ recordInputs: false,
+ recordOutputs: false,
+ });
});
it.each([
@@ -11012,7 +11113,14 @@ describe("createToolLoopHarness", () => {
recordOutputs: outputs,
}),
});
- const runStep = createToolLoopHarness(createTestConfig());
+ const runStep = createToolLoopHarness(
+ createTestConfig("conversation", undefined, {
+ instrumentation: {
+ hooks: createInstrumentationHooks([]),
+ runInContext: (_operation, execute) => execute(),
+ },
+ }),
+ );
const ctx = new ContextContainer();
ctx.set(ChannelInstrumentationKey, {
kind: "channel:public",
@@ -11028,6 +11136,9 @@ describe("createToolLoopHarness", () => {
recordInputs: inputs,
recordOutputs: outputs,
});
+ expect(mockGetRegisteredTelemetryIntegrations).toHaveBeenCalledWith({
+ sanitizeEveOtelErrors: !(inputs && outputs),
+ });
});
it("lets destination capture settings narrow an explicit content decision", async () => {
@@ -11063,6 +11174,9 @@ describe("createToolLoopHarness", () => {
recordInputs: false,
recordOutputs: true,
});
+ expect(mockGetRegisteredTelemetryIntegrations).toHaveBeenCalledWith({
+ sanitizeEveOtelErrors: true,
+ });
});
it("reuses the persisted rejected trace decision", async () => {
@@ -11075,7 +11189,14 @@ describe("createToolLoopHarness", () => {
});
const tracePolicy = vi.fn(() => true);
declareTelemetry({ recordInputs: true, recordOutputs: true, tracePolicy });
- const runStep = createToolLoopHarness(createTestConfig());
+ const runStep = createToolLoopHarness(
+ createTestConfig("conversation", undefined, {
+ instrumentation: {
+ hooks: createInstrumentationHooks([]),
+ runInContext: (_operation, execute) => execute(),
+ },
+ }),
+ );
const ctx = new ContextContainer();
ctx.set(SessionTraceSeedKey, {
decision: { action: "drop" },
@@ -11087,9 +11208,11 @@ describe("createToolLoopHarness", () => {
await contextStorage.run(ctx, () => runStep(createTestSession(), { message: "private" }));
const agentCall = vi.mocked(ToolLoopAgent).mock.calls[0]?.[0] as {
- telemetry?: unknown;
+ telemetry?: { integrations?: unknown[] };
};
- expect(agentCall.telemetry).toBeUndefined();
+ expect(agentCall.telemetry?.integrations).toEqual([
+ mockCreateAiSdkHookBridge.mock.results[0]!.value,
+ ]);
expect(tracePolicy).not.toHaveBeenCalled();
});
@@ -11103,7 +11226,14 @@ describe("createToolLoopHarness", () => {
});
const tracePolicy = vi.fn(() => true);
declareTelemetry({ recordInputs: true, recordOutputs: true, tracePolicy });
- const runStep = createToolLoopHarness(createTestConfig());
+ const runStep = createToolLoopHarness(
+ createTestConfig("conversation", undefined, {
+ instrumentation: {
+ hooks: createInstrumentationHooks([]),
+ runInContext: (_operation, execute) => execute(),
+ },
+ }),
+ );
const ctx = new ContextContainer();
ctx.set(SessionTraceSeedKey, {
spanId: "1".repeat(16),
@@ -11114,9 +11244,11 @@ describe("createToolLoopHarness", () => {
await contextStorage.run(ctx, () => runStep(createTestSession(), { message: "private" }));
const agentCall = vi.mocked(ToolLoopAgent).mock.calls[0]?.[0] as {
- telemetry?: unknown;
+ telemetry?: { integrations?: unknown[] };
};
- expect(agentCall.telemetry).toBeUndefined();
+ expect(agentCall.telemetry?.integrations).toEqual([
+ mockCreateAiSdkHookBridge.mock.results[0]!.value,
+ ]);
expect(tracePolicy).not.toHaveBeenCalled();
});
@@ -11184,7 +11316,10 @@ describe("createToolLoopHarness", () => {
expect(runtimeContext?.["eve.version"]).not.toBe("");
expect(runtimeContext?.["eve.session.id"]).toBe("test-session");
expect(agentCall?.telemetry?.isEnabled).toBe(true);
- expect(agentCall?.telemetry?.integrations).toBeUndefined();
+ expect(agentCall?.telemetry?.integrations).toEqual([]);
+ expect(mockGetRegisteredTelemetryIntegrations).toHaveBeenCalledWith({
+ sanitizeEveOtelErrors: true,
+ });
});
it("injects one provider-neutral bridge when lifecycle hooks opt in", async () => {
diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.ts
index e944cef85..b05b57227 100644
--- a/packages/eve/src/harness/tool-loop.ts
+++ b/packages/eve/src/harness/tool-loop.ts
@@ -154,11 +154,6 @@ import {
shouldPrepareApprovalPolicyTools,
} from "#harness/approval-delivery-coordinator.js";
import { buildTelemetryRuntimeContext } from "#harness/instrumentation/runtime-context.js";
-import {
- instrumentationHooksForDecision,
- instrumentationHooksForAudience,
- shouldCaptureInstrumentationContent,
-} from "#harness/instrumentation/content-policy.js";
import { createAiSdkHookBridge } from "#harness/ai-sdk-hook-bridge.js";
import {
createInstrumentationHandleEvent,
@@ -189,8 +184,12 @@ import {
import { getInstrumentationConfig } from "#harness/instrumentation/config.js";
import { getInstrumentationRuntime } from "#harness/instrumentation/runtime.js";
import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";
-import { applyAudienceCeiling } from "#shared/instrumentation-content.js";
+import {
+ applyAudienceCeiling,
+ shouldCaptureInstrumentationContent,
+} from "#shared/instrumentation-content.js";
import type { OtelHarnessSettings } from "#tracing/otel-declaration.js";
+import { readCurrentSessionTraceDecision } from "#tracing/agent-trace-context-store.js";
import {
isSampledTrace,
resolveTracePolicy,
@@ -346,9 +345,7 @@ function enrichTelemetry(
runtimeContext?: Readonly<Record<string, unknown>>,
bridgeIntegration?: Telemetry,
): TelemetryOptions | undefined {
- if (decision?.action === "drop") {
- return undefined;
- }
+ const dropsTrace = decision?.action === "drop";
if (settings === undefined && bridgeIntegration === undefined) {
return undefined;
}
@@ -362,6 +359,21 @@ function enrichTelemetry(
const effectiveDecision =
decision === undefined ? undefined : applyAudienceCeiling(decision, channelAudience);
+ const recordInputs =
+ !dropsTrace &&
+ (effectiveDecision?.action === "record"
+ ? effectiveDecision.recordInputs
+ : shouldCaptureInstrumentationContent(channelAudience)) &&
+ (settings?.recordInputs ?? false);
+ const recordOutputs =
+ !dropsTrace &&
+ (effectiveDecision?.action === "record"
+ ? effectiveDecision.recordOutputs
+ : shouldCaptureInstrumentationContent(channelAudience)) &&
+ (settings?.recordOutputs ?? false);
+ const sanitizeEveOtelErrors = settings !== undefined && !(recordInputs && recordOutputs);
+ const registeredIntegrations = () =>
+ getRegisteredTelemetryIntegrations({ sanitizeEveOtelErrors });
return {
functionId: settings?.functionId ?? agentName,
includeRuntimeContext,
@@ -369,19 +381,13 @@ function enrichTelemetry(
// bridge has to be composed with them rather than handed over on its own.
integrations:
bridgeIntegration === undefined
- ? undefined
- : [bridgeIntegration, ...getRegisteredTelemetryIntegrations()],
+ ? sanitizeEveOtelErrors
+ ? [...registeredIntegrations()]
+ : undefined
+ : [bridgeIntegration, ...registeredIntegrations()],
isEnabled: true,
- recordInputs:
- (effectiveDecision?.action === "record"
- ? effectiveDecision.recordInputs
- : shouldCaptureInstrumentationContent(channelAudience)) &&
- (settings?.recordInputs ?? false),
- recordOutputs:
- (effectiveDecision?.action === "record"
- ? effectiveDecision.recordOutputs
- : shouldCaptureInstrumentationContent(channelAudience)) &&
- (settings?.recordOutputs ?? false),
+ recordInputs,
+ recordOutputs,
};
}
@@ -627,7 +633,11 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
initialSession: Readonly<Parameters<StepFn>[0]>,
input?: StepInput,
): Promise<StepResult> {
- const instrumentationDecision = resolveStepInstrumentationDecision(otelSettings, agentName);
+ const instrumentationDecision = resolveStepInstrumentationDecision(
+ otelSettings,
+ agentName,
+ initialSession.sessionId,
+ );
// --- Turn span lifecycle ------------------------------------------------
// First step of a turn: open a new parent span. Continuation steps
@@ -689,14 +699,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
const store = contextStorage.getStore();
const channelInstrumentation = store?.get(ChannelInstrumentationKey);
const channelAudience = normalizeChannelAudience(channelInstrumentation?.metadata.audience);
- const instrumentationHooks =
- instrumentationDecision === undefined
- ? instrumentationHooksForAudience(config.instrumentation?.hooks, channelAudience)
- : instrumentationHooksForDecision(
- config.instrumentation?.hooks,
- instrumentationDecision,
- channelAudience,
- );
+ const instrumentationHooks = config.instrumentation?.hooks;
const parent = store?.get(ParentSessionKey);
const channel = store?.get(ChannelKey);
const callback = store?.get(SessionCallbackKey);
@@ -1570,9 +1573,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
};
activeAttemptScope = attemptScope;
const bridgeIntegration =
- instrumentationDecision?.action === "drop" ||
- attemptScope === undefined ||
- instrumentationHooks === undefined
+ attemptScope === undefined || instrumentationHooks === undefined
? undefined
: createAiSdkHookBridge(
attemptScope,
@@ -2061,18 +2062,23 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
function resolveStepInstrumentationDecision(
settings: OtelHarnessSettings | undefined,
agentName: string | undefined,
+ sessionId: string,
): InstrumentationDecision | undefined {
if (settings === undefined) return undefined;
const store = contextStorage.getStore();
const traceSeed = store?.get(SessionTraceSeedKey);
if (traceSeed?.decision !== undefined) return traceSeed.decision;
+ const persisted = readCurrentSessionTraceDecision(sessionId);
+ if (persisted !== undefined) return persisted;
const channel = store?.get(ChannelInstrumentationKey);
const audience = normalizeChannelAudience(channel?.metadata.audience);
if (traceSeed !== undefined) {
return resolveTracePolicyDecision(isSampledTrace(traceSeed), audience);
}
+ // The first step can reach this before OTel session preparation persists its
+ // decision, so that preparation may invoke the policy again.
return resolveTracePolicy(settings.tracePolicy, {
agentName,
audience,
diff --git a/packages/eve/src/tracing/agent-approval-instrumentation.ts b/packages/eve/src/tracing/agent-approval-instrumentation.ts
index 294ea6e17..f70f29aa9 100644
--- a/packages/eve/src/tracing/agent-approval-instrumentation.ts
+++ b/packages/eve/src/tracing/agent-approval-instrumentation.ts
@@ -43,8 +43,6 @@ export function createAgentApprovalInstrumentation(input: {
) => Promise<AgentActionContext | undefined>;
readonly frameworkVersion: string;
readonly idGenerator: AgentSpanIdGenerator;
- readonly recordInputs: boolean;
- readonly recordOutputs: boolean;
readonly tracer: Tracer;
}): Pick<
NonNullable<InstrumentationProviderDefinition["events"]>,
@@ -78,9 +76,7 @@ export function createAgentApprovalInstrumentation(input: {
stepIndex: event.scope.stepIndex,
turnId: event.scope.turnId,
};
- const requestAttribute = input.recordInputs
- ? contentAttribute(event.request, false)
- : undefined;
+ const requestAttribute = contentAttribute(event.request, false);
if (requestAttribute !== undefined) state["requestAttribute"] = requestAttribute;
ctx.state.set(state);
};
@@ -118,7 +114,7 @@ export function createAgentApprovalInstrumentation(input: {
if (state.requestAttribute !== undefined) {
span.setAttribute("agent.approval.request", state.requestAttribute);
}
- if (input.recordOutputs && event.response !== undefined) {
+ if (event.response !== undefined) {
const response = contentAttribute(event.response, false);
if (response !== undefined) span.setAttribute("agent.approval.response", response);
}
diff --git a/packages/eve/src/tracing/agent-otel-provider.test.ts b/packages/eve/src/tracing/agent-otel-provider.test.ts
index 4adae02eb..d169b788e 100644
--- a/packages/eve/src/tracing/agent-otel-provider.test.ts
+++ b/packages/eve/src/tracing/agent-otel-provider.test.ts
@@ -30,6 +30,7 @@ import {
type InstrumentationActionKind,
type InstrumentationAttemptScope,
type InstrumentationContextRunner,
+ type InstrumentationEvent,
type InstrumentationHooks,
type InstrumentationParentLineage,
type InstrumentationTraceContext,
@@ -54,13 +55,20 @@ interface TestRuntime {
typeof createAgentOtelInstrumentation
>["prepareSessionTrace"];
readonly prepareTurnTrace: ReturnType<typeof createAgentOtelInstrumentation>["prepareTurnTrace"];
+ readonly projectEvent: NonNullable<
+ ReturnType<typeof createAgentOtelInstrumentation>["hook"]["projectEvent"]
+ >;
readonly runInContext: InstrumentationContextRunner;
readonly tracer: ReturnType<BasicTracerProvider["getTracer"]>;
}
function createRuntime(
stateStore: AgentTraceStateStore = new InMemoryAgentTraceStateStore(),
- tracePolicy: TraceCapturePolicy | null = () => true,
+ tracePolicy: TraceCapturePolicy | null = () => ({
+ emit: true,
+ recordInputs: true,
+ recordOutputs: true,
+ }),
): TestRuntime {
const exporter = new InMemorySpanExporter();
const idGenerator = new AgentSpanIdGenerator();
@@ -87,6 +95,7 @@ function createRuntime(
hooks,
prepareSessionTrace: agentOtel.prepareSessionTrace,
prepareTurnTrace: agentOtel.prepareTurnTrace,
+ projectEvent: agentOtel.hook.projectEvent!,
provider,
runInContext: agentOtel.runInContext,
tracer,
@@ -116,7 +125,7 @@ async function emitAttempt(input: {
const scope: InstrumentationAttemptScope = {
attemptId: `${input.sessionId}:${input.turnId}:0:${input.attemptIndex ?? 0}`,
attemptIndex: input.attemptIndex ?? 0,
- channelAudience: input.channelAudience,
+ channelAudience: input.channelAudience ?? "public",
functionId: "weather",
sessionId: input.sessionId,
stepIndex: 0,
@@ -298,7 +307,7 @@ async function publishTurnStarted(input: {
const rootSessionId = input.rootSessionId ?? input.sessionId;
await input.hooks.publish({
agentName: "weather",
- channelAudience: input.channelAudience,
+ channelAudience: input.channelAudience ?? "public",
channelKind: "http",
idempotencyKey: sessionIdempotencyKey(input.sessionId),
parentTraceContext: input.parentTraceContext,
@@ -378,7 +387,11 @@ describe("createAgentOtelInstrumentation", () => {
const spans = runtime.exporter.getFinishedSpans();
const session = byName(spans, "agent.session")[0]!;
const turn = byName(spans, "agent.turn")[0]!;
- expect(session.spanContext()).toMatchObject(turnTrace);
+ expect(session.spanContext()).toMatchObject({
+ spanId: turnTrace.spanId,
+ traceFlags: turnTrace.traceFlags,
+ traceId: turnTrace.traceId,
+ });
expect(turn.spanContext().traceId).toBe(turnTrace.traceId);
expect(turn.parentSpanContext?.spanId).toBe(turnTrace.spanId);
});
@@ -574,6 +587,7 @@ describe("createAgentOtelInstrumentation", () => {
const started = {
agentName: "support",
delivery: {
+ channelAudience: "public" as const,
channelKind: "channel:slack",
channelName: "slack",
deliveryId: "delivery-1",
@@ -601,6 +615,7 @@ describe("createAgentOtelInstrumentation", () => {
await contextStorage.run(ctx, async () => {
await runtime.hooks.publish({
agentName: "support",
+ channelAudience: "public",
channelKind: "channel:slack",
idempotencyKey: sessionIdempotencyKey("session-1"),
rootSessionId: "session-1",
@@ -818,6 +833,61 @@ describe("createAgentOtelInstrumentation", () => {
},
);
+ it("uses the stored session decision when no event or context seed exists", async () => {
+ const stateStore = new InMemoryAgentTraceStateStore();
+ stateStore.setSession("session-policy", {
+ channelAudience: "public",
+ context: spanContext("1", "2"),
+ decision: { action: "record", recordInputs: false, recordOutputs: true },
+ rootSessionId: "session-policy",
+ });
+ const runtime = createRuntime(stateStore, null);
+
+ await expect(runtime.projectEvent(modelStartedEvent("session-policy"))).resolves.toMatchObject({
+ input: undefined,
+ });
+ });
+
+ it("reconstructs a sampled public session decision when persisted policy is absent", async () => {
+ const stateStore = new InMemoryAgentTraceStateStore();
+ stateStore.setSession("session-sampled", {
+ channelAudience: "public",
+ context: spanContext("1", "2"),
+ rootSessionId: "session-sampled",
+ });
+ const runtime = createRuntime(stateStore, null);
+
+ await expect(runtime.projectEvent(modelStartedEvent("session-sampled"))).resolves.toMatchObject(
+ {
+ input: { instructions: "private prompt" },
+ },
+ );
+ });
+
+ it("reconstructs an unsampled session as content-redacted", async () => {
+ const stateStore = new InMemoryAgentTraceStateStore();
+ stateStore.setSession("session-unsampled", {
+ channelAudience: "public",
+ context: { ...spanContext("1", "2"), traceFlags: 0 },
+ rootSessionId: "session-unsampled",
+ });
+ const runtime = createRuntime(stateStore, null);
+
+ await expect(
+ runtime.projectEvent(modelStartedEvent("session-unsampled")),
+ ).resolves.toMatchObject({ input: undefined });
+ });
+
+ it("fails closed when no trace decision source exists", async () => {
+ const runtime = createRuntime(new InMemoryAgentTraceStateStore(), null);
+
+ await expect(runtime.projectEvent(modelStartedEvent("session-missing"))).resolves.toMatchObject(
+ {
+ input: undefined,
+ },
+ );
+ });
+
it.each([
["legacy false", (): boolean => false],
["explicit emit false", (): { readonly emit: false } => ({ emit: false })],
@@ -977,6 +1047,7 @@ describe("createAgentOtelInstrumentation", () => {
const scope: InstrumentationAttemptScope = {
attemptId: "session-1:turn-1:0:0",
attemptIndex: 0,
+ channelAudience: "public",
sessionId: "session-1",
stepIndex: 0,
turnId: "turn-1",
@@ -1397,6 +1468,37 @@ describe("createAgentOtelInstrumentation", () => {
expect(action.attributes["gen_ai.tool.call.result"]).toContain("temperature");
});
+ it("applies trace content policy only to OTel spans", async () => {
+ const runtime = createRuntime(new InMemoryAgentTraceStateStore(), () => ({
+ emit: true,
+ recordInputs: false,
+ recordOutputs: false,
+ }));
+ await emitAttempt({
+ channelAudience: "public",
+ hooks: runtime.hooks,
+ runInContext: runtime.runInContext,
+ sessionId: "session-redacted",
+ turnId: "turn-redacted",
+ turnSequence: 0,
+ });
+ await runtime.provider.forceFlush();
+
+ const spans = runtime.exporter.getFinishedSpans();
+ expect(byName(spans, "chat claude-test")[0]?.attributes).not.toHaveProperty(
+ "gen_ai.input.messages",
+ );
+ expect(byName(spans, "chat claude-test")[0]?.attributes).not.toHaveProperty(
+ "gen_ai.output.messages",
+ );
+ expect(byName(spans, "ai.toolCall")[0]?.attributes).not.toHaveProperty(
+ "gen_ai.tool.call.arguments",
+ );
+ expect(byName(spans, "ai.toolCall")[0]?.attributes).not.toHaveProperty(
+ "gen_ai.tool.call.result",
+ );
+ });
+
it("caps full model input while keeping valid message JSON", async () => {
const runtime = createRuntime();
const manyMessages = Array.from({ length: 200 }, (_, index) => ({
@@ -1413,6 +1515,7 @@ describe("createAgentOtelInstrumentation", () => {
};
await runtime.hooks.publish({
agentName: "weather",
+ channelAudience: "public",
channelKind: "http",
idempotencyKey: sessionIdempotencyKey("session-1"),
rootSessionId: "session-1",
@@ -1878,6 +1981,29 @@ describe("createAgentOtelInstrumentation", () => {
});
});
+function spanContext(traceId: string, spanId: string) {
+ return { spanId: spanId.repeat(16), traceFlags: 1, traceId: traceId.repeat(32) };
+}
+
+function modelStartedEvent(
+ sessionId: string,
+): Extract<InstrumentationEvent, { type: "model.call.started" }> {
+ return {
+ idempotencyKey: `model:${sessionId}:turn-1:0:0:0`,
+ input: { instructions: "private prompt", messages: [] },
+ model: { modelId: "test-model", provider: "test-provider" },
+ scope: {
+ attemptId: `${sessionId}:turn-1:0:0`,
+ attemptIndex: 0,
+ channelAudience: "public",
+ sessionId,
+ stepIndex: 0,
+ turnId: "turn-1",
+ },
+ type: "model.call.started",
+ };
+}
+
describe("AgentSpanIdGenerator.withTraceId", () => {
it("primes the next generateTraceId call", () => {
const gen = new AgentSpanIdGenerator();
diff --git a/packages/eve/src/tracing/agent-otel-provider.ts b/packages/eve/src/tracing/agent-otel-provider.ts
index a618e9fe9..6f3f1c2f6 100644
--- a/packages/eve/src/tracing/agent-otel-provider.ts
+++ b/packages/eve/src/tracing/agent-otel-provider.ts
@@ -9,6 +9,10 @@ import {
trace,
} from "#compiled/@opentelemetry/api/index.js";
+import { contextStorage } from "#context/container.js";
+import { SessionTraceSeedKey } from "#context/keys.js";
+import { withoutInstrumentationContent } from "#harness/instrumentation/content.js";
+import { instrumentationEventForTraceDecision } from "#harness/instrumentation/content-policy.js";
import type { AgentTraceStateStore } from "#tracing/agent-trace-state.js";
import {
contentAttribute,
@@ -28,10 +32,12 @@ import { createAgentToolInstrumentation } from "#tracing/agent-tool-instrumentat
import { setAgentUsage } from "#tracing/agent-otel-usage.js";
import { createAgentOtelSessionContext } from "#tracing/agent-otel-session-context.js";
import type { TraceCapturePolicy } from "#tracing/otel-declaration.js";
-import { isSampledTrace } from "#tracing/sampled-trace.js";
+import { isSampledTrace, resolveTracePolicyDecision } from "#tracing/sampled-trace.js";
import { withChannelAudience } from "#tracing/channel-audience-context.js";
import { suppressTracing } from "#tracing/suppress-tracing.js";
+import { normalizeChannelAudience, type ChannelAudience } from "#shared/channel-audience.js";
import type {
+ InstrumentationEvent,
InstrumentationStepAttemptMetadataEvent,
InstrumentationAttemptScope,
InstrumentationStepAttemptStartedEvent,
@@ -41,7 +47,7 @@ import type {
InstrumentationModelCallStartedEvent,
InstrumentationProviderDefinition,
InstrumentationSessionStartedEvent,
- InstrumentationTraceContext,
+ InstrumentationTraceSeed,
InstrumentationSessionTransitionEvent,
InstrumentationTurnStartedEvent,
InstrumentationTurnTerminalEvent,
@@ -79,10 +85,10 @@ export interface AgentOtelInstrumentation {
readonly hook: InstrumentationProviderDefinition;
readonly prepareSessionTrace: (
event: InstrumentationSessionStartedEvent,
- ) => Promise<InstrumentationTraceContext>;
+ ) => Promise<InstrumentationTraceSeed>;
readonly prepareTurnTrace: (
event: InstrumentationTurnStartedEvent,
- ) => Promise<InstrumentationTraceContext>;
+ ) => Promise<InstrumentationTraceSeed>;
readonly runInContext: InstrumentationContextRunner;
}
@@ -115,8 +121,6 @@ export function createAgentOtelInstrumentation(
actionContextFor: actions.contextFor,
frameworkVersion: input.frameworkVersion,
idGenerator: input.idGenerator,
- recordInputs,
- recordOutputs,
tracer: input.tracer,
});
const tools = createAgentToolInstrumentation({
@@ -136,6 +140,36 @@ export function createAgentOtelInstrumentation(
const { ensureSessionContext, prepareSessionTrace, prepareTurnTrace } =
createAgentOtelSessionContext(input);
+ const projectEvent = async (event: InstrumentationEvent): Promise<InstrumentationEvent> => {
+ const session = await input.stateStore.getSession(sessionIdForEvent(event));
+ const audience = audienceForEvent(event, session?.channelAudience);
+ const eventSeed = "traceSeed" in event ? event.traceSeed : undefined;
+ const contextSeed = contextStorage.getStore()?.get(SessionTraceSeedKey);
+ const decision =
+ eventSeed?.decision ??
+ contextSeed?.decision ??
+ session?.decision ??
+ (eventSeed !== undefined
+ ? resolveTracePolicyDecision(isSampledTrace(eventSeed), audience)
+ : contextSeed !== undefined
+ ? resolveTracePolicyDecision(isSampledTrace(contextSeed), audience)
+ : session !== undefined
+ ? resolveTracePolicyDecision(isSampledTrace(session.context), audience)
+ : undefined);
+ if (decision === undefined) return withoutInstrumentationContent(event);
+ return instrumentationEventForTraceDecision(
+ event,
+ decision.action === "drop"
+ ? decision
+ : {
+ action: "record",
+ recordInputs: recordInputs && decision.recordInputs,
+ recordOutputs: recordOutputs && decision.recordOutputs,
+ },
+ audience,
+ );
+ };
+
const onSessionStarted = async (event: InstrumentationSessionStartedEvent): Promise<void> => {
await prepareSessionTrace(event);
};
@@ -350,7 +384,11 @@ export function createAgentOtelInstrumentation(
if (attempt !== undefined) setAgentUsage(attempt.step.span, event.usage);
if (recordOutputs) {
state.span.setAttribute("ai.response.finish_reason", event.finishReason);
- const content = event.content ?? [];
+ const content = event.content;
+ if (content === undefined) {
+ state.span.end();
+ return;
+ }
const outputMessages = genAiOutputMessagesAttribute(content, event.finishReason);
if (outputMessages !== undefined) {
state.span.setAttribute("gen_ai.output.messages", outputMessages);
@@ -461,6 +499,7 @@ export function createAgentOtelInstrumentation(
"turn.started": onTurnStarted,
},
name: "eve.otel",
+ projectEvent,
},
prepareSessionTrace,
prepareTurnTrace,
@@ -506,6 +545,24 @@ export function createAgentOtelInstrumentation(
}
}
+function sessionIdForEvent(event: InstrumentationEvent): string {
+ return "scope" in event ? event.scope.sessionId : event.sessionId;
+}
+
+function audienceForEvent(
+ event: InstrumentationEvent,
+ sessionAudience: ChannelAudience | undefined,
+): ChannelAudience {
+ if ("delivery" in event) return normalizeChannelAudience(event.delivery.channelAudience);
+ if ("scope" in event && event.scope.channelAudience !== undefined) {
+ return normalizeChannelAudience(event.scope.channelAudience);
+ }
+ if (event.type === "session.started") {
+ return normalizeChannelAudience(event.channelAudience);
+ }
+ return normalizeChannelAudience(sessionAudience);
+}
+
function getSpanStates<T>(
spans: WeakMap<InstrumentationAttemptScope, Map<string, T>>,
scope: InstrumentationAttemptScope,
diff --git a/packages/eve/src/tracing/agent-otel-session-context.ts b/packages/eve/src/tracing/agent-otel-session-context.ts
index 6f5c60889..92ac5b6bd 100644
--- a/packages/eve/src/tracing/agent-otel-session-context.ts
+++ b/packages/eve/src/tracing/agent-otel-session-context.ts
@@ -4,13 +4,18 @@ import {
sessionIdempotencyKey,
type InstrumentationSessionStartedEvent,
type InstrumentationTraceContext,
+ type InstrumentationTraceSeed,
type InstrumentationTurnStartedEvent,
} from "#harness/instrumentation/lifecycle.js";
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 { evaluateTracePolicy, isSampledTrace } from "#tracing/sampled-trace.js";
+import {
+ isSampledTrace,
+ resolveTracePolicy,
+ resolveTracePolicyDecision,
+} from "#tracing/sampled-trace.js";
import type { AgentSessionTraceState, AgentTraceStateStore } from "#tracing/agent-trace-state.js";
interface AgentOtelSessionContextInput {
@@ -27,10 +32,10 @@ interface AgentOtelSessionContext {
) => Promise<AgentSessionTraceState>;
readonly prepareSessionTrace: (
event: InstrumentationSessionStartedEvent,
- ) => Promise<InstrumentationTraceContext>;
+ ) => Promise<InstrumentationTraceSeed>;
readonly prepareTurnTrace: (
event: InstrumentationTurnStartedEvent,
- ) => Promise<InstrumentationTraceContext>;
+ ) => Promise<InstrumentationTraceSeed>;
}
export function createAgentOtelSessionContext(
@@ -42,6 +47,7 @@ export function createAgentOtelSessionContext(
readonly channelType?: string;
readonly rootSessionId: string;
readonly sessionId: string;
+ readonly traceDecision: ReturnType<typeof resolveTracePolicy>;
readonly traceSeed?: InstrumentationTraceContext;
}): SpanContext => {
if (session.traceSeed !== undefined) {
@@ -73,13 +79,7 @@ export function createAgentOtelSessionContext(
return span.spanContext();
}
// Fallback for already-running workflows that predate the seed.
- if (
- !evaluateTracePolicy(input.tracePolicy, {
- agentName: session.agentName,
- audience: session.channelAudience,
- channelType: session.channelType,
- })
- ) {
+ if (session.traceDecision.action === "drop") {
return {
isRemote: false,
spanId: input.idGenerator.deriveSpanId(`session:${session.sessionId}`),
@@ -108,18 +108,22 @@ export function createAgentOtelSessionContext(
): Promise<AgentSessionTraceState> => {
let state = await input.stateStore.getSession(event.sessionId);
if (state === undefined) {
+ const channelAudience = normalizeChannelAudience(event.channelAudience);
+ const decision = resolveSessionTraceDecision(event, channelAudience, input.tracePolicy);
state = {
agentName: event.agentName,
- channelAudience: normalizeChannelAudience(event.channelAudience),
+ channelAudience,
channelKind: event.channelKind,
+ decision,
context:
event.parentTraceContext === undefined
? openSessionTrace({
agentName: event.agentName,
- channelAudience: normalizeChannelAudience(event.channelAudience),
+ channelAudience,
channelType: event.channelType,
rootSessionId: event.rootSessionId,
sessionId: event.sessionId,
+ traceDecision: decision,
traceSeed: event.traceSeed,
})
: adoptedSpanContext(event.parentTraceContext),
@@ -132,16 +136,19 @@ export function createAgentOtelSessionContext(
const prepareSessionTrace = async (
event: InstrumentationSessionStartedEvent,
- ): Promise<InstrumentationTraceContext> => {
- return portableSpanContext((await ensureSessionContext(event)).context);
+ ): Promise<InstrumentationTraceSeed> => {
+ const session = await ensureSessionContext(event);
+ return portableSpanContext(session.context, session.decision);
};
const prepareTurnTrace = async (
event: InstrumentationTurnStartedEvent,
- ): Promise<InstrumentationTraceContext> => {
+ ): Promise<InstrumentationTraceSeed> => {
const prepared = await input.stateStore.getTurn(event.sessionId, event.turnId);
if (prepared !== undefined) {
+ const session = await input.stateStore.getSession(event.sessionId);
return {
+ decision: session?.decision,
spanId: prepared.parentSpanId,
traceFlags: prepared.context.traceFlags,
traceId: prepared.context.traceId,
@@ -176,14 +183,18 @@ export function createAgentOtelSessionContext(
startTimeMs: Date.now(),
subagentName: event.parentLineage?.subagentName,
});
- return portableSpanContext(session.context);
+ return portableSpanContext(session.context, session.decision);
};
return { ensureSessionContext, prepareSessionTrace, prepareTurnTrace };
}
-function portableSpanContext(spanContext: SpanContext): InstrumentationTraceContext {
+function portableSpanContext(
+ spanContext: SpanContext,
+ decision?: InstrumentationTraceSeed["decision"],
+): InstrumentationTraceSeed {
return {
+ decision,
spanId: spanContext.spanId,
traceFlags: spanContext.traceFlags,
traceId: spanContext.traceId,
@@ -198,3 +209,24 @@ function adoptedSpanContext(handed: InstrumentationTraceContext): SpanContext {
traceId: handed.traceId,
};
}
+
+function resolveSessionTraceDecision(
+ event: InstrumentationSessionStartedEvent,
+ audience: ChannelAudience,
+ policy: TraceCapturePolicy | undefined,
+): ReturnType<typeof resolveTracePolicy> {
+ if (event.traceSeed?.decision !== undefined) return event.traceSeed.decision;
+ if (event.traceSeed !== undefined) {
+ return resolveTracePolicyDecision(isSampledTrace(event.traceSeed), audience);
+ }
+ if (event.parentTraceContext !== undefined) {
+ return resolveTracePolicyDecision(isSampledTrace(event.parentTraceContext), audience);
+ }
+ // The tool loop can evaluate the same policy before this first-session
+ // preparation path; the persisted decision removes that window on replay.
+ return resolveTracePolicy(policy, {
+ agentName: event.agentName,
+ audience,
+ channelType: event.channelType,
+ });
+}
diff --git a/packages/eve/src/tracing/agent-trace-context-store.test.ts b/packages/eve/src/tracing/agent-trace-context-store.test.ts
index 48dd467dd..3a0ce1fae 100644
--- a/packages/eve/src/tracing/agent-trace-context-store.test.ts
+++ b/packages/eve/src/tracing/agent-trace-context-store.test.ts
@@ -7,6 +7,7 @@ import {
ContextAgentTraceStateStore,
preserveSerializedAgentTraceState,
readActionTraceContext,
+ readCurrentSessionTraceDecision,
readSessionTraceContext,
} from "#tracing/agent-trace-context-store.js";
@@ -116,6 +117,37 @@ describe("readSessionTraceContext", () => {
expect(readSessionTraceContext(serialized, "session-2")).toBeUndefined();
expect(readSessionTraceContext({}, "session-1")).toBeUndefined();
});
+
+ it("preserves a stored decision when the legacy context has no trace seed", async () => {
+ const context = new ContextContainer();
+ await contextStorage.run(context, () => {
+ new ContextAgentTraceStateStore().setSession("session-1", {
+ context: spanContext("1", "2"),
+ decision: { action: "record", recordInputs: false, recordOutputs: true },
+ rootSessionId: "session-1",
+ });
+ });
+
+ expect(readSessionTraceContext(await serializeContext(context), "session-1")).toEqual({
+ ...spanContext("1", "2"),
+ decision: { action: "record", recordInputs: false, recordOutputs: true },
+ });
+ });
+});
+
+describe("readCurrentSessionTraceDecision", () => {
+ it("reads the decision bound in the current worker context", async () => {
+ const context = new ContextContainer();
+ const decision = { action: "record", recordInputs: false, recordOutputs: true } as const;
+ await contextStorage.run(context, () => {
+ new ContextAgentTraceStateStore().setSession("session-1", {
+ context: spanContext("1", "2"),
+ decision,
+ rootSessionId: "session-1",
+ });
+ expect(readCurrentSessionTraceDecision("session-1")).toEqual(decision);
+ });
+ });
});
describe("readActionTraceContext", () => {
@@ -153,6 +185,37 @@ describe("readActionTraceContext", () => {
});
expect(readActionTraceContext(serialized, "session-1", "turn-1", "missing")).toBeUndefined();
});
+
+ it("propagates the stored session decision through an action context", async () => {
+ const context = new ContextContainer();
+ await contextStorage.run(context, () => {
+ const store = new ContextAgentTraceStateStore();
+ store.setSession("session-1", {
+ context: spanContext("1", "2"),
+ decision: { action: "record", recordInputs: true, recordOutputs: false },
+ rootSessionId: "session-1",
+ });
+ store.setAction("action-1", {
+ attemptIndex: 0,
+ callId: "call-1",
+ kind: "subagent-call",
+ name: "researcher",
+ parent: spanContext("1", "2"),
+ rootSessionId: "session-1",
+ sessionId: "session-1",
+ spanId: "3".repeat(16),
+ startTimeMs: 1_700_000_000_000,
+ stepIndex: 0,
+ turnId: "turn-1",
+ });
+ });
+
+ expect(
+ readActionTraceContext(await serializeContext(context), "session-1", "turn-1", "call-1"),
+ ).toMatchObject({
+ decision: { action: "record", recordInputs: true, recordOutputs: false },
+ });
+ });
});
function spanContext(traceId: string, spanId: string) {
diff --git a/packages/eve/src/tracing/agent-trace-context-store.ts b/packages/eve/src/tracing/agent-trace-context-store.ts
index 9ff9068e5..129ce34f7 100644
--- a/packages/eve/src/tracing/agent-trace-context-store.ts
+++ b/packages/eve/src/tracing/agent-trace-context-store.ts
@@ -11,6 +11,7 @@ import type {
AgentTurnTraceState,
} from "#tracing/agent-trace-state.js";
import { normalizeChannelAudience } from "#shared/channel-audience.js";
+import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";
interface AgentTraceContextState {
readonly actions: Readonly<Record<string, AgentActionTraceState>>;
@@ -25,6 +26,13 @@ const AgentTraceContextKey = new ContextKey<AgentTraceContextState>("eve.harness
},
});
+/** Reads the decision already bound to a session in the current worker context. */
+export function readCurrentSessionTraceDecision(
+ sessionId: string,
+): InstrumentationDecision | undefined {
+ return contextStorage.getStore()?.get(AgentTraceContextKey)?.sessions[sessionId]?.decision;
+}
+
/** Keeps only framework trace state from an interrupted step's context changes. */
export function preserveSerializedAgentTraceState(
original: Record<string, unknown>,
@@ -47,8 +55,10 @@ export function readSessionTraceContext(
): SessionTraceContext | undefined {
const raw = serializedContext[AgentTraceContextKey.name];
if (raw === undefined) return undefined;
- const context = deserializeState(raw).sessions[sessionId]?.context;
- return context === undefined ? undefined : withTraceDecision(serializedContext, context);
+ const session = deserializeState(raw).sessions[sessionId];
+ return session === undefined
+ ? undefined
+ : withTraceDecision(serializedContext, session.context, session.decision);
}
/** Reads the durable action span that should parent a dispatched child agent. */
@@ -60,24 +70,31 @@ export function readActionTraceContext(
): SessionTraceContext | undefined {
const raw = serializedContext[AgentTraceContextKey.name];
if (raw === undefined) return undefined;
- const action = Object.values(deserializeState(raw).actions).find(
+ const state = deserializeState(raw);
+ const action = Object.values(state.actions).find(
(state) => state.sessionId === sessionId && state.turnId === turnId && state.callId === callId,
);
if (action === undefined) return undefined;
- return withTraceDecision(serializedContext, {
- isRemote: false,
- spanId: action.spanId,
- traceFlags: action.parent.traceFlags,
- traceId: action.parent.traceId,
- });
+ return withTraceDecision(
+ serializedContext,
+ {
+ isRemote: false,
+ spanId: action.spanId,
+ traceFlags: action.parent.traceFlags,
+ traceId: action.parent.traceId,
+ },
+ state.sessions[action.sessionId]?.decision,
+ );
}
function withTraceDecision(
serializedContext: Readonly<Record<string, unknown>>,
context: SpanContext,
+ storedDecision?: InstrumentationDecision,
): SessionTraceContext {
const seed = serializedContext[SessionTraceSeedKey.name] as SessionTraceSeed | undefined;
- return seed?.decision === undefined ? context : { ...context, decision: seed.decision };
+ const decision = storedDecision ?? seed?.decision;
+ return decision === undefined ? context : { ...context, decision };
}
/** Durable trace state backed by eve's serialized Workflow context. */
@@ -205,6 +222,7 @@ function deserializeState(data: unknown): AgentTraceContextState {
channelAudience: normalizeChannelAudience(value.channelAudience),
channelKind: typeof value.channelKind === "string" ? value.channelKind : undefined,
context: value.context,
+ decision: deserializeInstrumentationDecision(value.decision),
rootSessionId: typeof value.rootSessionId === "string" ? value.rootSessionId : "",
} satisfies AgentSessionTraceState;
});
@@ -328,6 +346,20 @@ function isTurnTerminalType(
return value === "turn.cancelled" || value === "turn.completed" || value === "turn.failed";
}
+function deserializeInstrumentationDecision(value: unknown): InstrumentationDecision | undefined {
+ if (!isRecord(value)) return undefined;
+ if (value.action === "drop") return { action: "drop" };
+ return value.action === "record" &&
+ typeof value.recordInputs === "boolean" &&
+ typeof value.recordOutputs === "boolean"
+ ? {
+ action: "record",
+ recordInputs: value.recordInputs,
+ recordOutputs: value.recordOutputs,
+ }
+ : undefined;
+}
+
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
diff --git a/packages/eve/src/tracing/agent-trace-state.ts b/packages/eve/src/tracing/agent-trace-state.ts
index 3c58760c5..cbb7748e0 100644
--- a/packages/eve/src/tracing/agent-trace-state.ts
+++ b/packages/eve/src/tracing/agent-trace-state.ts
@@ -7,12 +7,14 @@ import type {
InstrumentationTurnSettledEvent,
} from "#harness/instrumentation/lifecycle.js";
import type { ChannelAudience } from "#shared/channel-audience.js";
+import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";
export interface AgentSessionTraceState {
readonly channelAudience?: ChannelAudience;
readonly agentName?: string;
readonly channelKind?: string;
readonly context: SpanContext;
+ readonly decision?: InstrumentationDecision;
readonly rootSessionId: string;
}
diff --git a/packages/eve/src/tracing/otel-declaration.ts b/packages/eve/src/tracing/otel-declaration.ts
index f8145138e..87339b02d 100644
--- a/packages/eve/src/tracing/otel-declaration.ts
+++ b/packages/eve/src/tracing/otel-declaration.ts
@@ -63,9 +63,13 @@ export interface OtelOptions {
* Process-wide trace and content decision. Boolean returns preserve the
* existing audience-aware behavior; explicit decisions can disable emission
* or select input and output capture independently. Defaults to emitting
- * every audience, with content only for public conversations. The result is a capture ceiling:
- * per-delivery audience and destination settings can only narrow it. A thrown
- * error rejects trace production without silencing lifecycle providers.
+ * every audience, with content only for public conversations. The result is
+ * an OpenTelemetry capture ceiling: per-delivery audience and destination
+ * settings can only narrow it. It never changes what authored instrumentation
+ * providers receive. A thrown error rejects trace production without
+ * silencing lifecycle providers. The policy may be invoked more than once
+ * while a new session is being prepared, so it must be deterministic for
+ * consistent results.
*/
readonly tracePolicy?: TraceCapturePolicy;
/**